Programming Examples

Java program to input a number and check whether it is a happy number or not


Write a program to input a number and check whether it is a happy number or not. If you iterate the process of summing the squares of the decimal digits of a number and if this process terminates in 1, then the original number is called a happy number. For example 7=> (72)=49=> (42+92)=97=>(92 +72)=130 =>(12 +32+02)=10 =>(12+02)= 1.

Solution

import java.util.*;
class HappyNumber
{
	public static void main(int n)
	{
		Scanner sc=new Scanner(System.in);
		int d,s,n;
		System.out.println(“Enter a number:”);
		n=sc.nextInt();
		do
		{
			s=0;
			while(n>0)
			{
				d=n%10;
				s+=d*d;
				n/=10;
			}
			n=s;
		}while(n>9);
		if(n==1)
			System.out.println(“Happy Number”);
		else
			System.out.println(“Not a Happy Number”);
	}
}
Output

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz