-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path039-Armstrong-Number.java
More file actions
82 lines (63 loc) · 2.48 KB
/
Copy path039-Armstrong-Number.java
File metadata and controls
82 lines (63 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* ============================================================================
* Program Name : Armstrong Number
* File Name : 039-Armstrong-Number.java
* Class Name : ArmstrongNumber
*
* Description:
* This program accepts an integer from the user and checks whether
* the given number is an Armstrong number or not using the while loop.
*
* Objective:
* - Understand user input using the Scanner class.
* - Learn how to use the while loop.
* - Calculate the sum of the cubes of the digits of a number.
* - Compare the calculated sum with the original number.
*
* Note:
* This program checks only 3-digit Armstrong numbers.
*
* Author : Shaik Mahaboob Basha
* Repository : 01-Core-Java
* Folder : 08-Java-Programs
* ============================================================================
*/
import java.util.Scanner;
public class ArmstrongNumber {
// The main() method is the entry point of every Java application.
public static void main(String[] args) {
// Create a Scanner object to read input from the keyboard.
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number.
System.out.print("Enter a Number: ");
// Read the number entered by the user.
int number = scanner.nextInt();
// Store the original number for comparison.
int originalNumber = number;
// Declare and initialize a variable to store the sum.
int sum = 0;
// Calculate the sum of the cubes of each digit.
while (number != 0) {
// Extract the last digit.
int digit = number % 10;
// Add the cube of the digit to the sum.
sum = sum + (digit * digit * digit);
// Remove the last digit from the number.
number = number / 10;
}
// Check whether the original number is equal to the calculated sum.
if (originalNumber == sum) {
// Display that the number is an Armstrong number.
System.out.println(originalNumber + " is an Armstrong Number.");
// Example Output:
// 153 is an Armstrong Number.
} else {
// Display that the number is not an Armstrong number.
System.out.println(originalNumber + " is Not an Armstrong Number.");
// Example Output:
// 123 is Not an Armstrong Number.
}
// Close the Scanner object to release system resources.
scanner.close();
}
}