KnowledgeBoat Logo

Computer Applications

Write a program to input a three digit number. Use a method int Armstrong(int n) to accept the number. The method returns 1, if the number is Armstrong, otherwise zero(0).

Sample Input: 153
Sample Output: 153 ⇒ 13 + 53 + 33 = 153
It is an Armstrong Number.

Java

User Defined Methods

396 Likes

Answer

import java.util.Scanner;

public class KboatArmstrongNumber
{
    public int armstrong(int n) {
        
        int num = n, cubeSum = 0;   
        
        while (num > 0) {
            int digit = num % 10;
            cubeSum = cubeSum + (digit * digit * digit);
            num /= 10;
        }
        
        if (cubeSum == n)
            return 1;
        else
            return 0;
    }
    
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Number: ");
        int num = in.nextInt();
        
        KboatArmstrongNumber obj = new KboatArmstrongNumber();
        int r = obj.armstrong(num);
        
        if (r == 1)
            System.out.println(num + " is an Armstrong number");
        else
            System.out.println(num + " is not an Armstrong number");
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to input a number. Use a function int Armstrong(int n) to accept the number. The function returns 1, if the number is Armstrong, otherwise zero(0). Sample Input: 153 Sample Output: 153 ⇒ 1 3 + 5 3 + 3 3 = 153 It is an Armstrong Number.

Answered By

156 Likes


Related Questions