R Fundamentals

The while loop

The while loop is used for executing a statement until a condition is valid. The loop terminates when the condition fails. The general format is


        while( condition ) expression 

First the condition is tested. If it is TRUE, the expression is executed, which generally modifies the condition. Then, the condition is again tested. If it is TRUE, the expression is executed. This goes on until the condition fails. When this happens, the while loop is terminated. This is illustrated here:


num = 100.0 while (num > 0.0) { num = num - 10.0 print(num) }

In the above script, the condition whether num is greater than zero is tested. Starting from an initial value of num = 100.0, a value of 10 is subtracted from num during each iteration. The while loop keeps on executing until the value of num falls below 10, where it terminates . The following numers are printed:

[1] 90 [1] 80 [1] 70 [1] 60 [1] 50 [1] 40 [1] 30 [1] 20 [1] 10 [1] 0