Here is a Java program to print all Armstrong numbers between 0 to N. In this Java program, given a number N we have to print all armstrong numbers between 0 and N. Here is a brief introduction of armstrong number. Here is the list of first few armstrong numbers 0, 1, 2, 3, 153, 370, 407 ...
153 = 1*1*1 + 5*5*5 + 3*3*3
115 is not an armstrong number
115 is not equal to 1*1*1 + 1*1*1 + 5*5*5
We have to find all armstrong numbers between 0 to N.
- Then using for loop we iterate from 0 till N.
- For any number i (0< i < N) find the cubic sum of digits of i, and store it in sum variable.
- Compare i and sum.
- If both are equal then i is an Armstrong number otherwise not an Armstrong number.
Java program to print all armstrong numbers between 0 to Numbers
In this java program, we first take N as input from user and then using a for loop iterate from 0 to N. Then we call "isArmstrongNumber" function for every number between 0 to N to check whether it is armstrong number or not. Function isArmstrongNumber takes an integer as input and returns "true" is it is armstrong number else return "false".
package com.tcc.java.programs;
import java.util.Scanner;
public class ArmstrongSeries {
public static void main(String[] args) {
double N;
int i;
Scanner scanner;
scanner = new Scanner(System.in);
System.out.println("Enter a Number");
N = scanner.nextFloat();
System.out.println("Armstrong Number between 0 to " + (int) N);
for (i = 0; i < N; i++) {
if (isArmstrongNumber(i)) {
System.out.println(i + " ");
}
}
}
public static boolean isArmstrongNumber(int num) {
int sum = 0, rightDigit, temp;
temp = num;
while (temp != 0) {
rightDigit = temp % 10;
sum = sum + (rightDigit * rightDigit * rightDigit);
temp = temp / 10;
}
if (sum == num) {
// N is armstrong number
return true;
} else {
// N is not an armstrong number
return false;
}
}
}
Output
Enter a Number 1000 Armstrong Number between 0 to 1000 0 1 153 370 371 407
Recommended Posts