Loops are a fundamental concept in programming that allow you to repeat a set of instructions for a specified number of times or until a certain condition is met. In this notebook, we will explore the different types of loops in R and provide exercises to help you practice.
In R, there are three main types of loops: 1. For loops 2. While loops 3. Repeat loops
Let’s explore each type in detail.
A for
loop is used when you know in advance how many
times you want to execute a block of code. It iterates over a sequence
of elements, performing the specified actions for each element.
for (variable in sequence) {
# Code to be repeated
}
for (i in 1:5) {
print(i)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
print(paste("I like", fruit))
}
Output:
[1] "I like apple"
[1] "I like banana"
[1] "I like cherry"
A while
loop repeats a block of code as long as a
specified condition is true. It’s useful when you don’t know in advance
how many iterations you need.
while (condition) {
# Code to be repeated
}
count <- 1
while (count <= 5) {
print(count)
count <- count + 1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
A repeat
loop is used to execute a block of code
indefinitely until a stop condition is met. You must explicitly break
out of the loop using a break
statement.
repeat {
# Code to be repeated
if (stop_condition) {
break
}
}
target <- sample(1:10, 1)
repeat {
guess <- as.integer(readline("Guess a number between 1 and 10: "))
if (guess == target) {
print("Correct! You win!")
break
} else {
print("Wrong guess. Try again.")
}
}
Loops can be nested inside other loops. This is useful for working with multi-dimensional data or performing complex iterations.
for (i in 1:5) {
for (j in 1:5) {
print(paste(i, "x", j, "=", i*j))
}
print("---")
}
R provides two main loop control statements:
break
: Exits the loop immediatelynext
: Skips the rest of the current iteration and moves
to the next onefor (i in 1:10) {
if (i == 3) {
next # Skip iteration when i is 3
}
if (i == 7) {
break # Exit loop when i is 7
}
print(i)
}
Output:
[1] 1
[1] 2
[1] 4
[1] 5
[1] 6
While loops are powerful, R is designed for vectorized operations, which are often faster and more concise. Many tasks that require loops in other languages can be accomplished using vectorized functions in R.
Using a loop:
numbers <- 1:100
sum <- 0
for (num in numbers) {
sum <- sum + num
}
print(sum)
Using vectorization:
numbers <- 1:100
sum <- sum(numbers)
print(sum)
Both produce the same result, but the vectorized version is faster and more concise.
Now, let’s practice with some exercises. Try to solve these on your own before looking at the solutions.
Write a for loop that prints the squares of numbers from 1 to 10.
Create a while loop that prints even numbers from 2 to 20.
Use a repeat loop to implement a simple calculator that keeps asking for operations until the user chooses to quit.
Write nested for loops to create a 5x5 identity matrix (1s on the diagonal, 0s elsewhere).
Create a for loop that iterates over a vector of numbers and uses
next
to skip negative numbers, printing only positive
ones.
Write a function that uses a while loop to calculate the factorial of a given number.
Implement the FizzBuzz game using a for loop: For numbers 1 to 100, print “Fizz” if the number is divisible by 3, “Buzz” if it’s divisible by 5, “FizzBuzz” if it’s divisible by both, and the number itself otherwise.
Create a loop that simulates rolling a die until a 6 is rolled, counting the number of rolls.
for (i in 1:10) {
print(paste(i, "squared is", i^2))
}
num <- 2
while (num <= 20) {
print(num)
num <- num + 2
}
repeat {
operation <- readline("Enter operation (+, -, *, /) or 'q' to quit: ")
if (operation == 'q') {
break
}
num1 <- as.numeric(readline("Enter first number: "))
num2 <- as.numeric(readline("Enter second number: "))
result <- switch(operation,
"+" = num1 + num2,
"-" = num1 - num2,
"*" = num1 * num2,
"/" = num1 / num2,
"Invalid operation")
print(paste("Result:", result))
}
identity_matrix <- matrix(0, nrow = 5, ncol = 5)
for (i in 1:5) {
for (j in 1:5) {
if (i == j) {
identity_matrix[i, j] <- 1
}
}
}
print(identity_matrix)
numbers <- c(-2, 5, 0, -1, 3, -4, 7)
for (num in numbers) {
if (num <= 0) {
next
}
print(num)
}
factorial <- function(n) {
result <- 1
while (n > 1) {
result <- result * n
n <- n - 1
}
return(result)
}
print(factorial(5)) # Should print 120
for (i in 1:100) {
if (i %% 3 == 0 && i %% 5 == 0) {
print("FizzBuzz")
} else if (i %% 3 == 0) {
print("Fizz")
} else if (i %% 5 == 0) {
print("Buzz")
} else {
print(i)
}
}
rolls <- 0
repeat {
roll <- sample(1:6, 1)
rolls <- rolls + 1
if (roll == 6) {
break
}
}
print(paste("It took", rolls, "rolls to get a 6"))
Remember, practice is key to mastering loops in R. Try to come up with your own examples and challenges to further your understanding!