Armstrong Number Program in C Language
C Program to check if the given number is Armstrong number.
What is Armstrong Number:
An Armstrong number of an integer such that the sum of the cubes of its digits is equal to the number itself.
Lets look at couple of examples
Number 371 is an Armstrong number
since 3^3 + 7^3 + 1^3 = 371
Number 153 is also a Armstrong number
since 1^3 + 5^3 + 3^3 = 153
Armstrong number Program Algorithm:
We need to get each digit and then calculate the cubes of each digit. Then add all cubes which should be equal to the given number. If the cubes are equal to the given number then it’s an Armstrong number. Otherwise, it is not.
Here is the flow of execution.
- We are going to use an extra variable temp to hold the input number n. As we need 'n' to verify our result.
- We are going to use the Modulus operator to get the last digit of the number, We can get the last digit of any number by performing the
- For example, 8798 % 10 = 8
- Once we get the last digit, calculate the cube of the digit. Then add to arm variable. arm variable is initialised with zero at the start. and we will add the cubes of each digit to the arm variable.
- We can remove the last digit of any number by diving the number by 10. As we already calculated the cube of the last digit we no longer need it. So we will remove the last digit by dividing the number with 10.
We are going to repeat above steps from 2 to 4 until the temp becomes less than 0. So at each iteration we are going to get one digit and then calculate the cube of that digit, Add to the ‘arm’ variable. Then remove that digit from the number. So once we pass through the all numbers the ‘temp’ will becomes less than zero. And our loop will be terminated.
Once we are out of the loop, We are going to check the 'arm' variable value with the input number 'n'. If both 'arm' value and 'n' are equal then the given number ‘n’ is Armstrong number. If the numbers are not equal then 'n' is not an Armstrong number.
Program: To check or detect Armstrong number :
arm = 0;
printf("Enter no : ");
temp = n;
// Go through the each digit and calculate the cube of each digit
// add the cubes to 'arm' variable. which will be holding sum of all cubes
rem = temp %10;
arm = arm + (rem*rem*rem);
temp = temp/10;
// After all iterations, The 'arm' variable contains the sum of cubes of each digit.
// if 'arm' is equal to the input number 'n', Then the 'n' is Armstrong number.
if(arm == n)
printf("Given Number %d is Armstrong Number \n", n);
printf("Not Armstrong Number\n");
// Compile the program using the gcc
$ gcc armStrong.c
// Run the executable file (./a.out in Linux) or ( .exe in windows )
Enter no : 153
Given Number 153 is Armstrong Number
Enter no : 432
Not Armstrong Number
Enter no : 765
Not Armstrong Number
- C Program to find sum of digits of a Number | Sum of Digits program in C – SillyCodes
- C program to print all ASCII characters and ASCII values/numbers – SillyCodes