Programming Examples

Java program to input a number and check whether it is a magic number or no


Write a program to input a number and check whether it is a magic number or not. If you iterate the process of summing the squares of the decimal digits of the number, and if this process terminates in 1, then the original number is called a magic number. For example 55=> (5+5)=10=>(1 +0)=1.

Solution

import java.util.*;
class MagicNumber
{
	public static void main(String arr[])
	{
		Scanner sc=new Scanner(System.in);
		int n,i,s,d;
		System.out.println(“Enter a number:”);
		n=sc.nextInt();
		for(s=0;n>9;n=s,s=0)
		{
			for(i=n;i>0;i=i/10)
			{
				d=i%10;
				s+=d;
			}
		}
		if(n==1)
			System.out.println(“Magic Number”);
		else
			System.out.println(“Not a magic 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