Lesson 4.3: Conditions and Loops
Duration: 45 minutes
Learning Objectives
After completing this lesson, you will be able to:
- Understand what conditions are and how they create decision points
- Recognize different types of loops and when to use each
- Combine conditions and loops to solve problems
- Write pseudo-code that includes conditional logic and repetition
Introduction
In the previous lessons, we learned that algorithms are step-by-step instructions. But real-world problems aren't always a straight line from start to finish. Sometimes you need to make decisions based on circumstances. Sometimes you need to repeat actions multiple times.
Conditions and loops are the two concepts that give algorithms their power. With just these two tools, you can solve remarkably complex problems.
Main Content
Part 1: Conditions (Making Decisions)
A condition is a decision point in an algorithm where you choose what to do based on whether something is true or false.
┌─────────────────────────────────────────────────────────────┐
│ CONDITIONS │
│ │
│ "IF something is true, THEN do this, │
│ ELSE do that" │
│ │
│ Example: │
│ IF it's raining THEN take umbrella ELSE wear sunglasses │
│ │
└─────────────────────────────────────────────────────────────┘
Conditions in Daily Life
You make conditional decisions constantly:
| Condition | If True | If False |
|---|---|---|
| Is it raining? | Take umbrella | Don't take umbrella |
| Is the light red? | Stop | Keep going |
| Am I hungry? | Eat something | Don't eat |
| Is it cold outside? | Wear jacket | Don't wear jacket |
| Is my phone battery low? | Charge it | Keep using |
The Structure of a Condition
Every condition has the same basic structure:
IF [something is true]
THEN [do this]
ELSE
[do that instead]
END IF
The ELSE part is optional. Sometimes you only need to do something when a condition is true:
IF [phone is ringing]
THEN [answer phone]
END IF
Multiple Conditions
Sometimes you need to check several things:
IF [temperature > 30°C]
THEN [wear shorts and t-shirt]
ELSE IF [temperature > 15°C]
THEN [wear light jacket]
ELSE IF [temperature > 0°C]
THEN [wear warm coat]
ELSE
[wear winter gear]
END IF
This is called an if-else chain. The computer checks each condition in order and executes the first one that's true.
Combining Conditions
You can combine multiple conditions using AND and OR:
IF [it's Saturday] AND [weather is nice]
THEN [go to the beach]
END IF
IF [I'm tired] OR [it's late]
THEN [go to bed]
END IF
- AND: Both conditions must be true
- OR: At least one condition must be true
Visualizing Conditions: Decision Trees
Conditions create branches in your algorithm:
[Start]
│
▼
┌─────────────┐
╱ Is it ╲
╱ raining? ╲
╲ ╱
╲ ╱
└──────┬────┘
Yes │ No
┌──────┴──────┐
▼ ▼
[Take umbrella] [Check temperature]
│ │
│ ▼
│ ┌─────────────┐
│ ╱ Above 25°C? ╲
│ ╱ ╲
│ ╲ ╱
│ ╲ ╱
│ └──────┬──────┘
│ Yes │ No
│ ┌──────┴──────┐
│ ▼ ▼
│ [Sunscreen] [Light jacket]
│ │ │
└──────┴──────┬──────┘
▼
[Leave home]
Part 2: Loops (Repeating Actions)
A loop is a way to repeat a set of instructions multiple times without writing them out again and again.
┌─────────────────────────────────────────────────────────────┐
│ LOOPS │
│ │
│ Instead of writing: │
│ Say "Hello" │
│ Say "Hello" │
│ Say "Hello" │
│ Say "Hello" │
│ Say "Hello" │
│ │
│ Write: │
│ REPEAT 5 times: │
│ Say "Hello" │
│ │
└─────────────────────────────────────────────────────────────┘
Types of Loops
There are three main types of loops:
1. Count-Controlled Loop (FOR)
Use when you know exactly how many times to repeat:
FOR i FROM 1 TO 10
Print i
END FOR
Result: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Real-life example: "Do 20 push-ups"
2. Condition-Controlled Loop (WHILE)
Use when you repeat until something becomes false:
WHILE [hungry]
Eat one bite
END WHILE
Real-life example: "Keep stirring until smooth"
3. Collection Loop (FOR EACH)
Use when you want to do something to every item in a group:
FOR EACH [shirt] IN [wardrobe]
Check if shirt is clean
END FOR EACH
Real-life example: "Check each email in inbox"
Loops in Daily Life
You use loops all the time without thinking:
| Loop Type | Daily Example |
|---|---|
| FOR | "Brush each tooth" (32 times) |
| WHILE | "Wait while water is boiling" |
| FOR EACH | "Say goodbye to each guest" |
| WHILE | "Keep scrolling until you find the post" |
| FOR | "Climb 10 stairs" |
The Danger: Infinite Loops
What happens if a loop never stops?
WHILE [true]
Say "Hello"
END WHILE
This never stops! 😱
This is called an infinite loop and it's one of the most common bugs in programming. The condition must eventually become false, or the loop will run forever.
Good practice: always ask "How does this loop end?"
WHILE [water is not boiling]
Wait 1 minute
Check water
END WHILE
This will end when water boils ✓
Part 3: Combining Conditions and Loops
The real power comes from combining these concepts:
Example: Simple Alarm Clock
SET alarm_time = 7:00 AM
WHILE [current_time < alarm_time]
Sleep
END WHILE
// Alarm goes off
WHILE [user has not pressed snooze OR dismiss]
Play alarm sound
END WHILE
IF [user pressed snooze]
Wait 10 minutes
Go back to alarm loop
ELSE
Turn off alarm
END IF
Example: ATM Withdrawal
Ask user for PIN
SET attempts = 0
WHILE [attempts < 3]
IF [PIN is correct]
Ask for amount
IF [amount <= balance]
Dispense cash
Update balance
Print receipt
EXIT
ELSE
Show "Insufficient funds"
END IF
ELSE
attempts = attempts + 1
Show "Incorrect PIN"
END IF
END WHILE
IF [attempts >= 3]
Lock card
Show "Card locked, contact bank"
END IF
Notice how loops and conditions work together to handle different scenarios.
Visualizing a Loop
Here's what a loop looks like in a flowchart:
┌─────────────┐
│ START │
└──────┬──────┘
│
▼
┌─────────────────┐
│ counter = 1 │
└────────┬────────┘
│
┌───────────▼───────────┐
│ │
▼ │
┌─────────┐ │
╱ counter ╲ No │
╱ <= 10? ╲────────────────┼─────┐
╲ ╱ │ │
╲ ╱ │ │
└────┬───┘ │ │
│ Yes │ │
▼ │ │
┌───────────────┐ │ │
│ Print counter │ │ │
└───────┬───────┘ │ │
│ │ │
▼ │ │
┌───────────────┐ │ │
│ counter = │ │ │
│ counter + 1 │──────────────┘ │
└───────────────┘ │
│
┌──────────────────────┘
│
▼
┌───────────┐
│ END │
└───────────┘
The arrow going back up is what makes it a loop — it keeps repeating until the condition is false.
Practice Exercise
Exercise 1: Write Conditions
Convert these decisions into IF-THEN-ELSE format:
- "If it's after 10 PM, go to bed"
- "If the traffic light is green, go. If yellow, slow down. If red, stop."
- "If you have milk and eggs, make breakfast. Otherwise, go to the store."
Solutions
1.
IF [time > 10 PM]
THEN go to bed
END IF
2.
IF [light is green]
THEN go
ELSE IF [light is yellow]
THEN slow down
ELSE
stop
END IF
3.
IF [have milk] AND [have eggs]
THEN make breakfast
ELSE
go to store
END IF
Exercise 2: Identify the Loop Type
What type of loop (FOR, WHILE, FOR EACH) would you use for:
- Washing each dish in the sink
- Running until you're tired
- Doing exactly 100 jumping jacks
- Checking each item in your shopping cart
- Waiting until your friend arrives
Answers
- FOR EACH — iterate through each dish
- WHILE — condition-based (until tired)
- FOR — exact count (100 times)
- FOR EACH — iterate through items
- WHILE — condition-based (until friend arrives)
Exercise 3: Fix the Infinite Loop
These loops have problems. Identify and fix them:
Loop A:
WHILE [1 = 1]
Print "Hello"
END WHILE
Loop B:
SET count = 10
WHILE [count > 0]
Print count
END WHILE
Problems and Solutions
Loop A Problem: 1 = 1 is always true — infinite loop!
Fix: Add a counter or condition that can become false
SET times = 0
WHILE [times < 5]
Print "Hello"
times = times + 1
END WHILE
Loop B Problem: count is never decreased — infinite loop!
Fix: Decrease count inside the loop
SET count = 10
WHILE [count > 0]
Print count
count = count - 1
END WHILE
Exercise 4: Combine Conditions and Loops
Write pseudo-code for a simple game:
- The user thinks of a number between 1 and 100
- The computer guesses numbers
- The user says "higher", "lower", or "correct"
- The game ends when the computer guesses correctly
Example Solution
SET low = 1
SET high = 100
SET found = false
WHILE [found is false]
SET guess = (low + high) / 2 (rounded)
Show "Is it [guess]?"
Get user response
IF [response is "correct"]
found = true
Show "I won!"
ELSE IF [response is "higher"]
low = guess + 1
ELSE IF [response is "lower"]
high = guess - 1
END IF
END WHILE
Key Takeaways
- Conditions (IF-THEN-ELSE) let algorithms make decisions based on whether something is true or false
- Loops let algorithms repeat actions without writing the same code multiple times
- Three main loop types: FOR (known count), WHILE (until condition is false), FOR EACH (for every item)
- Combine conditions with AND (both true) and OR (at least one true)
- Always ensure loops can end — infinite loops are a common bug
- Real algorithms combine conditions and loops to handle complex logic
Resources
| Resource | Type | Difficulty |
|---|---|---|
| Conditionals - Khan Academy | Interactive | Beginner |
| Loops - BBC Bitesize | Tutorial | Beginner |
| Control Flow - Scratch | Practice | Beginner |