C++ Program to Check Armstrong Number

Write a C++ program that takes an integer as input from the user and determines whether it is an Armstrong number or not.
An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or plus perfect number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. 

Input and Output Examples

  1. Input: 153 Output: 153 is an Armstrong number.
  2. Input: 123 Output: 123 is not an Armstrong number.

Algorithm to check a number is Armstrong or not

  1. Prompt the user to input an integer.
  2. Calculate the sum of the digits raised to the power of the number of digits.
  3. Compare the result with the original number to determine if it's an Armstrong number.
  4. Display the result to the user.

Below is the C++ code to check if a number is an Armstrong number:

cpp
#include <iostream>
#include <cmath> // Include the cmath library for pow() function
using namespace std;

int main() {
    int num, originalNum, remainder, n = 0, result = 0;

    // Step 1: Prompt the user to input an integer
    cout << "Enter an integer: ";
    cin >> num;

    // Store the number in originalNum to later compare
    originalNum = num;

    // Step 2: Count the number of digits
    while (originalNum != 0) {
        originalNum /= 10;
        ++n;
    }

    // Reset originalNum to the original input value
    originalNum = num;

    // Step 3: Calculate the sum of the digits raised to the power of n
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }

    // Step 4: Compare the result with the original number
    if (result == num) {
        cout << num << " is an Armstrong number.";
    } else {
        cout << num << " is not an Armstrong number.";
    }

    return 0; // Indicates successful termination
}

Testing with Different Input Values

  1. Input: 9474 Output: 9474 is an Armstrong number.
  2. Input: 12345 Output: 12345 is not an Armstrong number.

Practice Problem

Write a C++ program to find all Armstrong numbers in a given range (e.g., between 100 and 1000).

Programming

4545

347

Related Articles