Loops (Iteration Statements)
🎯 Core Concept
Loops are programming constructs that allow repeated execution of a block of code based on a condition or over a sequence. They are fundamental to automation and repetitive task handling.
🔄 Types of Loops
Entry-Controlled Loops
Loops where the condition is checked before executing the loop body.
For Loop
Used when the number of iterations is known in advance.
# Python
for i in range(5):
print(f"Iteration {i}")
// Java
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}
While Loop
Used when the number of iterations is unknown and depends on a condition.
# Python
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
// Java
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
Exit-Controlled Loops
Loops where the condition is checked after executing the loop body.
Do-While Loop
Executes the loop body at least once before checking the condition.
// Java
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);
🎮 Loop Control Statements
Break Statement
Immediately exits the loop, skipping remaining iterations.
Continue Statement
Skips the current iteration and moves to the next one.
📚 Common Use Cases
- Processing collections - Iterating over arrays, lists, or datasets
- Input validation - Repeatedly prompting until valid input
- Mathematical calculations - Series, factorial, summation
- Game loops - Continuous game state updates
- File processing - Reading records until end of file
⚡ Performance Considerations
- Choose the right loop type based on the use case
- Avoid infinite loops by ensuring proper termination conditions
- Minimize work inside loops for better performance
- Consider built-in functions for common operations (map, filter, reduce)
This atomic content can be included in Python, Java, C++, and general programming tutorials.