Write R code to use a for loop to print the numbers from 3 to 7.
Loops allow you to execute a block of code multiple times, which is useful for repetitive tasks. R has three main types of loops: for
, while
, and repeat
.
for
LoopIterates over a sequence of values.
for (i in 1:5) {
print(i)
}
while
LoopRepeats code as long as a condition is TRUE
.
count <- 1
while (count <= 5) {
print(count)
count <- count + 1
}
repeat
LoopExecutes code indefinitely until a break
statement is encountered.
n <- 1
repeat {
print(n)
n <- n + 1
if (n > 5) {
break
}
}
Loops are a powerful way to automate tasks and handle repeated operations efficiently.