13 Loops

13.1 Loops

Loops are a fundamental component of (procedural) programming.

There are two main types of loops:

  • conditional loops are executed as long as a defined condition holds true
    • construct while
    • construct repeat
  • deterministic loops are executed a pre-determined number of times
    • construct for

13.2 While

The while construct can be defined using the while reserved word, followed by the conditional statement between simple brackets, and a code block. The instructions in the code block are re-executed as long as the result of the evaluation of the conditional statement is TRUE.

## Current value is 0 
## Current value is 1 
## Current value is 2

13.3 For

The for construct can be defined using the for reserved word, followed by the definition of an iterator. The iterator is a variable which is temporarily assigned with the current element of a vector, as the construct iterates through all elements of the list. This definition is followed by a code block, whose instructions are re-executed once for each element of the vector.

## Do you live in Derby ?
## Do you live in Leicester ?
## Do you live in Lincoln ?
## Do you live in Nottingham ?

13.4 For

It is common practice to create a vector of integers on the spot in order to execute a certain sequence of steps a pre-defined number of times.

## This is exectuion number 1 :
##     See you later!
## This is exectuion number 2 :
##     See you later!
## This is exectuion number 3 :
##     See you later!

13.5 Loops with conditional statements

## [1] 3 2 1 0
## 3 
## 2 
## 1 
## Go!