An Armstrong number is an n-digit number that is equal to the sum of the nth power of its digits. For example, 153 is an Armstrong number because it has 3 digits, and 1^3 + 5^3 + 3^3 equals 153.
In this article, we’ll write a C program that can check if a given number is an Armstrong number. We’ll break down the problem into small, manageable tasks, and then solve them step by step.
C Program Structure
Here’s a high-level overview of the program we’ll write:
- Get the number to check from the user.
- Count the number of digits in the number.
- Calculate the sum of each digit to the power of the total number of digits.
- Compare the calculated sum to the original number. If they’re equal, then the number is an Armstrong number; otherwise, it’s not.
C Program Code
Now let’s look at the actual C program:
The program starts by including two header files: stdio.h for input/output functions and math.h for the power function pow() used later in the program.
We declare five variables:
- num: to hold the user’s input
- originalNum: to hold a copy of num because we’ll manipulate num during the program
- remainder: to hold the remainder of the division of originalNum by 10 (i.e., the last digit of the number)
- n: to hold the number of digits in the number
- result: to hold the sum of each digit to the power of n
The program then prompts the user to enter an integer. It copies this integer into originalNum and calculates the number of digits in the number.
The program then calculates the sum of each digit to the power of n using the formula result += pow(remainder, n);. After the sum is calculated, the program checks if the sum equals the original number. If the sum equals the original number, the number is an Armstrong number. If not, the number isn’t an Armstrong number.
Let’s test the program with the number 371, which is an Armstrong number.
Here are the steps the program would follow:
- Get the input 371.
- Calculate the number of digits. n = 3.
- Calculate the sum of each digit to the power of n:
3^3 (27) + 7^3 (343) + 1^3 (1) = 371
- Compare the calculated sum (371) to the original number (371). They’re equal, so the program would output “371 is an Armstrong number”.
In this article, we’ve looked at what an Armstrong number is and how to write a C program to check if a number is an Armstrong number. The program uses basic programming concepts, such as loops, if statements, and arithmetic operations, making it a great practice exercise for beginners in C programming.