Perfect Square Check in Java

Check whether a number is a perfect square using loops.

BeginnerModule 3: Loop ProgramsExample 23 of 25
perfect-square-check.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int n = sc.nextInt();
8
9 boolean isPerfect = false;
10 for (int i = 1; i * i <= n; i++) {
11 if (i * i == n) {
12 isPerfect = true;
13 break;
14 }
15 }
16
17 if (isPerfect) {
18 System.out.println(n + " is a Perfect Square");
19 } else {
20 System.out.println(n + " is not a Perfect Square");
21 }
22 sc.close();
23 }
24}

Output

Enter a number: 49
49 is a Perfect Square

What's going on

We square integers from 1 upward until the square reaches or exceeds n, and check equality.