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

Armstrong Number Using Recursion

Download .java

Question

Accept a three-digit integer and check whether it is an Armstrong number using recursion.

Step 1: Start the program and accept a three-digit integer. Step 2: Store the entered number separately so that it can be compared later. Step 3: Call the recursive method to calculate the sum of the cubes of its digits. Step 4: If the number passed to the method is zero, return zero. Step 5: Otherwise extract the last digit using the remainder operator. Step 6: Calculate the cube of the extracted digit. Step 7: Call the method recursively with the remaining digits. Step 8: Add the cube to the value returned by the recursive call. Step 9: Return the total sum of digit cubes. Step 10: Compare the returned sum with the original number. Step 11: If both values are equal, display that it is an Armstrong number. Step 12: Otherwise display that it is not an Armstrong number. Step 13: Stop the program.
Java
import java.util.*;
class ArmstrongRecursion
{
    static int sumCubes(int n)
    {
        if (n == 0)
        {
            return 0;
        }
        int d = n % 10;
        return d * d * d + sumCubes(n / 10);
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a three-digit number: ");
        int n = sc.nextInt();
        if (n >= 100 && n <= 999 && sumCubes(n) == n)
        {
            System.out.println("Armstrong number");
        }
        else
        {
            System.out.println("Not an Armstrong number");
        }
    }
}
Input: Input: 153 Output: Armstrong number
← Previous Program 36 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.