C++ Program to Check if a Number Is an Armstrong Number

1. Introduction

An Armstrong number (also known as a narcissistic number or pluperfect digit) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For instance, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. 

In this article, we will guide you on how to write a C++ program that determines whether a given number is an Armstrong number or not.

2. Program Overview

Our Armstrong number-checking program will:

1. Prompt the user for a number.

2. Calculate the sum of its digits raised to the power of the number of digits.

3. Compare this sum with the original number.

4. Display whether the number is an Armstrong number.

3. Code Program

#include<iostream>
#include<cmath>
using namespace std;

bool isArmstrong(int num) {
    int originalNum, remainder, n = 0;
    double result = 0.0;

    originalNum = num;

    // Find the number of digits
    while (originalNum != 0) {
        originalNum /= 10;
        ++n;
    }

    originalNum = num;

    // Calculate the sum of the nth power of each digit
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }

    return int(result) == num;
}

int main() {
    int num;
    cout << "Enter an integer: ";
    cin >> num;

    if(isArmstrong(num))
        cout << num << " is an Armstrong number." << endl;
    else
        cout << num << " is not an Armstrong number." << endl;

    return 0;
}

Output:

Enter an integer: 153
153 is an Armstrong number.

4. Step By Step Explanation

1. We start by calculating the number of digits in the given number (n).

2. We then loop through the digits of the number and calculate the sum of the nth power of each digit.

3. The function isArmstrong returns true if the calculated sum is equal to the original number, indicating it's an Armstrong number.

4. The main function demonstrates how to use this function by prompting the user for input and displaying the result.

Comments