Armstrong Number Program in C

To check if given number n is Armstrong Number in C programming, find the sum of cubes of individual digits in given number, and check if the sum equals the given number.

C Program

In the following program, we read a number to n from user via console input, and check if this number is Armstrong Number or not.

main.c

#include <stdio.h>

int main() {
    int n;
    printf("Enter a number : ");
    scanf("%d", &n);
    
    int sum = 0;
    int digit;
    int temp = n;
    while (temp > 0) {
        digit = temp % 10;
        sum = sum + (digit * digit * digit);
        temp = temp / 10;
    }
    
    if (sum == n) {
        printf("%d is an Armstrong Number.\n", n);
    } else {
        printf("%d is not an Armstrong Number.\n", n);
    }
}

Output

Enter a number : 371
371 is an Armstrong Number.
Program ended with exit code: 0

Output

Enter a number : 23
23 is not an Armstrong Number.
Program ended with exit code: 0

We have used C While Loop for iteration, and C If-Else statement for decision making.

ADVERTISEMENT

Conclusion

In this C Tutorial, we learned how to check if given number is an Armstrong Number, with example.