# hi. i want to rewrite this do loop into a while loop.

• January 25th, 2010, 11:52 PM
etidd
hi. i want to rewrite this do loop into a while loop.
hi help me rewrite the following do loop into a while loop.

int n = 1;
double x = 0;
double s ;
do
{
s = 1.0 / (n * n);
x = x + s;
n++;
}
while (s > 0.01);

is double s given a default value when it was declared? :-L

s is getting smaller and smaller...

hmm, i'm confused!
• January 26th, 2010, 07:11 AM
Json
Re: hi. i want to rewrite this do loop into a while loop.
Code :

``` int n = 1; double x = 0; double s ;   do { s = 1.0 / (n * n); x = x + s; n++; } while (s > 0.01);```

Yes, all primitives will receive a default value of zero if they are numbers or false if its a boolean.

The reason for s going smaller and smaller is the fact that s equals 1.0 divided by (n * n). For each loop you increment n which means that s will be 1.0 divided by a bigger number every time.

1.0 / 1 = 1.0
1.0 / 4 = 0.25
1.0 / 9 = 0.11
and so on.

The only difference with using a do/while loop and a normal while loop is that the do/while loop will always be run at least once. The normal while loop will always check the condition before it executes the code block.

Code :

``` int n = 1; double x = 0; double s ;   while(s > 0.01) { s = 1.0 / (n * n); x = x + s; n++; }```

// Json
• January 26th, 2010, 11:41 AM
Freaky Chris
Re: hi. i want to rewrite this do loop into a while loop.
Code :

``` int n = 1; double x = 0; double s ;   while(s > 0.01 || n == 1) { s = 1.0 / (n * n); x = x + s; n++; }```
• January 26th, 2010, 04:27 PM
etidd
Re: hi. i want to rewrite this do loop into a while loop.
yep, sure got it... figured it out myself shortly after posting this. it's great to voice it out to figure it out!