Java Program to Check if a Given Number is Perfect Square - The Coding Shala

Home >> Java Programs >> Check Perfect Square Number

 Hey there, welcome back to another post. In this post, we are going to learn how to check if a given number is a perfect square or not without using sqrt in Java.

Java Program to Check if a Given Number is Perfect Square

Write a Java Program to check if the given number is a perfect square or not. 

Example 1: 

Input: 36
Output: Yes
Explanation: 
6 * 6 = 36 

Solution

Using for loop,  we will check if the current element is the square root of the given number or not.

Condition: i * i = number

Java Program:  

/**
 * https://www.thecodingshala.com/
 */

import java.util.*;

public class Main {

    public static boolean isPerfectSquare(int n) {
        for (int i = 1; i * i <= n; i++) {
            if (i * i == n) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");
        int n = sc.nextInt();
        if (isPerfectSquare(n)) {
            System.out.println(n + " is a perfect square number");
        } else {
            System.out.println(n + " is not a perfect square number");
        }
    }
}

Output: 

Enter a number:
361
361 is a perfect square number


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala