Program opened below. You can scroll through the algorithm, Java code and output.

Magic Number Using Recursion

Download .java

Question

Accept an integer and determine whether it is a magic number by repeatedly adding its digits using recursion.

Step 1: Start the program and accept a positive integer from the user. Step 2: Pass the number to the recursive digit-sum method. Step 3: In the method, check whether the number has become zero. Step 4: If it is zero, return zero as the base case. Step 5: Otherwise obtain the last digit using the remainder operator. Step 6: Call the method recursively with the number divided by ten. Step 7: Add the extracted digit to the value returned by the recursive call. Step 8: Return the resulting sum of digits to the calling statement. Step 9: Repeat the digit-sum process while the current sum has more than one digit. Step 10: Store the final single-digit sum. Step 11: If the final digit is one, classify the number as a magic number. Step 12: Otherwise classify it as not a magic number. Step 13: Display the result and stop.
Java
import java.util.*;
class MagicNumber
{
    static int digitSum(int n)
    {
        if (n == 0)
        {
            return 0;
        }
        return n % 10 + digitSum(n / 10);
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number: ");
        int n = sc.nextInt();
        int s = n;
        while (s > 9)
        {
            s = digitSum(s);
        }
        if (s == 1)
        {
            System.out.println("Magic number");
        }
        else
        {
            System.out.println("Not a magic number");
        }
    }
}
Input: Input: 19 Output: Magic number (1 + 9 = 10; 1 + 0 = 1)
← Previous Program 34 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.