C++ Program to Check Armstrong Number

C++ProgrammingServer Side Programming

An Armstrong Number is a number where the sum of the digits raised to the power of total number of digits is equal to the number. Some examples of Armstrong numbers are as follows.

3 = 3^1
153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371
407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407

A program that checks whether a number is an Armstrong number or not is as follows.

Example

 Live Demo

#include <iostream>
#include <cmath<
using namespace std;
int main() {
   int num = 153, digitSum, temp, remainderNum, digitNum ;
   temp = num;
   digitNum = 0;
   while (temp != 0) {
      digitNum++;
      temp = temp/10;
   }
   temp = num;
   digitSum = 0;
   while (temp != 0) {
      remainderNum = temp%10;
      digitSum = digitSum + pow(remainderNum, digitNum);
      temp = temp/10;
   }
   if (num == digitSum)
   cout<<num<<" is an Armstrong number";
   else
   cout<<num<<" is not an Armstrong number";
   return 0;
}

Output

153 is an Armstrong number

In the above program, it is determined if the given number is an Armstrong number or not. This is done using multiple steps. First the number of digits in the number are found. This is done by adding one to digitNum for each digit.

This is demonstrated by the following code snippet −

temp = num;
digitNum = 0;
while (temp != 0) {
   digitNum++;
   temp = temp/10;
}

After the number of digits are known, digitSum is calculated by adding each digit raised to the power of digitNum i.e. number of digits. This can be seen in the following code snippet.

temp = num;
digitSum = 0;
while (temp != 0) {
   remainderNum = temp%10;
   digitSum = digitSum + pow(remainderNum, digitNum);
   temp = temp/10;
}

If the number is equal to the digitSum, then that number is an Armstrong number and that is printed. If not, then it is not an Armstrong number. This is seen in the below code snippet.

if (num == digitSum)
cout<<num<<" is an Armstrong number";
else
cout<<num<<" is not an Armstrong number";
raja
Published on 27-Sep-2018 11:44:39
Advertisements