FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Armstrong Number Program

noidatut course




An integer number is called Armstrong number if sum of the cubes of its digits is equal to the number itself. For example:

370 is an armstrong number because:

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

Example: Check Armstrong Number using For loop

#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.

You can also use while loop instead of for loop to check the Armstrong number:

Replace this part 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;
  }
Using While Loop
#include <iostream>  
using namespace std;    
int main() {
     int num, sum = 0, digit;
     cout<<"Enter a positive integer: ";
     cin>>num;
       int temp = num;
  while(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;
  }






Leave Comment