C++ Program to Check Whether a Number is Armstrong or Not

In the previous article, we have discussed about C++ Program to Find LCM of Two Numbers. Let us learn how to Check Whether a Number is Armstrong or Not in C++ Program.

Method to Check Whether a Number is Armstrong or Not in C++

In this article, we discuss different methods to check whether a number is Armstrong or not. The methods that we will discuss are given below.

First, understand what an Armstrong number is. A positive integer is called an Armstrong number (of order n) where n is the number of digits in the number if abcd…….=a^n+b^n+c^n+d^n………  For example, suppose our number is 153 as it has 3 digits so it has order 3.Also 153=1^3+5^3+3^3. Hence 153 is an Armstrong number.

Let discuss different methods to check whether a number is Armstrong or not.

Method 1-Using loop and arithmetic operator

Here idea is to extract the digit of a number using modulo operator and after that add nth power of that digit in a result. We repeat this step until our number becomes 0. If the result is equal to the given number then the number is an Armstrong number else the number is not Armstrong. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int originalNum=153,temp,temp1,rem, result = 0,n;
    temp=originalNum;
    temp1=originalNum;
    
    // count number of digit in a number
     while (originalNum != 0) {
        originalNum /= 10;
        n++;
    }
    
    while (temp1!= 0) {
        rem = temp1% 10;
        result += pow(rem,n);
        temp1 /= 10;
    }

    if (result == temp)
        cout << temp << " is an Armstrong number.";
    else
        cout << temp << " is not an Armstrong number.";

    return 0;
}

Output

153 is an Armstrong number.

Method 2-Converting number to string

Here the step will be the same as method 1 but here the difference is that we will convert the number to a string. Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int originalNum=153,rem, result = 0,n,i;
    string str=to_string(originalNum);
    n=str.size();
    for(i=0;i<n;i++)
    {
        string s(1, str[i]);
        result+=pow(stoi(s),n);
    }
    if (result == originalNum)
        cout << originalNum << " is an Armstrong number.";
    else
        cout << originalNum << " is not an Armstrong number.";

    return 0;
}

Output

153 is an Armstrong number.

So these are the methods to check whether a number is an Armstrong number or not in c++.