Dremendo Tag Line

Input a number and check if it is an armstrong number or not using a function in Java

Function - Question 8

In this question, we will see how to input a number and check if it is an Armstrong number or not in Java programming using a function. To know more about function click on the function lesson.

Q8) Write a program in Java to input a number and check if it is an Armstrong number or not using a function. The function should return 1 if the numbers is an Armstrong number else return 0. An Armstrong number is a number whose sum of the cube of its digit is equal to the number itself.

Example 153 = 13+53+33

Program

import java.util.Scanner;

public class Q8
{
    public static int armstrong(int num)
    {
        int s=0,t,d;
        t=num;
        while(t>0)
        {
            d=t%10;
            s=s+(d*d*d);     // sum of cube of the digits
            t=t/10;
        }

        if(s==num)
        {
            return 1;
        }
        return 0;
    }

    public static void main(String args[])
    {
        int n;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a numbers ");
        n=sc.nextInt();

        if(armstrong(n)==1)
        {
            System.out.print("Armstrong Number");
        }
        else
        {
            System.out.print("Not Armstrong Number");
        }
    }
}

Output

Enter a number 153
Armstrong Number
video-poster