C Program To Check Armstrong Number Using If Else
An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or plus perfect number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. In this article, you will learn how to write a C program to determine if a given number is an Armstrong number using if-else statements, focusing on three-digit numbers for simplicity.
Problem Statement
Checking if a number is an Armstrong number requires a programmatic approach to dissect the number into its individual digits, perform a calculation on each digit, and then sum these results. For a three-digit number like 153, the problem is to verify if $1^3 + 5^3 + 3^3$ equals 153. A robust solution needs to handle user input and provide a clear outcome.
Example
Consider the number 153.
$1^3 = 1$
$5^3 = 125$
$3^3 = 27$
Sum $= 1 + 125 + 27 = 153$.
Since the sum equals the original number, 153 is an Armstrong number.
For the number 123:
$1^3 = 1$
$2^3 = 8$
$3^3 = 27$
Sum $= 1 + 8 + 27 = 36$.
Since the sum 36 does not equal 123, 123 is not an Armstrong number.
Background & Knowledge Prerequisites
To understand and implement the solution, you should be familiar with:
- C Language Basics: Variables, data types (e.g.,
int), and basic program structure. - Input/Output Operations: Using
printf()for output andscanf()for input. - Arithmetic Operators: Specifically, the modulo operator (
%) to get the last digit and the division operator (/) to remove the last digit. - Looping Constructs: A
whileloop is essential for iterating through the digits of a number. - Conditional Statements:
if-elsestatements are used to compare the calculated sum with the original number and display the appropriate result.
Use Cases or Case Studies
Armstrong numbers, and number properties in general, find applications in various contexts:
- Educational Programming Exercises: They serve as common problems for beginners to practice loop constructs, arithmetic operations, and conditional logic.
- Mathematical Puzzles and Recreational Mathematics: Exploring unique number properties is a popular pastime for mathematicians and enthusiasts.
- Algorithm Development Practice: Digit manipulation is a fundamental skill that can be applied to more complex algorithms, such as encryption or data validation.
- Number Theory Research: While Armstrong numbers themselves might not have direct industrial applications, the underlying number theory principles are crucial in fields like cryptography.
Solution Approaches
This section details a common approach to check for Armstrong numbers.
Iterative Digit Extraction and Summation
This approach systematically breaks down the number into its individual digits, cubes each digit, and sums them up. Finally, it compares this sum with the original number.
One-line summary: Extract each digit of the number using modulo and division, cube it, sum the cubes, and compare the total with the original number.
Code example:
// Armstrong Number Checker
#include <stdio.h>
int main() {
int num, originalNum, remainder, sum = 0;
// Step 1: Prompt user for input and read the number
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num; // Store the original number for comparison later
// Step 2: Loop to extract digits and calculate the sum of cubes
while (originalNum != 0) {
remainder = originalNum % 10; // Get the last digit
sum += remainder * remainder * remainder; // Add cube of the digit to sum
originalNum /= 10; // Remove the last digit
}
// Step 3: Compare the sum with the original number using if-else
if (sum == num) {
printf("%d is an Armstrong number.\\n", num);
} else {
printf("%d is not an Armstrong number.\\n", num);
}
return 0;
}
Sample Output:
- Input:
153Enter a three-digit integer: 153 153 is an Armstrong number.
- Input:
370Enter a three-digit integer: 370 370 is an Armstrong number.
- Input:
123Enter a three-digit integer: 123 123 is not an Armstrong number.
Stepwise explanation:
- Initialize Variables:
-
num: Stores the integer entered by the user. -
originalNum: A copy ofnumis stored here becausenumwill be modified during the digit extraction process. -
remainder: Temporarily holds each digit extracted from the number. -
sum: Initializes to0and accumulates the sum of the cubes of the digits.
- Get User Input: The program prompts the user to enter a three-digit integer and reads it into the
numvariable usingscanf(). - Store Original Number: The value of
numis copied tooriginalNum. This is crucial because thewhileloop will modifyoriginalNum, and we need the initial value for comparison. - Digit Extraction Loop (
whileloop):
- The loop continues as long as
originalNumis not0. -
remainder = originalNum % 10;: This line extracts the last digit oforiginalNum. For example, iforiginalNumis153,remainderbecomes3. -
sum += remainder * remainder * remainder;: The extractedremainder(digit) is cubed (multiplied by itself three times), and this result is added to thesum. -
originalNum /= 10;: This line removes the last digit fromoriginalNumby performing integer division. For example, iforiginalNumwas153, it becomes15. The loop then continues with15, then1, and finally terminates whenoriginalNumbecomes0.
- Check Condition (
if-else):
- After the loop finishes,
sumholds the total of the cubes of the digits. -
if (sum == num): This condition checks if the calculatedsumis equal to thenum(the original number entered by the user). - If they are equal, the number is an Armstrong number, and a corresponding message is printed.
- Otherwise, the
elseblock executes, indicating that the number is not an Armstrong number.
Conclusion
Determining if a number is an Armstrong number is a classic programming problem that effectively utilizes fundamental C concepts like loops and conditional statements. By iteratively extracting digits and summing their cubes, we can efficiently verify this unique mathematical property. This approach provides a clear and straightforward solution using if-else for the final decision.
Summary
- An Armstrong number is equal to the sum of its digits raised to the power of the number of digits (e.g., $153 = 1^3 + 5^3 + 3^3$).
- The solution involves an iterative process to extract each digit of the number.
- The modulo operator (
% 10) helps in getting the last digit. - Integer division (
/ 10) helps in removing the last digit. - A
whileloop facilitates processing each digit until the number becomes zero. - An
if-elsestatement is used to compare the final sum of cubed digits with the original number to declare whether it is an Armstrong number or not.