Page 199 - Cs_withBlue_J_C11_Flipbook
P. 199
Enter the ending value:
50
11 13 17 19 23 29 31 37 41 43 47
Program 9 A magic number is a number whose eventual sum of digits is equal to 1. Write a program in
Java to input a number and check whether it is a magic number or not.
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()
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:
Enter a number
2467
2467 is a magic number
197
Statements and Scope 197

