2.5.2 For Loop

For loop repeats a block of code a specified number of times. The syntax is

# Syntax of for loop
for (i in SEQUENCE) {
    # Code block to be executed
}

In loop syntax, the code block will be executed with respect to each elements in SEQUENCE. For example, we want to print all numbers within 50 that are divisible by 3.

# Example 4
for(i in 1:50){
  if (i %% 3 == 0){ # %% is modulo operator, i.e. returns the remiainder of i/3
    print(i)
  }
}

Remark: The form of SEQUENCE can vary in many ways and doesn’t even need to be a numeric array. See the examples below.

# Example 5: print all the even number within 50
for(i in seq(2, 50, by = 2)){
  print(i)
}
# Example 6: say hello to famous mathematicians 
name_list = c("Gauss", "Euler", "Fourier", "Cantor")
for(i in name_list){
  print(paste0("Hello, ", i, "!"))
}

Previous page | Lecture 2 Homepage | Next page

© 2024 Xijia Liu. All rights reserved.
Logo