C Program to Check Armstrong Number

Lets write a C program to check whether user entered number is Armstrong or not.

Armstrong number: is a number that is equal to the sum of cubes of its individual digits.

Example: If user input the number 371. It’s individual digits are 3, 7 and 1. Lets cube each digit: 33 + 73 + 13 = 27 + 343 + 1 = 371.

The user entered number 371 is equal to the sum of cube of its individual digits. So 371 is a Armstrong number.

Logic

If user enters number as 371.
1. Lets use modular division on that number.
371 % 10 = 1;
2. Lets cube the result(reminder) and store it inside a variable sum.
(1*1*1) = 1. So sum = 1.
3. Divide the number(371) by 10.
371 / 10 = 37. (Remember, when you divide a number by integer number, it returns only the integer part of the result).

Now, sum = 1, number = 37.

Lets repeat step 1, 2 and 3.
1. Lets use modular division on that number.
37 % 10 = 7;
2. Lets cube the result(reminder) and store it inside a variable sum.
(7*7*7) = 343. So sum = 1 + 343.
3. Divide the number(37) by 10.
37 / 10 = 3.

Now, sum = 344, number = 3.

Lets repeat the steps 1,2 and 3 one more time.
1. Lets use modular division on that number.
3 % 10 = 3;
2. Lets cube the result(reminder) and store it inside a variable sum.
(3*3*3) = 27. So sum = 344 + 27.
3. Divide the number(3) by 10.
3 / 10 = 0.

Now, sum = 371, number = 0;

Since number is 0, which means false, the while loop exits.

Next using if-else we check if the user entered number is equal to the sum of cubes of its individual digits.

Related Read:
C Program To Reverse a Number
Basic Arithmetic Operations In C
while loop in C programming
if else statement in C
Calculate Sum of Digits: C Program
C Program to print Armstrong Numbers between 1 and 500

C Program to Check Armstrong Number



YouTube Link: https://www.youtube.com/watch?v=wfhGh44CVhw [Watch the Video In Full Screen.]


Source Code: C Program to Check Armstrong Number

#include < stdio.h >

int main()
{
    int num, rem, sum = 0, temp;

    printf("Enter an integer number\n");
    scanf("%d", &num);

    temp = num;

    while(num)
    {
        rem = num % 10;
        sum = sum + (rem * rem * rem);
        num = num / 10;
    }

    if(temp == sum)
    {
        printf("%d is armstrong number\n", temp);
    }
    else
    {
        printf("%d is not armstrong number\n", temp);
    }

    return 0;
}

Output 1:
Enter an integer number
371
371 is armstrong number

Output 2:
Enter an integer number
563
563 is not armstrong number

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert