How to Check Amstrong Number in C Program

We are going to discuss here how to check the given number is either Armstrong number or not.

What is an Armstrong number?

An Armstrong number is n digit number that sum of its individual digit’s power n is equal to that number. For example, 370 is an Armstrong number because: (3)^3 + (7)^3 + (0)^3 = 370

Here we have taken power 3 because the number 370 is 3 digit number if we take 4 digits number of new power will be 4 to calculate. For example power for the number 1667 will be 4.

Program to check Armstrong number in C

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

void main()
{
int number, sum = 0, rem = 0, power = 0, temp, len_temp, len = 0;

printf ("Enter a number to check armstrong number: ");
scanf("%d", &number);
temp = number;
len_temp = temp;
while (len_temp != 0){
len_temp /= 10;
len++;
}
while (number != 0){
rem = number % 10;
power = pow(rem, len);
sum = sum + power;
number = number / 10;
}
if (sum == temp)
printf ("The given number is a valid armstrong number\n");
else
printf ("The given number is not a valid armstrong number\n");
printf("Please Enetr Any Key To Continue");
getch();
clrscr();
}

Explanation:

  • First, we get an integer number from the user and store it to the number variable.
  • Next, we count the length of that number.
  • After that, we create a while loop to find the sum of the power of each individual bit in the given number.
  • At last, we compare the sum with the given number and print the output.

This program works for a range of 1 to 1000. You can even explore more by taking a big integer.

I hope this post helps you out to understand Armstrong number and its implementation in C programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *