C Program to Display Armstrong Number Between Two Intervals

This post explains how to display Armstrong number between two intervals using the C programming language.

C Program to Display Armstrong Number Between Two Intervals

#include<stdio.h>
#include<math.h>
int main()
{
    int n1,n2,i,temp,num,rem,count=0;
    printf("Enter the intervals:");
    scanf("%%d %%d",&n1,&n2);
    printf("Amrstrong numbers between %%d and %%d are:",n1,n2);
    //to store the values
    for(i=n1+1;i<n2;++i)
    {
        temp=i;
    //checking the armstrong formulation
    while (temp != 0) 
    {
         temp /= 10;
         ++count;
    }
      temp= i;
      while (temp != 0) 
      {
         rem = temp %% 10;
         num += pow(rem, count);
         temp /= 10;
      }
      if ((int)num== i) 
      {
         printf("%%d ", i);
      }
    // resetting the values
      count=0;
      num=0;
    }
    return 0;
}

Output

Explanation

This C program deals with Armstrong numbers, where Armstrong number is the sum of the digit’s cube is equal to the number itself. We first initialize the n1 and n2 where the user-defined values get stored using printf and scanf functions.

	int n1,n2,i,temp,num,rem,count=0;
    printf("Enter the intervals:");
    scanf("%%d %%d",&n1,&n2);
    printf("Amrstrong numbers between %%d and %%d are:",n1,n2);

Next using For loop condition we store the value in the variable named temp, and then we check the Armstrong formulation using the while condition where the temp is not equal to zero, and carry on the calculation part.

	for(i=n1+1;i<n2;++i)
    {
        temp=i;
    //checking the armstrong formulation
    while (temp != 0) 
    {
         temp /= 10;
         ++count;
    }

Again using the while loop condition we calculate the remainder(rem) and the num(result), to get the desired result.

	temp= i;
      while (temp != 0) 
      {
         rem = temp %% 10;
         num += pow(rem, count);
         temp /= 10;
      }

Now using the If condition we check whether num is equal to variable “i” print the final value and then reset the values.

	if ((int)num== i) 
      {
         printf("%%d ", i);
      }
    // resetting the values
      count=0;
      num=0;

We have now obtain the desired output.