You are here

C program to generate and print armstrong numbers

C program to generate Armstrong numbers. In our program, a user will input two integers, and we will print all Armstrong numbers between these two integers. Using a for loop we will check numbers in this range, in the loop, we call function check_armstrong which returns '1' if a number is Armstrong and '0' otherwise. If you are not familiar with Armstrong numbers see Check Armstrong number program.

C programming code

  1. #include <stdio.h>
  2.  
  3. int check_armstrong(int);
  4. int power(int, int);
  5.  
  6. int main () {
  7.    int c, a, b;
  8.    
  9.    printf("Input two integers\n");
  10.    scanf("%d%d", &a, &b);
  11.    
  12.    for (c = a; c <= b; c++) {
  13.       if (check_armstrong(c) == 1)
  14.          printf("%d\n", c);
  15.    }
  16.      
  17.    return 0;
  18. }
  19.  
  20. int check_armstrong(int n) {
  21.    long long sum = 0, temp;
  22.    int remainder, digits = 0;
  23.    
  24.    temp = n;
  25.  
  26.    while (temp != 0) {
  27.       digits++;
  28.       temp = temp/10;
  29.    }
  30.    
  31.    temp = n;
  32.    
  33.    while (temp != 0) {
  34.       remainder = temp%10;
  35.       sum = sum + power(remainder, digits);
  36.       temp = temp/10;
  37.    }
  38.  
  39.    if (n == sum)
  40.       return 1;
  41.    else
  42.       return 0;
  43. }
  44.  
  45. int  power(int n, int r) {
  46.    int c, p = 1;
  47.    
  48.    for (c = 1; c <= r; c++)
  49.       p = p*n;
  50.      
  51.    return p;  
  52. }

Output of the program (In the sample output, we are printing Armstrong numbers in the range [0, 1000000]):
C program output to generate Armstrong numbers

Download Generate Armstrong numbers program.