C++ Program to Display Armstrong Numbers Between 1 to 1000

14/04/2024 0 By indiafreenotes

Displaying Armstrong numbers within a specific range, such as from 1 to 1000, is a common programming task that showcases the application of loops, conditionals, and arithmetic operations in C++. Armstrong numbers, as previously discussed, are numbers that equal the sum of their own digits each raised to the power of the number of digits in the number. This property makes them particularly interesting from both mathematical and programming perspectives.

To create a program that identifies and displays Armstrong numbers within a given range, the steps are as follows:

  1. Loop through the Range:

Iterate over each number in the specified range (1 to 1000 in this case).

  1. Check for Armstrong Number:

For each number, determine if it is an Armstrong number.

  1. Display the Number:

If a number is identified as an Armstrong number, display it.

This process requires a function to check if a given number is an Armstrong number, similar to what was outlined previously.

C++ Program

 

#include <iostream>

#include <cmath>

using namespace std;

// Function to calculate the number of digits in a number

int countDigits(int n) {

    int count = 0;

    while (n != 0) {

        count++;

        n /= 10;

    }

    return count;

}

// Function to check if a number is an Armstrong number

bool isArmstrong(int num) {

    int originalNum = num;

    int numOfDigits = countDigits(num);

    int sumOfPowers = 0;

    while (num != 0) {

        int digit = num % 10;

        sumOfPowers += pow(digit, numOfDigits);

        num /= 10;

    }

    return sumOfPowers == originalNum;

}

int main() {

    cout << “Armstrong numbers between 1 to 1000 are:” << endl;

    for (int num = 1; num <= 1000; num++) {

        if (isArmstrong(num)) {

            cout << num << endl;

        }

    }

    return 0;

}

 

Explanation

  1. Counting Digits (countDigits function):

This function, as before, calculates the number of digits in a given number. This is crucial for determining the power to which each digit should be raised.

  1. Armstrong Number Check (isArmstrong function):

This function determines if a given number is an Armstrong number by comparing it to the sum of its digits each raised to the power of the number of digits in the number.

  1. Main Logic:

The main function iterates through numbers from 1 to 1000, utilizing the isArmstrong function to check for Armstrong numbers. When an Armstrong number is found, it is printed out.