Friday, October 16, 2015

Armstrong Number in C Programming.

Theory

Armstrong number: An n-digit number equal to the sum of the nth powers of its digits.


1. Raise each digit to a power equal to the number of digits in the number. 

     For instance, each digit of a four‑digit number would be raised to the fourth power; each digit of a five‑digit number would be raised to the fifth power; and so on.

2. Add the results.
3. If sum is equal to the number then it’s an Armstrong number.

Demonstrate this process for 1634—

         Because 1634 is a four-digit number, raise each digit to the fourth power, and add
14 + 64 + 34 + 44 = 1 + 1296 + 81 + 64 = 1634.
Hence 1634 is an Armstrong Number.

PROGRAM FOR ARMSTRONG NUMBER.

1.) Program for only 3 digit number

#include<stdio.h>

int main(){
    int num,r,sum=0,temp;

    printf("Enter a number: ");
    scanf("%d",&num);

    temp=num;
    while(num!=0){
         r=num%10;
         num=num/10;
         sum=sum+(r*r*r);
    }
    if(sum==temp)
         printf("%d is an Armstrong number",temp);
    else
         printf("%d is not an Armstrong number",temp);

    return 0;
}

Sample output:
Enter a number: 153
153 is an Armstrong number

2.) Program for any number of digits.

#include<stdio.h>
#include<Math.h>
#include<conio.h>

int main(){
    int num,r,t=0,sum=0,temp,count=0;

    printf("Enter a number: ");
    scanf("%d",&num);

    temp=num;
 while(temp>0){
  count++;
  temp = temp/10;
 }

 temp = num;

    while(num!=0){
         r=num%10;
         num=num/10;
    t=(int)pow((double) r, (double) count);
         sum=sum+t;
    }
    if(sum==temp)
         printf("%d is an Armstrong number",temp);
    else
         printf("%d is not an Armstrong number",temp);

 getch();
    return 0;
}
Sample output:
Enter a number: 1634
1634 is an Armstrong number


No comments:

Post a Comment