# Thread: simple program on loops

1. ## simple program on loops

I am trying to get this program to divide and add. it is suppose to add all the (1/limit*limit) up and give a sum. for some reason it gives me an out of 1.0000 every time. Does anybody have any advise or help they can give me..... here is my code....
Code:
```#include <stdio.h>

int main (void)
{
int limit;
float sum=0;
int i;

scanf("%d",&limit);
printf("your limit is %d\n\n",limit);

for(i=1;i<=limit;i++)
{
sum=(1/(i*i))+sum;

}

return 0;
}```

2. Well you are getting the problem from integer division. int can not be a decimal number, Try this insted
Code:
```#include <stdio.h>

int main (void)
{
int limit;
double sum=0;
double i;

scanf("%d",&limit);
printf("your limit is %d\n\n",limit);

for(i=1;i<=limit;i++)
{
sum=(1.0/(i*i))+sum;

}

return 0;
}```

3. int limit;
double sum=0;
double i; /* i is loop counter */

For good C programing practice, NEVER make a
loop control counter with floating point number
such as float, double..
Above, the program will work fine as declare
i as integer (int i). Just add:
sum = sum + ( 1.0/(i*i) );

is good enough.

DV007

Popular pages Recent additions