WHILE Loop (Pre-counted Loop – Turns) Explanation – O Level 2210
A WHILE loop is a type of loop used when we want to repeat a set of instructions as long as a condition is true.
It checks the condition before entering the loop — this is why it is called a pre-condition loop or pre-checked loop.When we use a WHILE loop for a fixed number of turns, we call it a pre-counted loop because the number of repetitions is based on a counter that controls how many turns the loop runs.
How a WHILE Loop Works
The condition is checked first.
If the condition is true, the loop runs.
After running the instructions, the condition is checked again.
The loop stops when the condition becomes false.
Pseudocode Example (Pre-counted Turns)
Example: Display numbers 1 to 5 using a WHILE loop
Explanation of Example
The counter
countstarts at 1Before each turn, we check:
count <= 5If it’s true, the loop runs
After printing the number, the counter is increased by 1
When
countbecomes 6, the condition becomes false and the loop stopsThis loop runs 5 turns in total.
Why Use a WHILE Loop? (Benefits)
1. Condition is checked before running
Useful when you want the loop to run only if a given condition is true.
2. Flexible
You can stop the loop based on:
Counter
User input
Sensor values
Calculations
3. Good for unknown or changing repetitions
While a FOR loop is ideal when repetitions are fixed,
a WHILE loop is better when repetitions depend on a condition.4. Can also be used as a pre-counted loop
By using a counter (like
count ← count + 1),
you can run it for a specific number of turns — just like a FOR loop.
Student-Friendly Summary
A WHILE loop repeats instructions as long as its condition is true.
Because the condition is checked before running the loop, it is called a pre-condition loop.
When used with a counter, it becomes a pre-counted loop that runs for a fixed number of turns.
Instructions
0/1
Paper 2 – Problem Solving Approach -Practical
0/102
Databases
0/1
Past Paper-2 May/June 2025
Paper 1 – Theory
0/20
Past Paper-1 May/June 2025
Download Files
0/1
