C Program to Display Armstrong Numbers Between Two Intervals
In this programming tutorial, we will create a C program to find and display Armstrong numbers within a given range. The program will include a detailed explanation of the algorithm used, the C code implementation, and examples demonstrating the output.
Armstrong Number
An Armstrong number (also known as a narcissistic, pluperfect, or pluperfect digital invariant) is a number that is the sum of its own digits, each raised to the power of the number of digits. For example, 153 is an Armstrong number because:
Algorithm for Displaying Armstrong Numbers Between Two Intervals
- Input: Accept two integers (
start
andend
) from the user, representing the range. - Loop: Iterate from
start
toend
.- Inside the loop, calculate the number of digits in the current number.
- Calculate the sum of digits raised to the power of the number of digits.
- If the sum equals the current number, it is an Armstrong number.
- Output: Display the Armstrong numbers found within the specified range.
C Program for Displaying Armstrong Numbers
#include <stdio.h>
#include <math.h>
// Function to calculate the number of digits in a number
int countDigits(int num) {
int count = 0;
while (num != 0) {
num /= 10;
count++;
}
return count;
}
// Function to check if a number is an Armstrong number
int isArmstrong(int num) {
int originalNum = num;
int sum = 0;
int power = countDigits(num);
while (num != 0) {
int digit = num % 10;
sum += pow(digit, power);
num /= 10;
}
return (sum == originalNum);
}
int main() {
int start, end;
// Input range from the user
printf("Enter the start of the range: ");
scanf("%d", &start);
printf("Enter the end of the range: ");
scanf("%d", &end);
// Display Armstrong numbers in the specified range
printf("Armstrong numbers between %d and %d are:\n", start, end);
for (int i = start; i <= end; i++) {
if (isArmstrong(i)) {
printf("%d\n", i);
}
}
return 0;
}
Output Example
Example: Display Armstrong Numbers Between 100 and 1000
Enter the start of the range: 100
Enter the end of the range: 1000
Armstrong numbers between 100 and 1000 are:
153
370
371
407
Explanation
- Input: The user provides the start and end values of the range (e.g., 100 and 1000).
- Loop: The program iterates through the numbers in the specified range.
- Function Calls:
countDigits
: Calculates the number of digits in the current number.isArmstrong
: Checks if the current number is an Armstrong number.
- Output: The program displays Armstrong numbers found within the given range.
Conclusion
This C program efficiently identifies and displays Armstrong numbers within a specified range. The countDigits
function calculates the number of digits, and the isArmstrong
function checks for the Armstrong property. Feel free to test the program with different ranges to observe the results. If you have any questions or need further clarification, please don’t hesitate to ask!