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.
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:
or:
then:
Output:
|
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
or, with only S set to 0,