C program and algorithm to check whether a number is armstrong or not.

ALGORITHM

  1. Start
  2. read number
  3. set sum=0 and duplicate=number
  4. reminder=number%10
  5. sum=sum+(reminder*reminder*reminder)
  6. number=number/10
  7. repeat steps 4 to 6 until number > 0
  8. if sum = duplicate
  9. display number is armstrong
  10. else 
  11. display number is not armstrong
  12. stop


PROGRAM



#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,s,r,dup;
s=0;
printf("\n Enter a number please:\t");
scanf("%d",&n);
dup=n;
while(n>0)
{
r=n%10;
s=s+(r*r*r);       //or you can use pow(r,3) and use the header file math.h
n=n/10;
}
if(dup=s)
printf("\n %d is an armstrong number",dup);
else
printf("\n %d is not an armstrong
number",dup);
getch();
}


LOGIC



An armstrong number: the sum of cube of its digits results in that number itself.

eg: 153 = (1*1*1)+(5*5*5)+(3*3*3) = 1+125+27 =153.


r=n%10:

153%10 gives the reminder, that is the number 3 here. The modulus operator is used here to seperate the digits. The other thing is that " a small number % large number= that small number itself ".
eg: 3%5= 3 (reminder)


n=n/10:

after a modulus operation we will get the last digit of that number now we have to remove the last digit from the input number so we divide it by 10 and what happens is:



153%10=3 (reminder,r=3)
sum=0+(3*3*3) (sum,s=27)
153/10=15 (number,n=15)


the actual answer is 15.3 but since we initialize it as an integer the floating point value isn't considered. So the calculation continues like:

now the value of n is 15 after the division by 10.


15%10=5                      (reminder,r=5)

sum=(3*3*3)+(5*5*5)  (sum,s=152)
15/10=1                         (number,n=1)



and this continues till the number becomes 0 that is the while condition (n>0) evaluates to false.



OUTPUT


Enter a number please: 153

153 is an armstrong number




28 comments:

  1. Is that on step5 of algorithm why reminder*reminder*reminder written

    ReplyDelete
    Replies
    1. In entered number '153' is a 3 different numbers so, 1³+5³+3³ is done. If 'ABCD' is a number, it has 4 different numbers, the results will be A⁴+B⁴+C⁴+D⁴

      Delete
  2. Thanks for explaining 😊

    ReplyDelete
  3. How you make the search for another program gedget in blogger... Please must reply....Thank you

    ReplyDelete
  4. Its only for 3 digit no can any one explain case where more than 3 digits are applied

    ReplyDelete