C program to check whether a number is armstrong number or not

Previous Program Next Program

Write a C program to enter any number from user and check whether given number is Armstrong number or not using for loop. C program for Armstrong number. Logic to check Armstrong numbers in C program.

Example

Input

Input number: 371

Output

371 is armstrong number

Required knowledge

Basic C programming, For loop, If else

What is Armstrong number?

An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits. Read more about Armstrong numbers. Below are few examples of Armstrong numbers:
6 = 61 = 6
371 = 33 + 73 + 13 = 371

Logic to check Armstrong number

There are three important concepts required for checking Armstrong number. That you must be strong in for before this program. The entire logic is based upon these three concepts.

Below is the step by step descriptive logic to check Armstrong number.

  1. Read number from user to be checked for Armstrong. Store it in some variable say num. Make a temporary copy of the value to some another variable for calculation purposes, say originalNum = num.
  2. Count total digits in the given number. Store it in some variable say digits.
  3. Initialize another variable to store the sum of power of its digits. Say sum = 0.
  4. Run a loop till num > 0. The loop structure should look like while(num > 0).
  5. Inside the loop extract the last digit of num. Store it in some variable say lastDigit = num % 10.
  6. Now comes the real calculation to find sum of power of digits. Perform sum = sum + pow(lastDigit, digits). Here pow(x, y) returns xy.
  7. Since the last digit of num is processed. Hence, remove last digit by performing num = num / 10. Repeat step 5-7 till num > 0.
  8. After loop according to definition if originalNum == sum, then it is Armstrong number otherwise not.

Program to check Armstrong number

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

int main()
{
    int originalNum, num, lastDigit, digits, sum;

    /*
     * Read number from user
     */
    printf("Enter any number to check Armstrong number: ");
    scanf("%d", &num);

    sum = 0;

    // Copy the value of num for processing
    originalNum = num;

    /*
     * Find total digits in num
     */
    digits = (int) log10(num) + 1;

    /*
     * Calculate sum of power of digits
     */
    while(num > 0)
    {
        // Extract the last digit
        lastDigit = num % 10;

        // Find sum
        sum = sum + round(pow(lastDigit, digits));

        // Remove the last digit
        num = num / 10;
    }

    // Check for Armstrong number
    if(originalNum == sum)
    {
        printf("%d is ARMSTRONG NUMBER", originalNum);
    }
    else
    {
        printf("%d is NOT ARMSTRONG NUMBER", originalNum);
    }

    return 0;
}
Output
Enter any number to check Armstrong number: 371
371 is ARMSTRONG NUMBER

Happy coding ;)

Recommended post

Previous Program Next Program

Labels: , ,