Page 223 - ComputerScience_Class_11
P. 223

Program 9      Write a program in Java to input a number and check whether it is a magic number or not.
                                 A magic number is a number whose eventual sum of digits is equal to 1.

                                 For example: 2467 = 2 + 4 + 6 + 7 = 19 = 1 + 9 = 10 = 1 + 0 = 1
                   1      import java.util.*;
                   2      class magic_number

                   3      {
                   4          public static void main(String args[])
                   5          {

                   6              Scanner sc= new Scanner(System.in);
                   7              int n, temp, s=0;

                   8              System.out.println("Enter a number ");
                   9              n=sc.nextInt();
                  10              temp=n;

                  11              while(temp>9)
                  12              {

                  13                 s=0;
                  14                 while(temp>0)
                  15                 {

                  16                     s= s+temp%10;
                  17                     temp=temp/10;
                  18                 }

                  19                 temp=s;
                  20              }
                  21              if(s==1)

                  22                  System.out.println(n+ " is a magic number ");
                  23              else

                  24                  System.out.println(n+ " is not a magic number ");
                  25          }
                  26      }


                 The output of the preceding program is as follows:

                       BlueJ: Terminal Window - Java
                   Options

                  Enter a number
                  2467
                  2467 is a magic number






                                                                                              Statements and Scope  221
   218   219   220   221   222   223   224   225   226   227   228