Part15 Repetitive execution

Loops are used to repeat a specific block of code.


Structure of the for loop:

3 main elements:

  • i is the loop variable: it is updated at each iteration.
  • vector_expression: value attributed to i at each iteration (the number of iterations is the length of vector_expression).
  • action_command: what action to take at each iteration.

Note the usage of curly brakets {} to start and end the loop!

  • Example:
  • Example of a for loop that iterates over a character vector:
  • Example of a for loop that iterates over each row of a matrix, and prints the minimum value of that row :
  • If statement in For loop:

You can combine for loops and if statements:

You can also have a look at this tutorial, to know more about loops.