Skip to content

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

  1. Processing collections - Iterating over arrays, lists, or datasets
  2. Input validation - Repeatedly prompting until valid input
  3. Mathematical calculations - Series, factorial, summation
  4. Game loops - Continuous game state updates
  5. 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.