Armstrong Number

Program to check if a number is an Armstrong number

C++Intermediate
C++
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int num, original, remainder, result = 0, n = 0;
    
    cout << "Enter a number: ";
    cin >> num;
    
    original = num;
    
    // Count number of digits
    int temp = num;
    while (temp != 0) {
        temp /= 10;
        n++;
    }
    
    temp = num;
    // Calculate sum of digits raised to power n
    while (temp != 0) {
        remainder = temp % 10;
        result += pow(remainder, n);
        temp /= 10;
    }
    
    if (result == original) {
        cout << original << " is an Armstrong number" << endl;
    } else {
        cout << original << " is not an Armstrong number" << endl;
    }
    
    return 0;
}

Output

Enter a number: 153
153 is an Armstrong number

Armstrong Number in C++

This program checks whether a number is an Armstrong number (also called Narcissistic number). An Armstrong number is a number that equals the sum of its digits, each raised to the power of the number of digits. This program demonstrates digit extraction, counting digits, exponentiation, and accumulation patterns.

What is an Armstrong Number?

An Armstrong number is a number where the sum of its digits, each raised to the power of the number of digits, equals the number itself.

Mathematical definition:

For a number with n digits: If sum of (each digit^n) = the number, then it's an Armstrong number.

Examples:

153 (3 digits):

  • 1³ + 5³ + 3³ = 1 + 125 + 27 = ## 153 ✅
  • 153 is an Armstrong number

371 (3 digits):

  • 3³ + 7³ + 1³ = 27 + 343 + 1 = ## 371 ✅
  • 371 is an Armstrong number

123 (3 digits):

  • 1³ + 2³ + 3³ = 1 + 8 + 27 = ## 36 ❌
  • 36 ≠ 123, so 123 is NOT an Armstrong number

Algorithm

  1. Count the number of digits (n)
  2. Extract each digit
  3. Raise each digit to power n
  4. Sum all the results
  5. Compare sum with original number

Summary

  • Armstrong number: sum of (each digit^n) = the number itself
  • Algorithm: Count digits, then calculate sum of (digit^n)
  • Use pow() function for exponentiation
  • Compare result with original number
  • Two passes needed: first to count, second to calculate

This program teaches:

  • Digit extraction and counting
  • Exponentiation using pow()
  • Accumulation pattern
  • Two-pass algorithm design
  • Number manipulation techniques