An Armstrong Number is an n-digit number which is equal to the nth power sum of its individual digits. In this tutorial post, we are going to write a program for Armstrong Number in C programming with its algorithm, source code and sample output.
The C program presented here displays Armstrong number between a specified interval; it is short and relatively simple to understand. It gives the fundamental idea of input and output functions and simple mathematical operations that come along with the loops.
First of all, What is an Armstrong Number? An Armstrong Number can be defined an n-digit number which is equal to the nth power sum of the individual digits of the number. For example, 371 is an Armstrong Number because 33 + 73 + 13 = 27 + 343 + 1 = 371. Here, 3 has been used as the power of digit because 371 is a three-digit number.
Before going through the source code, here’s a simple algorithm to display Armstrong Number; it can be used as a reference algorithm to print Armstrong numbers in any programming language.
Algorithm to Display Armstrong Numbers:
- Declare and initialize the variables.
- Enter the interval in which the Armstrong numbers are to be displayed.
- Separate each digit of the numbers in the interval.
- Find the cube of each digit.
- Add the cube of all the digits.
- Compare sum with the number.
- If the sum is equal to number, print the number as an Armstrong number and jump to next number.
- Else, jump to next number without printing.
Armstrong Number in C Source Code:
int num1, num2, j, temp, num, rmd;// variable Declaration
printf(" Enter the interval for Armstrong Numbers: ");
scanf("%d %d", &num1, &num2); // getting the interval
printf(" The Armstrong Numbers Between %d an %d are: ", num1, num2);
for(j=num1+1; j<num2; ++j)
while(temp!=0)// loop to check if the number is Armstrong number
printf("%d ",j); // printing the Armstrong numbers
The above source code in C program to display Armstrong Numbers between intervals is very simple. It includes just a single header file: stdio.h which controls the basic input output function such as printf(), scanf(), etc.
When the C program is executed, it asks for the interval of numbers between which the Armstrong numbers are to be displayed. In order to check whether a number is Armstrong number or not, each digit of the number in the interval are separated using remainder operation in loop.
Then, each separated number are cubed and summed up. The sum is compared to the number and if the sum and the number are equal, the number is saved as an Armstrong number. Finally, all the Armstrong numbers in the interval specified are obtained in the output as shown below.
The source code for Armstrong Number in C programming presented here needs to be compiled in Code::Blocks IDE. The program is well-tested and completely error-free. If you have any queries regarding this post, Armstrong number, its algorithm or C source code, bring them up from the comments.