While, For and Repeat Loops Explained with Pseudocode: Programming Fundamentals (8)
Learn While, Repeat Until and For loops with runnable pseudocode: counters, accumulators, Break, Continue, nested loops and how to pick the right loop.
A loop is an instruction that runs a group of lines again and again, while a condition holds or a fixed number of times. Each run of the group is called an iteration. With loops, a short program can do a large amount of work: add a thousand numbers, check a million divisors, or ask the user for input until the answer is valid. In this lesson you learn the three loops of pseudocode and when to use each one.
In this lesson you will:
- Repeat code with
While,RepeatandFor. - Count and add values with counters and accumulators.
- Leave a loop early with
Breakand skip an iteration withContinue. - Put one loop inside another.
- Build a prime number checker and make it a thousand times faster.
It takes about 45 minutes. Every example runs in the page.
Why programs repeat
Computers are good at doing the same operation many times without getting tired or making a mistake. That is most of what they do. Without loops, a program that adds the numbers from 1 to 100 needs 100 lines. With a loop, it needs three.
In the last lesson your programs learned to decide. A loop is a decision that comes back: after the body runs, the program checks the condition again. That small change brings two new kinds of bugs. A loop can run one time too many or one time too few. Or it can never stop.
Both bugs are easy to write and hard to see, for people and for AI agents. A loop that an agent wrote can look perfect and still skip the last item of a list, or hang on an input nobody tested. When you review that code, you ask three questions about every loop: where does it start, what changes in each iteration, and what makes it stop. This lesson teaches you to answer them.
The While loop
While checks a condition. If it is true, the body runs, and then the program goes back and checks the condition again. When the condition is false, the program jumps to the line after EndWhile. The loop starts with While condition Do and ends with EndWhile.
Something in the body must change the condition. If nothing changes it, the loop never ends.
The factorial of a number is that number times every whole number below it, down to 1. For example, 8! = 8 Γ 7 Γ 6 Γ 5 Γ 4 Γ 3 Γ 2 Γ 1. This program from class calculates it.
With 8 you see:
Enter a number:
8! = 40320
The line i <- i - 1; is what makes the loop end. Each iteration, i gets smaller, until i > 1 is false.
Python has the same loop with the same name:
n = int(input("Enter a number: "))
factorial = 1
i = n
while i > 1:
factorial = factorial * i
i = i - 1
print(f"{n}! = {factorial}")
Counters and accumulators
Two patterns appear in almost every loop.
- A counter is a variable that goes up by a fixed amount each iteration, usually 1:
count <- count + 1;. It answers βhow manyβ. - An accumulator is a variable that collects values each iteration, usually with a sum:
total <- total + value;. It answers βhow muchβ.
Both need a starting value before the loop. A counter or a sum starts at 0. A product, like the factorial, starts at 1. You will use both patterns on every list of values in Arrays.
This program adds the digits of a number. Two facts from the course guide make it work, and you met both in Operators and expressions: n Mod 10 is the last digit, and n Div 10 removes the last digit. So 123 Mod 10 is 3, and 123 Div 10 is 12.
With 123 you see:
Enter n:
The sum of its digits is: 6
total is the accumulator. It goes from 0 to 3, then 5, then 6. Each iteration, n loses one digit, so the loop ends when no digits are left.
n is 0, so the loop stops. The sum of its digits is 6.
| Iteration | digit | total | n after |
|---|---|---|---|
| 1 | 3 | 3 | 12 |
| 2 | 2 | 5 | 1 |
| 3 | 1 | 6 | 0 |
The Repeat loop
Repeat runs the body first and checks the condition after it. The loop starts with Repeat and ends with Until condition;. It stops when the condition becomes true. That is the opposite of While, which stops when its condition becomes false.
Because the check comes last, the body always runs at least once. That makes Repeat the right loop for menus: the program shows the menu, does the work, and then asks if the user wants to go again. Here is the Switch calculator from Conditionals, now inside a loop.
Type 12, +, 4, y, then 9, /, 2, n. You see:
First number:
Operation (+, -, *, /):
Second number:
= 16
Another one? (y/n)
First number:
Operation (+, -, *, /):
Second number:
= 4.5
Another one? (y/n)
Bye!
Python has no Repeat loop. In Python you write a while True: loop and leave it with break at the end.
The For loop
When you know how many times the body must run, use For. It manages a counter for you. For i <- 1 To 10 Step 1 Do sets i to 1, runs the body, adds 1 to i, and repeats while i is not past 10. The loop ends with EndFor.
This program from class writes the multiplication table of a number.
With 7 you see:
Table of:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Step sets how much the counter changes each iteration. A step of 2 visits every second number. A negative step counts down.
You should see:
0 2 4 6 8 10 12 14 16 18 20
5 4 3 2 1 Go!
In pseudocode, the end value of For is included: 1 To 10 runs with 10. In Python, range(1, 10) stops before 10. Remember this difference when you translate code, or when you check code that an AI translated for you.
For i <- 1 To 10 Step 1 Do
i takes: 1 2 3 4 5 6 7 8 9 10
Break and Continue
Sometimes you want to leave a loop early, before its condition says so. Break; ends the loop at once. The program skips the rest of the body and continues after the end of the loop. You will use it in the prime number checker below: once you find one divisor, there is no reason to keep looking.
Continue; skips only the rest of the current iteration and goes to the next one. This program adds the numbers from 1 to 10 but skips the multiples of 3.
You should see:
1 2 4 5 7 8 10
Total: 37
Use both with care. A loop with many exits is harder to read, because the reader must find every Break to know when it stops.
Nested loops
A loop can contain another loop. The inner loop runs completely for every single iteration of the outer loop. This is how programs work with rows and columns. The outer loop picks the row, and the inner loop walks through the columns of that row. Matrices uses this pattern in every program.
This mosaic comes from the workshop guide of the course. A cell is blue when its row plus its column is even, and green when it is odd.
With 5 you see:
Side:
π¦π©π¦π©π¦
π©π¦π©π¦π©
π¦π©π¦π©π¦
π©π¦π©π¦π©
π¦π©π¦π©π¦
With a side of 5, the inner body runs 5 Γ 5 = 25 times. Nested loops multiply. A side of 1000 means a million iterations, so watch the size of nested loops.
Nested loops fill a 5 by 5 mosaic. The outer loop takes row 1, then the inner loop fills columns 1 to 5 of that row. Then the outer loop takes row 2, and so on. The inner body runs 25 times in total.
row = 5 column = 5 inner body ran 25 of 25 times
Build a prime number checker
A prime number is a whole number greater than 1 that divides only by 1 and by itself. 7 is prime. 12 is not, because it also divides by 2, 3, 4 and 6. Checking primes was a graded activity in the course, and it asked for one more thing: the program had to be fast. You build it in four parts.
1. Count the divisors with a For loop
Try every number from 1 to n. Each time one divides n, add 1 to a counter.
Press Run and type 12.
You should see:
Enter a number:
12 has 6 divisors
2. Decide if the number is prime
A prime has exactly two divisors: 1 and itself. Add that decision after the loop. Add a second counter, turns, that counts how many times the loop runs.
Press Run and type 1000003.
You should see:
Enter a number:
The number 1000003 is prime.
The loop ran 1000003 times.
It is correct, but the loop ran a million times. In the browser you may notice a short wait before the answer.
3. Stop early with While and Break
Two ideas make it faster. First, if n has a divisor, it has one that is not larger than its square root. So you only test divisors while divisor * divisor <= n. Second, the moment you find a divisor, the answer is βnot primeβ, so Break leaves the loop. A Boolean variable, isPrime, holds the answer. It starts as n > 1, because numbers below 2 are never prime.
Divisors come in pairs. For 36 the pairs are 1 times 36, 2 times 18, 3 times 12, 4 times 9 and 6 times 6. In every pair the smaller number is at most 6, the square root of 36. So a loop that tests divisors only up to the square root still finds a divisor whenever one exists. For 1000003 that means at most 999 turns instead of 1000003.
36 is not prime. The fast loop tests 2 to 6: at most 5 turns. The slow loop tests 1 to 36: 36 turns.
Press Run and type 1000003.
You should see:
Enter a number:
The number 1000003 is prime.
The loop ran 999 times.
Same answer, about a thousand times less work. Try 12: the loop runs once, because 2 divides 12 and Break ends it.
4. Check many numbers with Repeat
Wrap the checker in a Repeat loop, so the user can test several numbers. The value 0 ends the program. Now you have a loop inside a loop, and each one has its own job.
Press Run and type 7, 12, -7 and 0.
You should see:
Enter a number (0 to exit):
The number 7 is prime.
Enter a number (0 to exit):
The number 12 is not prime.
Enter a number (0 to exit):
The number -7 is not prime.
Enter a number (0 to exit):
Bye!
Break leaves only the loop it is in. Here it ends the While, and the Repeat keeps going.
Common mistakes
If the program never finishes and the output stops growing, you have an infinite loop. Press Stop. Then look for the line in the body that should move the condition toward its end, like i <- i - 1; or Read answer;. It is missing, or it moves the wrong way.
If you see "total" has no value yet: give it one before using it., it means an accumulator or counter had no starting value. Write total <- 0; before the loop, not inside it. Inside the loop, it would go back to zero every iteration.
If you see The step cannot be 0: the loop would never end., the Step of a For is 0. Use 1 to count up or -1 to count down.
If the result is off by one, check the ends of the range. To add the numbers from 13 up to but not including 23, the loop must go To finish - 1. Run the smallest case by hand, like a range of two numbers, and compare it with the program.
If a While loop never runs, its condition was false from the start. That is normal for While. If the body must run at least once, use Repeat.
Choosing the right loop
In many cases the loops can replace each other. The course compared them like this.
While |
For |
|
|---|---|---|
| Repeats | Until a condition changes | A fixed number of times |
| Flexibility | More, it does not need to know the number of iterations | Less, it needs the number of iterations |
| Typical logic error | Infinite loop | Fewer chances for errors |
And Repeat is the loop for βdo it once, then askβ. The short rule:
- You know the number of iterations before the loop starts:
For. - You repeat until something happens, and it may already be true:
While. - The body must run at least once, like a menu or an input check:
Repeat.
A loop is not the same as a conditional. An If runs its body zero or one time. A loop runs it zero, one or many times.
Practice exercises
These come from the course practice guides. Try each one first, then compare. The numbers must match.
Sum of a range
Ask for a start and an end. Add the numbers from the start (included) to the end (not included).
Inputs 13 and 23 give:
Start:
End:
Answer: 175
Fibonacci series
The Fibonacci series starts with 0 and 1. Each next number is the sum of the two before it. Write the first n numbers.
Input 10 gives:
Enter n:
0 1 1 2 3 5 8 13 21 34
Collatz conjecture
Start from a positive number. If it is even, divide it by 2. If it is odd, multiply it by 3 and add 1. Repeat until you reach 1, and write every number.
Input 6 gives:
Enter a number:
6
3
10
5
16
8
4
2
1
Nobody has proved that this loop ends for every starting number. That is why it is still called a conjecture.
Average until done
Read grades until the user types done. Then write the average. A special value that ends the input, like done, is called a sentinel. ToNumber turns the text into a number.
Inputs 17, 14 and Done give:
Type done to calculate the average.
Enter a grade or done:
Enter a grade or done:
Enter a grade or done:
The average is 15.5
Lower makes the check work for done, Done and DONE. You will meet it, with the other text tools, in the next lesson. The If at the end protects against a division by zero when the first answer is already done.
All these editors run on StepCode. I built it so my students at UCAB could run pseudocode in the browser and watch each variable change, one step at a time.
What you learned
Whilechecks before the body,Repeatchecks after it, andForcounts through a known range.- Every loop needs a start, a change in each iteration, and a stop. Check all three when you review a loop.
- Counters count and accumulators collect. Give them a starting value before the loop.
Breakleaves a loop early andContinueskips to the next iteration.- Nested loops multiply the work, and a smarter stop condition can divide it by a thousand.
Next steps
With sequence, conditionals and loops, you have every control structure a program needs. In the next lesson, strings, you use loops to work with text one character at a time.