In this tutorial you will learn about the Program to check Sunny Number in Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Sunny Numbers in Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Sunny Number.
Sunny number is a number,if next number to a given number is a perfect square.
For Example=> 80 is a Sunny Number because 81 is a perfect square of 9.
Program to check Sunny Number in Java
In this program we would find given number is a Sunny number or not .first of we would take a value from user and find the Sunny number.let have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// java program to find given number is a Sunny number or not.. import java.util.Scanner; public class Sunny { // Function to check the Sunny number public static boolean Sunny_no(int num) { if(Math.sqrt(num+1)%1 == 0) return true; else return false; } // main method public static void main(String[] args) { // declare variables and tale value from user. int number = 0; boolean result = false; Scanner scan = new Scanner(System.in); System.out.print("Enter any integer value"); number = scan.nextInt(); // check number is Sunny number or not result = Sunny_no(number); // display result if(result) System.out.println(number +" is a Sunny number."); else System.out.println(number +" is not a Sunny number."); } } |
Output
Sunny Number.
Not a Sunny Number.
In the above program, we have first declared and initialized a set variables required in the program.
- num,numberand= it will hold entered number.
- result it will hold result it means number is a sunny or not.
After that we take a number from user and find given number is a Sunny number or not
and pass this number to Sunny_no() function where we check condition for sunny number or we cans say condition for Perfect square where we add one to the number to check it is Sunny Number or not.
Function return value true if number is Perfect square
else return false and we will store the return value in variable result.
if value of result is true number is Sunny and if value of result if false number is not a Sunny number.