KnowledgeBoat Logo

Computer Applications

Write a program to input a number and check whether it is 'Magic Number' or not. Display the message accordingly.
A number is said to be a magic number if the eventual sum of digits of the number is one.
Sample Input : 55
Then, 5 + 5 = 10, 1 + 0 = 1
Sample Output: Hence, 55 is a Magic Number.
Similarly, 289 is a Magic Number.

Java

Java Nested for Loops

121 Likes

Answer

import java.util.Scanner;

public class KboatMagicNum
{

    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter number to check: ");
        int num = in.nextInt();
        int n = num;

        while (n > 9) {
            int sum = 0;
            while (n != 0) {
                int d = n % 10;
                n /= 10;
                sum += d;
            }
            n = sum;
        }

        if (n == 1)
            System.out.println(num + " is Magic Number");
        else
            System.out.println(num + " is not Magic Number");

    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to input a number and check whether it is 'Magic Number' or not. Display the message accordingly. A number is said to be a magic number if the eventual sum of digits of the number is one. Sample Input : 55 Then, 5 + 5 = 10, 1 + 0 = 1 Sample Output: Hence, 55 is a Magic Number. Similarly, 289 is a Magic Number.

Answered By

41 Likes


Related Questions