Contact Learn C
Copy

Program 24:To print whether the number is armstrong number or not

Program 24:
#include<stdio.h>
#include<math.h>
main()
{
  int num,i,j,temp,sum=0;;
  printf("Enter a number to know whether it is armstrong or not\n");
  scanf("%d",&num);
  temp=num;
  while(num>0)
  {
    i=num%10;
    sum+=i*i*i;
    num=num/10;
  }
  if(sum==temp)
  {
    printf("Giveb number %d is an armstrong number\n",temp);
  }
  else
  {
    printf("Giveb number %d is not an armstrong number since the sum of cubes of individual digits is %d\n",temp,sum);
  }
}
Explanation:
  1. The program starts with initializing :
    • i → used as a variable
    • j → not used
    • temp → to store given input for future reference.
    • num → To store user input
    • sum → To store the final output initialized with zero
  2. printf("Enter a number to know whether it is 
             armstrong or not\n");
    scanf("%d",&num);
    used to take input from user using scanf statement.Lets us take input as 371
  3. temp=num;
    while(num>0)
    {
    i=num%10;
    sum+=pow(i,3);
    num=num/10;
    }
    This is the main logic for the program.
    • the given number is stored in temp for future reference.So temp=371
    • Iteration 1:As num which is 371>0 which is true and loop executes
      • i=num%10 →371%10 → i=1
      • sum+=pow(i,3) → 0+1^3 → sum=1
      • num=num/10 → 371/10 → num=37 as num is integer don't store float values
      • The final values are i=1,sum=1,num=37
    • Iteration 2:As num which is 37>0 which is true and loop executes
      • i=num%10 →37%10 → i=7
      • sum+=pow(i,3) → 1+7^3 → sum=344
      • num=num/10 → 37/10 → num=3 as num is integer don't store float values
      • The final values are i=7,sum=344,num=3
    • Iteration 3:As num which is 3>0 which is true and loop executes
      • i=num%10 →3%10 → i=3
      • sum+=pow(i,3) → 344+3^3 → 344+27 → sum=371
      • num=num/10 → 3/10 → num=0 as num is integer don't store float values
      • The final values are i=3,sum=371,num=0
    • Iteration 4:As num which is 0>0 which is false and loop terminates
  4. if(sum==temp)
    {
    printf("Giveb number %d is an armstrong number\n",temp);
    }
    else
    {
    printf("Giveb number %d is not an armstrong number since the
            sum of cubes of individual digits is %d\n",temp,sum);
    }
    temp value is 371 which we stored for future reference and now I hope you understood why we used temp instead of num as num value is 0 now after our logic.
  5. Now we compare sum and temp are equal or not if equal it prints it is armstrong else not an armstrong and reason why it is not
  6. From our input 371 as sum equals temp which is true then the printf under if part will execute and prints "Given number 371 is an armstrong number".

 Output:

To print whether the number is armstrong number or not


Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide