Table of Contents
The Power of Repetition in Programming
Loops allow programs to repeat actions efficiently. Instead of writing the same code multiple times, loops let you repeat it automatically!
Why Do We Need Loops?
Imagine you want to print "Hello" 100 times. Without loops, you'd need to write 100 separate print statements. With loops, you write it once and let the computer repeat it!
Types of Loops
1. For Loops - Counting Loops
Use when you know exactly how many times to repeat something.
For Loop Example
// Print numbers 1 to 5
for i = 1 to 5:
print("Number: " + i)
// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5
2. While Loops - Condition-Based Loops
Use when you want to repeat something as long as a condition is true.
While Loop Example
count = 1
while count <= 3:
print("Count is: " + count)
count = count + 1 // Important: update the condition!
// Output:
// Count is: 1
// Count is: 2
// Count is: 3
Loop Components
Every loop has these parts:
- Initialization: Starting point (count = 1)
- Condition: When to keep going (count <= 3)
- Update: How to change each time (count = count + 1)
- Body: What to do each time (print statement)
Real-World Loop Examples
Processing a List
fruits = ["apple", "banana", "orange", "grape"]
for each fruit in fruits:
print("I like " + fruit)
// Output:
// I like apple
// I like banana
// I like orange
// I like grape
User Input Loop
password = ""
while password != "secret123":
password = input("Enter password: ")
if password != "secret123":
print("Wrong password, try again!")
print("Access granted!")
Common Loop Patterns
1. Counting Pattern
// Count from 1 to 10
for i = 1 to 10:
print(i)
2. Accumulator Pattern
// Add up numbers 1 to 5
total = 0
for i = 1 to 5:
total = total + i
print("Total: " + total) // Total: 15
3. Search Pattern
// Find a specific item
names = ["Alice", "Bob", "Charlie", "Diana"]
found = false
for each name in names:
if name == "Charlie":
print("Found Charlie!")
found = true
break // Exit the loop early
Loop Control Statements
- break: Exit the loop immediately
- continue: Skip to the next iteration
Break and Continue Example
for i = 1 to 10:
if i == 3:
continue // Skip 3
if i == 7:
break // Stop at 7
print(i)
// Output: 1, 2, 4, 5, 6
🎯 Loop Practice Exercises
- Write a loop that prints your name 5 times
- Create a loop that counts down from 10 to 1
- Write a loop that adds up all numbers from 1 to 100
- Create a loop that prints only even numbers from 2 to 20
Common Loop Mistakes
- Infinite Loops: Forgetting to update the condition
- Off-by-One Errors: Starting or ending at wrong number
- Wrong Loop Type: Using while when for would be better
When to Use Each Loop Type
- For Loop: When you know the exact number of repetitions
- While Loop: When you repeat based on a condition
- For-Each Loop: When processing items in a list