C Program to Display Armstrong Number Between Two Intervals

An Armstrong number (also known as a narcissistic number or a pluperfect digital invariant) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, 153 is an Armstrong number because:

1^3 + 5^3 + 3^3 = 153

To display Armstrong numbers between two intervals in a C program, you can follow these steps:

  1. Take two integer values as input from the user, representing the lower and upper bounds of the interval.
  2. Loop through the numbers in the given interval.
  3. For each number, calculate the sum of its digits raised to the power of the number of digits.
  4. If the calculated sum is equal to the original number, then it is an Armstrong number and should be displayed.

Here's a C program to achieve this with an example and sample output:

#include <stdio.h>
#include <math.h>

int countDigits(int num) {
    int count = 0;
    while (num > 0) {
        num /= 10;
        count++;
    }
    return count;
}

int isArmstrong(int num) {
    int originalNum = num;
    int n = countDigits(num);
    int sum = 0;
    
    while (num > 0) {
        int digit = num % 10;
        sum += pow(digit, n);
        num /= 10;
    }
    
    return originalNum == sum;
}

int main() {
    int lower, upper;

    printf("Enter the lower and upper bounds of the interval: ");
    scanf("%d %d", &lower, &upper);

    printf("Armstrong numbers between %d and %d are:\n", lower, upper);

    for (int i = lower; i <= upper; i++) {
        if (isArmstrong(i)) {
            printf("%d ", i);
        }
    }

    printf("\n");
    return 0;

Example: Suppose you enter the lower bound as 100 and the upper bound as 1000.

Input:

Enter the lower and upper bounds of the interval: 100 1000 

Output:

Armstrong numbers between 100 and 1000 are:
153 370 371 407  

These are the Armstrong numbers in the specified interval.

Prasun Barua

Prasun Barua is an Engineer (Electrical & Electronic) and Member of the European Energy Centre (EEC). His first published book Green Planet is all about green technologies and science. His other published books are Solar PV System Design and Technology, Electricity from Renewable Energy, Tech Know Solar PV System, C Coding Practice, AI and Robotics Overview, Robotics and Artificial Intelligence, Know How Solar PV System, Know The Product, Solar PV Technology Overview, Home Appliances Overview, Tech Know Solar PV System, C Programming Practice, etc. These books are available at Google Books, Google Play, Amazon and other platforms.

*

Post a Comment (0)
Previous Post Next Post