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 find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala