Previous Up Next

12.3.5  The while loop: while

The while loop is used to repeat a code block as long as a given condition holds. To use it, enter while, the condition in parentheses, and then a code block.

while (bool) block


Example.
Add the terms of the harmonic series 1 + 1/2 + 1/3 + 1/4 + … until a term is less than 0.05.
You can initialize the sum S to 0 and let j be the first term 1.
Input:

S:=0
j:=1

Then use a while loop:
Input:

while (1/j >= 0.05) {S:= S + 1/j; j:= j+1;}

or:

tantque (1/j >= 0.05) faire S:= S + 1/j; j:= j+1; ftantque

then:

S

Output:

55835135
15519504

Note that a while loop can also be written as a for loop. For example, as long as S is set to 0 and j is set to 1 , the above loop can be written as

for (;1/j >= 0.05;) {S:= S + 1/j; j:= j+1;}

or, with only S set to 0,

for (j:= 1; 1/j >= 0.05; j++) {S:= S + 1/j;}

Previous Up Next