Previous Up Next

10.3.5  The while loop

The while loop is used to repeat a code block as long as a given condition holds. To use it, enter while, the condition, and then a code block. For example, to add the terms of the harmonic series 1 + 1/2 + 1/3 + 1/4 + … until a term is less than 0.05, you could initialize the sum S to 0 and let j be the first term 1. Then

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

will find the sum. This line is the same as

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

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