Signup/Sign In
LAST UPDATED: OCTOBER 12, 2020

C++ Check whether the number is Armstrong or not

Hello Everyone!

In this tutorial, we will learn how to Check whether given number is Armstrong or not, in the C++ programming language.

What is an Armstrong number?

In number theory, an Armstrong number in a given number base is a number that is the sum of its own digits each raised to the power of the number of digits. (In programming, we usually define it for a 3 digit number)

Example:

153 is an Armstrong number as 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153. (same as the original number 153)

But, 213 is not an Armstrong number as 2^3 + 1^3 + 3^3 = 8 + 1 + 27 = 36 (which is not equal to the original number 213)

Code:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to check if the number is Armstrong or not ===== \n\n";

    //variable declaration
    int n, n1, remainder, num = 0;

    //taking input from the command line (user) all at once
    cout << " Enter a positive integer :  ";
    cin >> n;

    //storing the original value before modifying it
    n1=n;
    
   //Logic to check if it is Armstrong or not for a 3 digit number
    while( n1!=0 )
    {
        remainder = n1 % 10; //storing the digits at the units place
        num += remainder*remainder*remainder;
        n1/=10; 
    }
    cout << "\n\n\n";
    
    if(num == n)
    {
        cout << n << " is an Armstrong number.";
    }
    else
    {
        cout << n << " is not an Armstrong number.";
    }   
    cout << "\n\n\n";

    return 0;
}

Output:

C++ Armstrong number program output

Now let's see what we have done in the above program.

Program Explained:

Let's break down the parts of the code for better understanding.

//Logic to check if it is Armstrong or not for a 3 digit number
    while( n1!=0 )
    {
        remainder = n1 % 10; //storing the digits at the units place
        num += remainder*remainder*remainder;
        n1/=10;
    
    }

The above code snippet is used to check whther a given 3 digit number is Armstrong or not.

remainder = n1 % 10;

This is used to store the digit at the units place into the remainder variable.

num += remainder*remainder*remainder;

This statement is used to perfrom the cubing overation and adding onto the previous sum to find the final sum of the cubes of all the digits of the given 3 digit number.

n1/=10;

This statement, divides the actual number with 10 so that the new value contains only the digits that has not been explored yet.

We will recommend you to program this on your own and perform it's step-by-step analysis using pen-paper for the number 153, to develop better understanding.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.