C Program to check the given number is an Armstrong or not

Ans: 

In this tutorial, we are going to learn how to write a program in c to check a given input number is Armstrong or not?
So before moving directly on the writing program, I will recommend you please first know :

What is Armstrong Number?

  •  Armstrong Number is also known as narcissistic number.
  • A number which have n digits can be say that  Armstrong number if its sum of nth powers of its digits is equal to original number.
  • Like Armstrong number of 3 digits is a number which is equal to the sum of cube of its digits.
  • For eg: 153, 370 etc.

Example of Armstrong number

Lets see it practically by calculating it,

Suppose I am taking 153 for an example 

First calculate the cube of its each digits

  1^3 = (1*1*1) = 1

  5^3 = (5*5*5) = 125

  3^3= (3*3*3) = 27

Now add the cube 

  1+125+27 = 153

It means 153 is an Armstrong number.

Ok, Then move on the program where your concept will be cleared 🙂

C Program to check a number is Armstrong or not

#include<stdio.h>
#include<math.h>
#include<conio.h>
void main(){
	int number,i=0,n,result=0,number1,temp;
	printf("enter the number:");
	scanf("%d",&number);
	number1=number;
	temp=number;
	while(number!=0){
		number=number/10;
		i++;
	}

	while(number1!=0){
		n=number1%10;
		result=result+pow(n,i);
		number1=number1/10;
		}

	if(temp==result)
		printf("number is armstrong");
		else
		printf("not a armstrong");
	getch();

} 

Output:

c-program-to-check-number-is-armstrong-or-not

Explanation of Armstrong number validating program in c

  • In the above program, you can see that I have Math.h header file because We need pow() function to calculate power and this function is defined in Math.h header file.
  • Here I have taken almost six variable because in most of cases, we need to persist the previous value for the validation purpose.
  • So first, I have taken input from the user and stored it in the ‘number’ variable.
  • Now again, I am assigning the same variable in the ‘temp’ and ‘number1’ variable.
  • First, while a loop is used to calculate the count of digits in a given number, we will use this count to calculate the power of each digit.
  • And Second While loop is responsible for calculating the power of each digit and adding them together.
  • Now, at last, we have if statement which I have used to validate our result after the performing operations.
  • Using this if statement we are validating our original number(stored in ‘temp’ variable) is equal or not to calculated result ( stored in ‘result’ variable). 
  • Its value of temp and result is equal. It means that number is an Armstrong, and if not equal, then it is not an Armstrong number.

I hope now you have an idea of how to calculate and write a program to check number is an Armstrong or not in C.