C Program to Generate First N Armstrong Numbers Where N is Given by User

A number is said to be Armstrong or Narcissistic Number if it is equal to the sum of its own digits raised to the power of the number of digits in a given number.

For example number 153 is Armstrong number because: 13 + 53 + 33 = 153

Similary, 1634 is also Armstrong number i.e. 14+64+34+44 = 1634

Single digits number 1 to 9 are also Armstrong numbers.

In this C program, we are going to generate first N Armstrong Numbers where value of N is given by user.

Program


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

int main()
{
	 int n, digitCount, number, sum, rem, i=2, count=1;
	 clrscr();
	 printf("Enter how many Armstrong numbers? \n");
	 scanf("%d", &n);
	
	 /* Generating Armstrong Numbers */
	 while(count <= n)
	 {
	
		  /* Finding number of digits */
		  number = i;
		  digitCount = 0;
		  while(number != 0)
		  {
			   digitCount++;
			   number = number/10;
		  }
		
		  /* Finding sum */
		  number = i;
		  sum = 0;
		  while(number != 0)
		  {
			   rem = number%10;
			   sum = sum + pow(rem, digitCount);
			   number = number/10;
		  }
		
		  /* Making Decision and Printing */
		  if(sum == i)
		  {
			   printf("%d\t", i);
			   count++;
		  }
		  i++;
	 }
	 getch();
	 return(0);
}

Output of the above program :

Run 1:
----------
Enter how many Armstrong numbers?
5 ↲
1   2   3   4   5

Run 2:
----------
Enter how many Armstrong numbers?
15 ↲
1     2     3    4      5     6     7     8     9     153   
370   371   407  1634   8208

Note: ↲ indicates enter is pressed.