Write a program to check whether the given number is a happy number or not
Answers
Here's your answer buddy
happy number:-
import java.util.*;
class Happy_Number
{
public static void main{
Scanner sc= new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
int sum = n;
int sum1 = 0;
int dig = 0;
while(sum > 0)
{
dig = sum%10;
sum1 = sum1+(dig*dig);
sum = sum/10;
}
sum = sum1;
dig = 0;
sum1 = 0;
}
if(sum == 1)
System.out.println("It is a Happy number");
else
System.out.println("It is not a Happy number");
}
}
this the entire code for happy number using scanner class. i have done by using while loop but you can use for loop too.
Required Program :-
import.java.util.scanner
class happy number
{
void main (int n )
{
int r , s ;
while (n ! = 0)
{
r = n % 10 ;
s = s + (r * r) ;
n = n / 10
}
n = s ;
}
if (n == 1)
System.out.println (" It is happy No. ") ;
System.out.println (" It is not a happy No. ");
}
Explaination :-
Line 1 : Util package and scanner class has been used.
Line 4 : Number (n) has been entered
Line 6 : r is remainder and s is sum. It has been used because we would be adding the numbers and division will be done.
Line 7 : While loop has been used.
Line 15 : Condition is being checked.
Line 16 : If the condition evaluates true then (" It is happy No. ") will be printed.
Line 17 : If the condition evaluates false then(" It is not a happy No. ") will be printed.
Example :
Let us take any number.
So we have decided to take 820 to check whether it is a happy number or not.
Adding the squares of 8 , 2 and 0.
=> 8² + 2² + 0²
=> 64 + 4 + 0
=> 64 + 4
=> 68
Again, now adding the squares of 6 and 8.
=> 6² + 8²
=> 36 + 64
=> 100
Taking squares of 1 , 0 and 0 and adding.
=> 1² + 0² + 0²
=> 1 + 0 + 0
=> 1
It proves that 820 is a happy number.