C++

Armstrong Number Checker In C++- Detailed FAQ

If the total of the cubes of an integer number’s digits equals the number itself, the number is said to be an Armstrong number. For instance:
The reason 370 is an armstrong number is

370 = 3*3*3 + 7*7*7 + 0*0*0
    = 27 + 343 + 0
    = 370

Example: Using the For loop, check the Armstrong Number.

For loops and if-else statements should be familiar to you in order to comprehend this program.

#include <iostream>
using namespace std;

int main() {
   int num, sum = 0, digit;
   cout<<"Enter a positive integer: ";
   cin>>num;

   for(int temp=num; temp!=0;){
      digit = temp % 10;
      sum = sum +(digit * digit * digit);
      temp = temp/10;
   }

   if(sum == num)
      cout<<num<<" is an Armstrong number.";
   else
      cout<<num<<" is not an Armstrong number.";

   return 0;
}

Output:

Enter a positive  integer: 370
370 is an Armstrong number.

As an alternative to the for loop, the while loop can be used to check the Armstrong number:
Change this section of the code:

for(int temp=num; temp!=0;){
    digit = temp % 10;
    sum = sum +(digit * digit * digit);
    temp = temp/10;
}

with this:

int temp = num;
while(temp != 0)
{
   digit = temp % 10;
   sum = sum +(digit * digit * digit);
   temp = temp/10;
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button