Armstrong Numbers Between Two Integers using c program

C Programming Language / Loop control in C Language

163

Tip: Before trying this program, learn what is armstrong-number

Given Input:

Enter two numbers(intervals): 200
2000

Expected Output:

Armstrong numbers between 200 and 2000 are: 370 371 407 1634 

Program:

#include <math.h>
#include <stdio.h>
int main() {
  int low, high, number, originalNumber, rem, count = 0;
  double result = 0.0;
  printf("Enter two numbers(intervals): ");
  scanf("%d %d", &low, &high);
  printf("Armstrong numbers between %d and %d are: ", low, high);

  // swap numbers if high < low
  if (high < low) {
    high += low;
    low = high - low;
    high -= low;
  }
   
  // iterate number from (low + 1) to (high - 1)
  // In each iteration, check if number is Armstrong
  for (number = low + 1; number < high; ++number) {
    originalNumber = number;

    // number of digits calculation
    while (originalNumber != 0) {
      originalNumber /= 10;
      ++count;
    }

    originalNumber = number;

    // result contains sum of nth power of individual digits
    while (originalNumber != 0) {
      rem = originalNumber % 10;
      result += pow(rem, count);
      originalNumber /= 10;
    }

    // check if number is equal to the sum of nth power of individual digits
    if ((int)result == number) {
      printf("%d ", number);
    }

    // resetting the values
    count = 0;
    result = 0;
  }

  return 0;
}

Output:

Enter two numbers(intervals): 200
2000
Armstrong numbers between 200 and 2000 are: 370 371 407 1634 

Explanation:

In the program, the outer loop is iterated from (low+ 1) to (high - 1). In each iteration, it's checked whether number is an Armstrong number or not.

Inside the outer loop, the number of digits of an integer is calculated first and stored in count. And, the sum of the power of individual digits is stored in the result variable.

If number is equal to result, the number is an Armstrong number.

Notes:

  • You need to swap low and high if the user input for high is less than that of low. To learn more, check our example on swapping two numbers.
  • You need to reset count and result to 0 in each iteration of the outer loop.

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.