Perfect Square Check

Check whether a number is a perfect square using loops.

BeginnerTopic: Module 3: Loop Programs
Back

Java Perfect Square Check Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        boolean isPerfect = false;
        for (int i = 1; i * i <= n; i++) {
            if (i * i == n) {
                isPerfect = true;
                break;
            }
        }

        if (isPerfect) {
            System.out.println(n + " is a Perfect Square");
        } else {
            System.out.println(n + " is not a Perfect Square");
        }
        sc.close();
    }
}
Output
Enter a number: 49
49 is a Perfect Square

Understanding Perfect Square Check

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

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents