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

Write a C program to enter any number from user and check whether the number is Armstrong number or not using for loop. C program for Armstrong number. How to check armstrong number in C programming using loops.

Input: 371
Output: Armstrong number

If interested also check this program using function - C program to check armstrong number using function.

Required knowledge

Basic C programming, For loop, If else

Armstrong number

Armstrong number is a special number whose sum of cube of its digits is equal to the original number. For example: 371 is an Armstrong number because
33 + 73 + 13 = 371

Logic to check armstrong number

Checking of armstrong number can be divided into basic three steps:
  1. Find last digit of the given number simply by performing modular division by 10. If you don't know how, check it here how to find last digit of any number.
  2. Find cube of the last digit just found and add it to a variable called sum.
  3. Repeat above two steps till the number becomes 0. And at the completion of the iteration check whether sum equals to original number or not. If it does then the given number is armstrong number otherwise not.

Program to check armstrong number

 * C Program to check whether a number is Armstrong number or not

#include <stdio.h>

int main()
    int n, num, lastDigit, sum = 0;

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

    /* Copies the original value of n to num */
    num = n;

     * Finds the sum of cubes of each digit of number
    while(n != 0)
        /* Finds last digit of number */
        lastDigit = n % 10; 
        /* Finds cube of last digit and adds to sum */
        sum += (lastDigit * lastDigit * lastDigit);

        n = n / 10;

    /* Checks if sum of cube of digits is equal to original value or not. */
    if(num == sum)
        printf("\n%d is Armstrong number.", num);
        printf("\n%d is not Armstrong number.", num);

    return 0;

Enter any number to check Armstrong number: 371

371 is Armstrong number.

Note: You can also compute cube of any number using pow() function.

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

1 comment: