Program to check Armstrong number in c++

Introduction

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself.  For example, 407 is an Armstrong Number i.e. 4*4*4+0*0*0+7*7*7 = 407.

It becomes difficult to tell that the number is Armstrong number or not. So here is a program to check Armstrong number. First you should know about the logic behind the program to check Armstrong number.

Logic of the program

  • First the concept of Armstrong number should be clear to you.
  • arm,n are the variables where the number and result will be stored.
  • Store the number to check as Armstrong number in a variable.
  • Now,  take the mod of number with 10 and the remainder will be last digit and store the last digit in “arm” integer, for example 145Mod 10 = 5  and store the 5 in “arm” integer
  • Now, n/10 will give you the first digits, for example 145/10= 14.5  but 14 will be stored in “n” as it is an integer
  • Now multiply value in arm by 3 times and update “arm” variable and add the “arm ” in one variable “k”.
  • Repeat the steps until “n” becomes zero.
  • Now check if the final number generated is equal to the number stored earlier.
  • If the number is same then its an Armstrong number.

Source Code

The following is the program to check Armstrong number :

/*

    armstrong.cpp
    Program to check armstrong number in c++
    To compile (Need g++ compiler for unix/linux or Microsoft compiler for windows)
    g++ armstrong.cpp -o  armst
    To exectue.
    ./armst

    For windows
    c:\directory> cl -GX armstrong.cpp
*/
#include<iostream>
using namespace std;
int main()
{
   int arm=0,n=0,k=0,check;

cout<<"Enter a Number to check if it is armstrong number or not";
   cin>>n;
   check=n;

   for(int i=1;n!=0;i++){

       arm=n%10;
       n=n/10;

  arm=arm*arm*arm;
       k=k+arm;
   }

   if(k==check){
   cout<<check<<"  is an Armstrong Number";
   }
   else{
   cout<<check<<"  is not an Armstrong Number";

   }

   return 0;
}

Screenshots

This is a screenshot of a program to check Armstrong number i.e. 54321

program to check armstrong number

This Screenshot checks 407 is Armstrong number or not :

program to check armstrong number

What you Think? Share your Views