C program to print the armstrong number

C program to print the armstrong number


Input:

Enter the range till you want to print armstrong numbers:

10000

Output:


The armstrong numbers from 1 to 10000 are:

1 153 370 371 407

Implementation:


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

/* replacing the data type name unsigned long long int with ll (name whatever you wish) */
typedef unsigned long long int ll;

/* Function to check whether the number is armstrong or not */
/* 
   The number is said to be armstrong if, the sum of cubes of every digit is equal to the 
   number itself.
   For example:
   consider the number 153.
   the sum of cubes of digits = (1*1*1) + (5*5*5) + (3*3*3)
            = 1 + 125 + 27
            = 153
   Here, as you can see, the sum of cube powers of digits of the entered number is 
   equal to the number itself.
   Hence, the number 153 is an armstrong number.
   */
ll checkarmstrong(ll n)
{
 
 /* create a copy of input number to temp */
 /* initialize sum variable to zero */
 ll temp=n,sum=0,rem;
 
 /* while the number is not equal to zero 
    or 
    until the number becomes zero 
    */
 while(temp)
 {
  /* calculate the remainder of the number 
     the remainder will be the last digit of the number
     */
  rem=temp%10;
  
  /* cube the last digit using pow function from math.h library 
     & add the result to the sum variable
     */
  sum+=pow(rem,3);
  
  /* now that we have calculated the cube sum for last digit,
     so we may now remove the last digit from the number 
     dividing any number with 10 will cut the last digit of that number
     */
  temp/=10;
 }
 
 /* returns true if the sum equals n
    returns false if the sum not equals n
    */
 return (sum==n);
}

int main(void) {
 
 /* ll is typedefined as unsigned long long int datatype.(see the header for definition) */
 ll i;
 ll range;
 printf("Enter the range till you want to print armstrong numbers:\n");
 scanf("%llu",&range);
 printf("The armstrong numbers from 1 to %d are:\n",range);
 for(i=1;i<=range;i++)
 {
  
  /* check whether the number is armstrong 
     If so, print the number
     Else, check the next number
     Repeat the process until the given range
     */
  if(checkarmstrong(i))
  {
   printf("%d ",i);
  }
 }
 return 0;
}