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

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare