This blog is under construction

Saturday 22 June 2013

C program to print Armstrong number from 1 to N

Write a C program to print Armstrong number from 1 to N.

A number is armstrong if the sum of each digit raised to the power of n(where 'n' represents number of digits in the given number) is equal to the number itself.


Example: check whether 153 is Armstrong or not.
No of digits in 153 is 3
1^3 + 5^3 + 3^3 = 153
So, 153 is an Armstrong number.



  #include <stdio.h>
  int main() {
        int n, res = 0, mod, data, temp, digits = 0, i;
        printf("Enter the value for n:");
        scanf("%d", &n);
        for (i = 1; i < n; i++) {
                data = temp = i;

                /* find number of digits in the input */
                while (data > 0) {
                        mod = data % 10;
                        data = data / 10;
                        digits++;
                }

                data = temp;

                /* sum of nth power of individual digits of a num */
                while (data > 0) {
                        mod = data % 10;
                        res = res + pow(mod, digits);
                        data = data / 10;
                }

                /* print armstrong number alone */
                if (res == temp)
                        printf("%6d\n", res);

                res = digits = 0;
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ gcc ex12.c -lm
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:99999
       1
       2
       3
       4
       5
       6
       7
       8
       9
     153
     370
     371
     407
    1634
    8208
    9474
   54748
   92727
   93084



No comments:

Post a Comment