Loops are used in programming to repeat a block of code multiple times. In R, the main types of loops are:
break statement is encountered.The for loop iterates over elements of a vector or sequence.
# Print numbers 1 to 5
for(i in 1:5) {
print(i)
}
Output: 1 2 3 4 5 (each printed on a new line)
You can also loop over vectors of characters or any other types:
fruits <- c("apple", "banana", "cherry")
for(fruit in fruits) {
print(paste("I like", fruit))
}
The while loop repeats as long as the condition remains TRUE.
count <- 1
while(count <= 5) {
print(paste("Count is", count))
count <- count + 1 # increment count
}
Output:
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5
The repeat loop runs infinitely until a break statement stops it.
count <- 1
repeat {
print(paste("Count is", count))
count <- count + 1
if(count > 5) {
break # exit the loop when count is greater than 5
}
}
Output: Same as above
break to exit a loop early.next to skip the current iteration and continue with the next.break and next
for(i in 1:10) {
if(i == 3) {
next # skip when i is 3
}
if(i == 7) {
break # stop the loop when i is 7
}
print(i)
}
Output: 1 2 4 5 6
| Loop Type | When to Use | Syntax |
|---|---|---|
| for loop | When you want to repeat for each element in a sequence or vector. |
for(var in sequence) { statements } |
| while loop | When you want to repeat while a condition is true. |
while(condition) { statements } |
| repeat loop | When you want to repeat indefinitely until a break. |
repeat { statements if(condition) break } |
Write a for loop to print the squares of numbers from 1 to 10.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!