PROGRAM
A Magic Number is a number in which the eventual sum of
digits of the number is equal to 1.
For example, 172=1+7+2=10
10=1+0=1
then 172 is a Magic Number.
Design a class Magic
to check if a given number is a magic number. Some of the members of the class
are given below:
Class Name : Magic
Data members/instance variables :
n :
stores the number
Member functions :
Magic() :
constructor to assign 0 to n
void getnum(int nn) :
to assign the parameter value to the number, n=nn
int Sum_of_digits(int) :
returns the sum of the digits of a number
void
ismagic() : checks if
the given number is a magic number by calling the function
Sum_of_digits(int) and display appropriate
message.
/**
* class magicnum checks whether a number is Magic Number or not.
* @author: Nitendra Verma
* @version: June 8,2013
*/
import java.util.Scanner;
public class Magic
{
int n,ntemp; //instace variable to store the number
public Magic() //default constructor, assigns 0 to n
{
n=0;
}
public void getnum(int nn) //metod, assigns the parameter value to the number
{
n=nn;
}
public int Sum_of_digits() //method, returns the sum of digits of number
{
int n1,r1,sum=0;
ntemp=n;
do //outer loop
{
sum=0;
do //inner loop
{
n1=n/10;
r1=n%10;
sum+=r1;
n=n1;
}
while(n1!=0);
n=sum;
}
while(sum>=10);
return sum; //returning sum
}
public void ismagic() //method, checks if the number is Magic Number
{
int sum=Sum_of_digits();
if(sum==1)
System.out.println(ntemp+" is a Magic Number");
else
System.out.println(ntemp+" is not a Magic Number");
}
public static void main()
{
Magic ob=new Magic(); //creating object of Magic class
Scanner in=new Scanner(System.in); //creating object of Scanner class
System.out.println("Enter a number");
int num=in.nextInt(); //inputting number
ob.getnum(num); //calling method
ob.ismagic(); //calling method
}
}
/*---------------Program developed by: Nitendra Verma---------------*/
//For more details visit http://javawithnitendra.blogspot.in
Enter a number
172
172 is a Magic Number
too long
ReplyDelete