Finding Armstrong Numbers in a Given Range using C Programming


This program is written in the C programming language and it is used to find and print all the Armstrong numbers within a given range. An Armstrong number is a number that is equal to the sum of the cubes of its own digits.

  • The program starts by including the standard input/output header file, "stdio.h". Then, the main() function is defined. Inside the main function, seven variables are declared: "i" and "n" for the starting and ending values of the range, "h" is used as a temporary variable, "arms" to keep track of the number of Armstrong numbers found, and "a", "b", "c", "d", "e" are used as temporary variables in the calculations.
  • The program then prompts the user to enter the starting and ending values of the range using the printf() function and stores the values in the "i" and "n" variables using the scanf() function. The for loop is then used to repeatedly execute the code inside the loop for the number of times specified by the range. The for loop starts with "i" initialized to the user input value, and the loop continues until "i" is less than or equal to "n".
  • In each iteration of the for loop, the program uses the integer division and modulus operators to separate the digits of the number and store them in separate variables. Then it cubes each digit and adds the cubes together to get the sum. If the sum is equal to the original number, the program considers it as an Armstrong number and prints the number using the printf function, and increments the variable "arms" by 1.
  • Finally, the program prints the total number of Armstrong numbers found within the given range and then the program is exited by returning 0 from main.

Source Code

#include<stdio.h>
int main()
{
  int i,n,h,arms=0,a,b,c,d,e;
  printf("\nEnter the starting value:");
  scanf("%d",&i);
  printf("\nEnter the Ending value:");
  scanf("%d",&n);
  printf("\nArmstrong numbers:");
  for(i;i<=n;i++)
 {
  a=i/10;//12
  b=i%10;//8
  c=a/10;//1
  d=a%10;//2
  b=b*b*b;
  c=c*c*c;
  d=d*d*d;
  e=b+c+d;
  if(i==e)
  {
   printf("\n%d",i);
   arms++;
  }
  }
  printf("\nTotal number of armstrong values:%d",arms);
  return 0;
}
To download raw file Click Here

Output

Enter the starting value :100
Enter the Ending value :999
Armstrong numbers:
153
370
371
407
Total number of armstrong values:4

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C