×

Java Programs

Java Practice

Java program to check Armstrong number

In this example, we will read a positive integer number and check whether the entered number is an Armstrong number or not.

An Armstrong number is a number that is the sum of its digits each raised to the power of the number of digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.

Example:

Input:
153

Output:
Armstrong

Explanation:
153 = (1*1*1)+(5*5*5)+(3*3*3)  
153 = 1 + 125 + 27
153 = 153
Thus, 153 is an Armstrong number

Input:
371

Output:
Armstrong

Explanation:
371 = (3*3*3)+(7*7*7)+(1*1*1)  
371 = 27 + 343 + 1
371 = 371 
Thus, 371 is an Armstrong number

Program:

// Java program to check whether number is 
// armstrong or not

import java.util.*;

class DigitsOpr {
  private int num;

  //function to get value of num
  public void getNum(int x) {
    num = x;
  } //End of getNum()

  //function to check armstrong
  public boolean isArmstrong() {
    int n, sum, d;

    n = num; //keep value of num safe
    sum = 0;
    while (n > 0) {
      d = n % 10;
      sum += (d * d * d);
      n /= 10;
    }

    if (sum == num) return true;
    else return false;
  }
}

public class armstrong {
  public static void main(String[] s) {
    DigitsOpr dig = new DigitsOpr();
    int n;

    Scanner sc = new Scanner(System.in);

    //read number
    System.out.print("Enter a positive integer number: ");
    n = sc.nextInt();

    dig.getNum(n);
    if (dig.isArmstrong()) {
      System.out.println(n + " is an Armstrong number.");
    } else {
      System.out.println(n + " is not an Armstrong number.");
    }
  }
}

Output

RUN 1:
Enter a positive integer number: 153
153 is an Armstrong number.

RUN 2:
Enter a positive integer number: 407
407 is an Armstrong number.

RUN 3:
Enter a positive integer number: 417
417 is not an Armstrong number.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.