Monday , December 18 2017
Home / Blue J / Java program to print the magic number series

Java program to print the magic number series

This is a Java program to print the Magic number series. However before starting let me tell you what is a magic number.

A Magic number is a number whose sum of digits eventually leads to 1.
Example#1:  19 ;  1+9 =10 ; 1+0 = 1.  Hence a magic number.
Example#2:  224; 2+2+4=10; 1+0 =1.  Hence a magic number.
Example#3:  874; 8+7+4=19; 1+9=10; 1+0=1.  Hence a magic number.

ALSO CHECK:
1. 
Java program to check for a magic number
2. C program for magic number

import java.io.*;
class magic
{
public static void main(String args[])throws Exception
{
int i,j,k,n;
magic obj=new magic();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the upper limit to print the magic number series: ");  // i.e the value of n;
n=Integer.parseInt(br.readLine());
for(k=0;k<n;k++)
{i=k;
while((j=obj.magicno(i))/10!=0)       //   You have to check the sum of all digits until a single digit is achieved i.e. sum=1,2,3,..9
{
i=j;				// If sum of digits= 19 it then again goes to 1+9 =10 and again 1+0= '1' a single digit to check if 1 or not
}
if ( j==1)
System.out.print(k+",");
}
}

int magicno(int n)     // recursive program for magic number
{
if(n/10==0)
return n;
else
return n%10 + magicno(n/10);
}
}

OUTPUT:

Also See:   program for display lower triangular matrix in java
Java program to print magic number series
Java program to print magic number series

 

Check Also

Java program to implement polymorphism

Java program to implement polymorphism: Polymorphism is a technique in java with which you can ...