SnapTimes

News In A Snap!!

C++ Programs: Find an Armstrong Number

February 5, 2015

C++_Main

What is an Amstrong Number?

An Armstrong number is a number such that the sum of its digits raised to the third power is equal to the number itself. For example, 371 is an Armstrong number, since
3**3 + 7**3 + 1**3 = 371.

Code

// Program to find/generate Armstrong numbers

#include<iostream.h>
#include<conio.h>

int pow(int n, int power);
int digits(long int n);
int isArmstrong (int x);

int main () {
   clrscr();
   int min=0, max=1000;

   cout << "Program to find Armstrong numbers..." << endl;
   cout << "Enter a range for the Armstrong number..." << endl;

   cout << endl << "Enter lowest value to test: ";
   cin >> min;

   cout << endl << "Enter highest value to test: ";
   cin >> max;
   cout << endl;

   for (int i=min; i<=max; i++)
     if (isArmstrong(i))
       cout << i << endl;
       getch();
}

int isArmstrong (int x) {
   int n = x;
   int d = digits(x);

   int y=0, z=x;

   while (z>0) {
     x = z%10;
     y = y + pow(x, d);
     z /= 10;
   }

   if (y==n)
     return 1;

   else return 0;
}

int pow (int n, int power) {
   if (power == 1)
     return n;
   else
     return n * pow(n, power-1);
}

int digits(long int n) {
   if (n<10)
     return 1;
   else
     return 1+digits(n/10);
}

Output

armstrongsnumber


About the author: Prateek Kathal
22, Web Developer, CMS Manager, Blogger, Content-Writer, Foodie and Dog Lover, and TV Show Addict....

SnapTimes.in | Get Tech Addicted...
About Us | Contact Us | ©2017