đ Introduction
Loops are control structures that allow a block of code to be executed repeatedly until a specified condition is met. Instead of writing the same code multiple times, loops automate repetitive tasks, making programs shorter, more efficient, and easier to maintain.
Information
đ¯ Why Use Loops?
- Reduce repetitive code.
- Automate repeated tasks.
- Process collections such as vectors and lists.
- Perform calculations efficiently.
- Improve program readability and maintainability.
đ Types of Loops in R
đš The for Loop
The for loop executes a block of code for every element in a sequence, vector, list, or other iterable object.
Syntax of for Loop
for (variable in sequence) {
# Code to execute
}Example: Printing Numbers
for (i in 1:5) {
print(i)
}Output
Console Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5đ¸ The while Loop
The while loop repeatedly executes a block of code as long as the specified condition remains TRUE.
Syntax of while Loop
while (condition) {
# Code to execute
}Example: while Loop
count <- 1
while (count <= 5) {
print(count)
count <- count + 1
}Output
Console Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5đ The repeat Loop
The repeat loop executes indefinitely until it is explicitly terminated using the break statement.
Syntax of repeat Loop
repeat {
# Code to execute
if (condition) {
break
}
}Example: repeat Loop
count <- 1
repeat {
print(count)
count <- count + 1
if (count > 5) {
break
}
}Output
Console Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5âš The break Statement
The break statement immediately terminates the current loop, regardless of the loop condition.
Example: break
for (i in 1:10) {
if (i == 6) {
break
}
print(i)
}Output
Console Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5â The next Statement
The next statement skips the current iteration and continues with the next iteration of the loop.
Example: next
for (i in 1:5) {
if (i == 3) {
next
}
print(i)
}Output
Console Output
[1] 1
[1] 2
[1] 4
[1] 5đ Looping Through a Vector
A for loop is commonly used to process each element of a vector.
Loop Through a Vector
fruits <- c("Apple", "Banana", "Orange")
for (fruit in fruits) {
print(fruit)
}Output
Console Output
[1] "Apple"
[1] "Banana"
[1] "Orange"đ Nested Loops
A loop placed inside another loop is called a nested loop. Nested loops are useful for working with tables, matrices, and multidimensional data.
Nested for Loop
for (i in 1:3) {
for (j in 1:2) {
print(paste("Row:", i, "Column:", j))
}
}đ§Ž Real-World Example
The following program calculates the total sales for five days.
Calculating Total Sales
sales <- c(1200, 1500, 1800, 1700, 1600)
total <- 0
for (amount in sales) {
total <- total + amount
}
print(total)Output
Console Output
[1] 7800đ Loop Execution Flow
đ Comparison of Loops
| Loop | Purpose | Best Used When |
|---|---|---|
| for | Iterates over a sequence. | The number of iterations is known. |
| while | Repeats while a condition is true. | The number of iterations is unknown. |
| repeat | Creates an infinite loop until stopped. | The loop should continue until a manual exit condition is reached. |
â ī¸ Infinite Loops
An infinite loop occurs when the loop condition never becomes FALSE. This causes the program to run indefinitely.
Avoid Infinite Loops
count <- 1
while (count <= 5) {
print(count)
count <- count + 1
}Warning
â ī¸ Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Forgetting to update the loop variable | May create an infinite loop. | Update the loop variable during each iteration. |
| Using the wrong loop type | May result in unnecessary complexity. | Choose the loop that best matches the problem. |
| Misplacing break or next | Can change loop behavior unexpectedly. | Place them carefully inside conditional statements. |
| Modifying the loop sequence incorrectly | Can produce unexpected results. | Avoid changing the sequence while iterating. |
đĄ Best Practices
- Use for loops when the number of iterations is known.
- Use while loops when repetition depends on a condition.
- Use repeat only when an explicit exit condition is required.
- Keep loop bodies simple and readable.
- Whenever possible, use R's vectorized functions instead of loops for better performance.
Best Practice
đ Summary
Loops enable R programs to perform repetitive tasks efficiently. You learned about the for, while, and repeat loops, along with the break and next statements for controlling loop execution. You also explored nested loops, vector iteration, loop execution flow, and best practices for writing efficient looping code. Mastering loops is an important step toward solving real-world programming problems and processing large amounts of data.