Coders Packet

Armstrong Number-C++

By Gokul S Nambiar

A C++ program to check whether a given integer of any size is an Armstrong number or not.

For a given number with number of digits n, it is called an Armstrong number if sum of each digit raised to n is equal to the number itself.

DESCRIPTION OF FUNCTIONS- 

 

1) digits(int x)- Returns the number of digits in the integer x. 

 

2) armstrong(int x)- Returns the result of sum of all digits raised individually to the number of digits. 

 

3) main() - Returns whether the integer is an Armstrong number or not 

 

#include 
#include 
using namespace std;

int digits(int x)
{
 int size = 0;
    while (x)
    {
        size++;
        x = x/10;
    }
    return size;	
}

int armstrong(int x)
{
int remainder,result=0,size=digits(x);
while (x != 0) {
        remainder = x % 10;
        
        result += pow(remainder,size);
        
        x /= 10;
    }	
return result;
}

void input(int &num)
{
  cout<<"Enter an integer-";
  cin>>num;
}

int main() {
    int num;
    input(num);
    if (armstrong(num) == num)
        cout << num << " is an Armstrong number.";
    else
        cout << num << " is not an Armstrong number.";

    return 0;
}

OUTPUT

 

Download project

Reviews Report

Submitted by Gokul S Nambiar (Gokul)

Download packets of source code on Coders Packet