7.1 Why Do We Need Loops?
Loops allow a program to repeat actions without writing the same instruction multiple times.
Example in Real Life:
Imagine you’re washing dishes. Instead of saying:
- Pick up a plate.
- Scrub the plate.
- Rinse the plate.
- Dry the plate.
- Pick up another plate.
- Scrub the plate… (and repeating for every plate!)
A loop allows you to say:
"While there are still dirty plates, repeat the process: pick up, scrub, rinse, dry."
7.2 Types of Loops
Definite Loops (repeat a fixed number of times).
Indefinite Loops (repeat until a certain condition is met).
7.2.1 Definite Loops (Fixed Repetition)
A definite loop is used when we know in advance how many times something should repeat.
Example in Real Life:
You want to send a thank-you message to 10 friends.
Instead of writing 10 separate instructions, a loop can repeat the task exactly 10 times.
7.2.2 Indefinite Loops (Repeat Until Condition is Met)
An indefinite loop keeps running until a certain condition is met.
Example in Real Life:
You are waiting for a taxi.
You keep checking the road until a taxi arrives.
Once a taxi arrives, you stop checking and get in.
7.2.3 Infinite Loops (Caution!)
An infinite loop happens when the loop never stops running. This is usually a mistake.
Example in Real Life:
Imagine you are watching a playlist of videos, but instead of stopping after the last video, it keeps replaying forever!
To prevent infinite loops, we must ensure that there is always a way to exit the loop.
7.3 Nested Loops (Loops Inside Loops)
Sometimes, we need a loop inside another loop.
Example in Real Life:
You know you wrote someones birthday on your calendar and are trying to find it, but you have no idea what month or day it is.
You look through every month (First loop) and then every day (Second loop).
7.5 When to Use Loops?
When repeating tasks multiple times (e.g., processing 100 files).
When waiting for a condition to change (e.g., waiting for user input).
When iterating over large amounts of data (e.g., analyzing customer orders).