C Program to Generate Armstrong Numbers

Here is a C program to generate armstrong numbers. A number is called an Armstrong number if the sum of cubes of every digit is equal to the number itself. Given a number N, we have to generate a list of all Armstrong numbers between 0 and N.

For Example
407 is an Armstrong number
407 = 4*4*4 + 0*0*0 + 7*7*7

121 is not an Armstrong number
121 is not equal to 1*1*1 + 2*2*2 + 1*1*1
Examples of Armstrong Numbers : 0, 1, 2, 3, 153, 370, 407 etc.

Algorithm to Generate Armstrong number
  1. Take a number as input from user and store it in number variable.
  2. Then using for loop we iterate from 0 till N using a counter variable.
  3. Find the cubic sum of digits of counter, and store it in sum variable.
  4. Compare counter and sum.
  5. If both are equal then current number(counter) is Armstrong number otherwise not an Armstrong number.

C program to generate armstrong numbers between 0 and N

This program first takes a number as input from user using scanf function and stores it in variable 'number'. Then using a for loop, it perform armstrong number check for every number from 0 to 'number'. It calculates the cube of every digit of counter using getCubicSumOfDigits function and stores in a 'sum' variable. If sum is equal to number then it is an Armstrong number otherwise not an Armstrong number.

#include <stdio.h>

int getCubicSumOfDigits(int number);
int main(){
    int number, sum, counter;
    printf("Enter a number : ");
    scanf("%d", &number);
    
    for(counter = 0; counter <= number; counter++){
        sum = getCubicSumOfDigits(counter);
        if(sum == counter){
            printf("%d\n", counter);
        }
    }
    return 0;
}

int getCubicSumOfDigits(int number){
    int lastDigit, sum = 0;
    while(number != 0){
        lastDigit = number%10;
        sum = sum + lastDigit*lastDigit*lastDigit;
        number = number/10;
    }
    return sum;
}
Output
Enter a number : 10000
0
1
153
370
371
407

Related Topics
C program to check armstrong number
C program to check a number is palindrome or not
C program to calculate power of a number
C program to check if two strings are anagram
C program to reverse a number
C program to find hcf and lcm of two numbers
C program to convert string to integer
List of all C programs