Write a C program to check whether a number is an Armstrong number

Description: Take a 3 digit number as input. Print if it is an Armstrong number. For example, 153 is, because 13 + 53 + 33 = 153.

Hint:

  • Take each digit with % 10, add its cube to a sum, and compare the sum with the original number.

C program to check an Armstrong number

#include <stdio.h>

int main(void) {
    int n, original, digit, sum = 0;

    printf("Enter a 3 digit number: ");
    scanf("%d", &n);
    original = n;

    while (n > 0) {
        digit = n % 10;
        sum += digit * digit * digit;
        n /= 10;
    }

    if (sum == original) {
        printf("%d is an Armstrong number\n", original);
    } else {
        printf("%d is not an Armstrong number\n", original);
    }
    return 0;
}

Output:

Output of the above program is

Enter a 3 digit number: 153
153 is an Armstrong number

How it works

  • The digits of 153 are 3, 5 and 1. Their cubes are 27, 125 and 1, and the sum is 153.
  • For numbers with a different count of digits, the power is the count of digits, not 3.

Learn more about the similar topics:
Tutorials
C If Else Statement
C Else If Ladder and Nested If
C Switch Statement
C While Loop
C Do While Loop
C For Loop
C Nested Loops
Exercises & Assignments
Write a C program to check whether a number is even or odd
Write a C program to check whether a user is eligible to vote or not
Write a C program to check whether an alphabet is vowel or consonant
Write a C program to find the maximum number between three numbers
Write a C program to check whether a number is positive, negative or zero
Write a C program to calculate an electricity bill
Write a C program to print 1 to 10 numbers using a while loop
Interview Questions & Answers
What is the difference between while and do while loop in C?
What is the difference between break and continue in C?
How to check if a number is prime in C?
How to find the factorial of a number in C?