Google News
logo
C++ Program to display Armstrong Numbers between 1 and 1000
In the following example of C++ program to display all the Armstrong numbers between 1 and 1000 :
Program :
#include <iostream>
#include <cmath>

int main() {
    int num, originalNum, remainder, result;
    std::cout << "Armstrong numbers between 1 and 1000 are: " << std::endl;
    for (int i = 1; i <= 1000; i++) {
        num = i;
        result = 0;
        originalNum = num;
        int n = 0;
        while (originalNum != 0) {
            originalNum /= 10;
            n++;
        }
        originalNum = num;
        while (originalNum != 0) {
            remainder = originalNum % 10;
            result += pow(remainder, n);
            originalNum /= 10;
        }
        if (result == num) {
            std::cout << num << std::endl;
        }
    }
    return 0;
}
Output :
Armstrong numbers between 1 and 1000 are: 
1
2
3
4
5
6
7
8
9
153
370
371
407
This program uses a for loop to iterate through all the numbers between 1 and 1000. For each number, the program calculates the sum of the cubes of its digits and compares it with the original number. If the two values are equal, then the number is an Armstrong number, and the program displays it to the console using std::cout.

* The program declares four variables: num, originalNum, remainder, and result. num stores the current number being checked for Armstrongness, originalNum stores the original value of num, remainder stores the remainder when originalNum is divided by 10, and result stores the sum of the cubes of the digits of num.

* The program calculates the number of digits in num using a while loop that divides originalNum by 10 and increments n until originalNum is 0. It then uses another while loop to calculate the sum of the cubes of the digits of num by repeatedly dividing originalNum by 10, calculating the cube of the remainder using the pow function from the cmath library, and adding the result to result.

* Finally, the program checks whether result is equal to num, and if so, it outputs num to the console using std::cout.