;

Java Program to Display Armstrong Numbers Between Intervals Using Function


Tutorialsrack 10/07/2021 Java

In this java program, you’ll learn how to display an Armstrong number between two intervals such as 1 to 100 or 1 to nth using a function. In this program, we used the following java basics as for loop, while loop, and if..else condition.

Here is the code of the program to display an Armstrong number between two intervals using a function. 

Program - Java Program to Display Armstrong Numbers Between Intervals Using Function
//Java Program to Display Armstrong Numbers Between Intervals Using Function

import java.util.Scanner;

public class JavaPrograms {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter a Start Number: ");
		int low = sc.nextInt();

		System.out.println("Enter an End Number: ");
		int high = sc.nextInt();

		System.out.println("All Armstrong Number Between Intervals of " + low + " to " + high + " are:");

		for (int number = low + 1; number < high; ++number) {

			if (checkArmstrong(number))
				System.out.print(number + " ");
		}
	}

	public static boolean checkArmstrong(int num) {
		int digits = 0;
		int result = 0;
		int originalNumber = num;

		// number of digits calculation
		while (originalNumber != 0) {
			originalNumber /= 10;
			++digits;
		}

		originalNumber = num;

		// result contains sum of nth power of its digits
		while (originalNumber != 0) {
			int remainder = originalNumber % 10;
			result += Math.pow(remainder, digits);
			originalNumber /= 10;
		}

		if (result == num)
			return true;

		return false;
	}
}
Output

Enter a Start Number: 

1

Enter an End Number: 

9999

All Armstrong Number Between Intervals of 1 to 9999 are:

2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 


Related Posts



Comments

Recent Posts
Tags