C Programming Examples Tutorial Index

C Number Programs

This C tutorial helps you understand Armstrong numbers and how to write a C program to validate them. Here you will learn to verify whether the integer entered by the user is an Armstrong number or not.



What is an Armstrong Number?

An Armstrong number is a positive integer equal to the sum of all its digits raised to the power of the total count of digits.

To demonstrate this, let's take the number 370 as an example:

(3^3) + (7^3) + (0^3)
= (3 * 3 * 3) + (7 * 7 * 7) + (0 * 0 * 0)
= 27 + 343 + 0
= 370

This 370 is a three-digit number. If you raise each digit to a power of 3 (the total number of digits) and add them, you get the original number.

C Program to Check Armstrong Number

#include <stdio.h>
#include <math.h>

int main() {
    int number, originalNumber, lastDigit, sum = 0, digits = 0, temp;
    
    printf("Enter an integer: ");
    scanf("%d", &number);
    originalNumber = number;
    
    // Calculate the number of digits
    temp = number;
    while (temp != 0) {
        temp /= 10;
        digits++;
    }

    while (originalNumber != 0) {
        // lastDigit contains the last digit of the number
        lastDigit = originalNumber % 10;
        
        // raise the last digit to the power of digits and add it to the sum
        sum += pow(lastDigit, digits);
        
        // removing last digit from the original number
        originalNumber /= 10;
    }

    // Checking if the sum equals the original number
    if (sum == number)
        printf("%d is an Armstrong number.\n", number);
    else
        printf("%d is not an Armstrong number.\n", number);

    return 0;
}

Program Output:

Enter an integer: 55
55 is not an Armstrong number.
Enter an integer: 8208
8208 is an Armstrong number.

Program Explanation:

  1. The user is requested to enter an integer.
  2. The calculations are performed to determine the digit count of the input number.
  3. The program then goes into a loop where each digit is multiplied by the total number of digits and added to the sum.
  4. After processing all the digits, the sum is compared to the original number.
  5. The program prints that the input number is an Armstrong number if they are equal. If not, it prints that the input number is not an Armstrong number.


Found This Useful? Share This Page!