2
votes

I want to write a c program that prints the sum of the squares of a given number. For example, if the given number is 456, the output would be 4^2+5^2+6^2=16+25+36=77.

So i have written this code and i want to know why it doesn't work if the user gives a number like 100,101,102 or 200,300 etc. It works fine for other numbers. I guess it has something to do with the dowhile loop. Please help me.

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
 int n,t=0,r,q;
 printf("Enter the number to be tested: ");
 scanf("%d",&n);
 q=n;
 do
 {
      r=q%10;
      t=t+pow(r,2);
      q=q/10;
 }
 while(q%10!=0);
 printf("%d",t);
 getch();


}
2
Shouldn't while(q%10!=0); be something like while(q>0);? Otherwise it'll stop at a 0.Biffen

2 Answers

3
votes

Your stopping condition is wrong: q%10!=0 will become "true" as soon as you reach the first zero in a decimal representation. For example, for a number 6540321 your program would add 32+22+12, and stop, because the next digit happens to be zero. Squares of 6, 5, and 4 would never be added.

Use q != 0 condition instead to fix this problem. In addition, consider replacing

t=t+pow(r,2);

with a more concise and C-like

t += r*r;
2
votes

Change

while(q%10!=0);

To

while(q);

Which is the short for

while(q!=0);

This is done to prevent to loop from ending once the value of q is a multiple of 10.