C Program to check the Number is Armstrong Number

In this tutorial, i am going to show you how to check the number is armstrong number in c program with the help of if else and function.

All C Programs to check the Number is Armstrong Number or Not

  • Algorithm to check for Armstrong number
  • C program to check a number is Armstrong number or not
  • C Program to check whether a number is Armstrong number or not using function

Algorithm to check for Armstrong number

Use the following algorithm to write a program for armstrong number:

  1. Take a number as input from user and store it in an integer variable.
  2. Find the cubic sum of digits of inputNumber, and store it in sum variable.
  3. Compare inputNumber and sum.
  4. If both are equal then input number is Armstrong number otherwise not an Armstrong number.

C program to check a number is Armstrong number or not

/*
* C Program to check whether a number is armstrong number or not
*/
#include <stdio.h>
 
int main(){
    int number, sum = 0, lastDigit, temp;
    printf("Enter a number : ");
    scanf("%d", &number);
    temp = number;
     
    while(temp != 0){
        lastDigit = temp%10;
        sum = sum + (lastDigit*lastDigit*lastDigit);
        temp = temp/10;
    }
     
    if(sum == number){
        printf("%d is Armstrong Number \n", number);
    } else {
        printf("%d is not an Armstrong Number \n", number);       
    }
    return 0;
}

The result of above c program; as follows:

Enter a number : 789
789 is not an Armstrong Number

C Program to check whether a number is Armstrong number or not using function

/*
* C Program to check whether a number is armstrong number or not
*/
#include <stdio.h>
 
int getCubicSumOfDigits(int number);
int main(){
    int number, sum;
    printf("Enter a number ");
    scanf("%d", &number);
     
    sum = getCubicSumOfDigits(number);
     
    if(sum == number){
        printf("%d is Armstrong Number \n", number);
    } else {
        printf("%d is not an Armstrong Number \n", number);       
    }
    return 0;
}
 
/*
 * Funtion to calculate the sum of cubes of digits of a number
 * getCubicSumOfDigits(123) = 1*1*1 + 2*2*2 + 3*3*3;
 */
int getCubicSumOfDigits(int number){
    int lastDigit, sum = 0;
    while(number != 0){
        lastDigit = number%10;
        sum = sum + lastDigit*lastDigit*lastDigit;
        number = number/10;
    }
    return sum;
}

The result of above c program; as follows:

Enter a number 153
153 is Armstrong Number 

More C Programming Tutorials

Leave a Comment