Loops: Repeating Instructions
Doing the same thing many times
What is a loop?
A loop repeats a set of instructions. Loops are useful when the same action must happen many times.
Counting loop idea
-
1
Step 1: Start with a counter.
-
2
Step 2: Run the repeated instructions.
-
3
Step 3: Change the counter and stop when the goal is reached.
Why loops matter
Without loops, programs would need many repeated lines of code, which is harder to write and maintain.
What is the main purpose of a loop?
Loops are for repetition.
Correct answer: To repeat instructions
Why are loops useful?
Loops reduce repetition and make code cleaner.
Correct answer: They save time and prevent writing the same code many times
Two common loop ideas
Counting loop
- Repeats a known number of times
- Often uses a counter
Condition loop
- Repeats while a condition stays true
- Stops when the condition becomes false
If you want to print numbers from 1 to 5, which concept is most useful?
A loop is ideal for repeated counting.
Correct answer: Loop
What must eventually happen for a loop to stop?
A loop should not run forever unless that is intentionally desired.
Correct answer: Its ending condition must be met or its count must finish