What Are Looping Structures?
- Looping structures allow a program to repeat a block of code until a condition is met or for a fixed number of iterations.
- They prevent code duplication.
- Useful for tasks like processing lists, validating input, or running simulations.
Think of loops as "automation for repetition."
Forgetting to update the loop condition → infinite loop.
Types of Loops
For Loops
Used when the number of iterations is known in advance.
Python:
for i in range(5):
print("Iteration", i)Java:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}Use for loops for counting or iterating collections.
Off-by-one errors (< vs. <=).
While Loops
Used when the number of iterations is unknown and depends on a condition.
Python:
count = 0
while count < 5:
print("Count:", count)
count += 1Java:
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}Good for input validation and waiting for conditions.
Forgetting to update the variable → infinite loop.
Do-While Loops (Java only)
Similar to while, but guarantees the loop runs at least once.
int num = 0;
do {
System.out.println("Number: " + num);
num++;
} while (num < 5);Use when you want code to execute before checking the condition.
Assuming the condition is checked first → it runs once regardless.
Control Statements
- break: Exits the loop immediately.
- continue: Skips the current iteration and moves to the next.
Use break in search algorithms when the target is found.
Overusing break/continue → makes loops hard to follow
Performance and Memory Considerations
- Loops themselves are efficient (O(n)), but performance depends on:
- Loop condition complexity.
- Size of the dataset being processed.
- Infinite loops waste CPU and memory resources.
Applications of Loops
- Traversing arrays and lists.
- Processing user input until valid.
- Searching and sorting algorithms.
- Simulating real-world events (e.g., traffic lights, games)
- If asked to trace a loop → always show variable values per iteration.
- Distinguish clearly: for = fixed count, while = unknown repetitions, do-while = at least once.