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."
Common MistakeForgetting to update the loop condition → infinite loop.
Types of Loops
For Loops
Used when the number of iterations is known in advance.
ExamplePython:
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.
Common MistakeOff-by-one errors (< vs. <=).
While Loops
Used when the number of iterations is unknown and depends on a condition.
ExamplePython:
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.
Common MistakeForgetting to update the variable → infinite loop.
Do-While Loops (Java only)
Similar to while, but guarantees the loop runs at least once.