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
- Java Program to Check Armstrong Number
- Java Program to Check Prime Number
- Java Program to Reverse a Number
- Java Program to Check if a Number is a Palindrome
- Java Program to Count the Number of Digits in an Integer
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment