Reputation: 145
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();
}
Upvotes: 2
Views: 32035
Reputation: 20244
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.
Upvotes: 2
Reputation: 726479
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;
Upvotes: 3