---
title: "While, For and Repeat Loops Explained with Pseudocode: Programming Fundamentals (8)"
date: "2026-10-04"
description: "Learn While, Repeat Until and For loops with runnable pseudocode: counters, accumulators, Break, Continue, nested loops and how to pick the right loop."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-loops/"
author: "Rolando Andrade"
---

# 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`, `Repeat` and `For`.
- Count and add values with counters and accumulators.
- Leave a loop early with `Break` and skip an iteration with `Continue`.
- 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](/blog/programming-fundamentals-conditionals/) 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.

**While: factorial** (StepCode)

```stepcode
Program Factorial
    Define n, i, factorial As Integer;
    Write "Enter a number:";
    Read n;
    factorial <- 1;
    i <- n;
    While i > 1 Do
        factorial <- factorial * i;
        i <- i - 1;
    EndWhile
    Write n, "! = ", factorial;
EndProgram
```

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:

```python
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](/blog/programming-fundamentals-arrays/#2-sum-and-average-a-list-of-grades).

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](/blog/programming-fundamentals-operators-and-expressions/#arithmetic-operators): `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`.

**Accumulator: sum of digits** (StepCode)

```stepcode
Program SumOfDigits
    Define n, total, digit As Integer;
    Write "Enter n:";
    Read n;
    total <- 0;
    While n > 0 Do
        digit <- n Mod 10;
        total <- total + digit;
        n <- n Div 10;
    EndWhile
    Write "The sum of its digits is: ", total;
EndProgram
```

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.

*Figure: Press Next step to run one iteration. The last digit leaves n (that is n Mod 10) and goes into total, and n gets one digit shorter (that is n Div 10). The loop stops when n reaches 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](/blog/programming-fundamentals-conditionals/#switch-for-one-value), now inside a loop.

**Repeat: a calculator that keeps going** (StepCode)

```stepcode
Program CalculatorLoop
    Define a, b As Real;
    Define operation, again As Char;
    Repeat
        Write "First number:";
        Read a;
        Write "Operation (+, -, *, /):";
        Read operation;
        Write "Second number:";
        Read b;
        Switch operation Do
            '+':
                Write "= ", a + b;
            '-':
                Write "= ", a - b;
            '*':
                Write "= ", a * b;
            '/':
                Write "= ", a / b;
            Otherwise:
                Write "I do not know that operation";
        EndSwitch
        Write "Another one? (y/n)";
        Read again;
    Until again = 'n' Or again = 'N';
    Write "Bye!";
EndProgram
```

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.

**For: multiplication table** (StepCode)

```stepcode
Program MultiplicationTable
    Define n, i As Integer;
    Write "Table of:";
    Read n;
    For i <- 1 To 10 Step 1 Do
        Write n, " x ", i, " = ", n * i;
    EndFor
EndProgram
```

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.

**For with Step: count by two and count down** (StepCode)

```stepcode
Program EvenNumbers
    Define i As Integer;
    For i <- 0 To 20 Step 2 Do
        WriteNoNewline i, " ";
    EndFor
    Write "";
    For i <- 5 To 1 Step -1 Do
        WriteNoNewline i, " ";
    EndFor
    Write "Go!";
EndProgram
```

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.

*Figure: Pick a loop and watch the counter hop. Step sets the size of each hop, and a negative step walks backward. In pseudocode the counter reaches the end value. In Python, range stops one step before it.*

## 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.

**Continue: skip multiples of 3** (StepCode)

```stepcode
Program SkipMultiplesOf3
    Define i, total As Integer;
    total <- 0;
    For i <- 1 To 10 Step 1 Do
        If i Mod 3 = 0 Then
            Continue;
        EndIf
        WriteNoNewline i, " ";
        total <- total + i;
    EndFor
    Write "";
    Write "Total: ", total;
EndProgram
```

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](/blog/programming-fundamentals-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.

**Nested loops: a mosaic** (StepCode)

```stepcode
Program Mosaic
    Define side, row, column As Integer;
    Write "Side:";
    Read side;
    For row <- 1 To side Step 1 Do
        For column <- 1 To side Step 1 Do
            If (row + column) Mod 2 = 0 Then
                WriteNoNewline "🟦";
            Else
                WriteNoNewline "🟩";
            EndIf
        EndFor
        Write "";
    EndFor
EndProgram
```

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.

*Figure: The outer loop picks a row and the inner loop walks every column of that row. The column number goes 1 to 5 again for each row, so the inner body runs 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.

**Part 1: count the divisors** (StepCode)

```stepcode
Program Prime
    Define n, divisor, divisors As Integer;
    Write "Enter a number:";
    Read n;
    divisors <- 0;
    For divisor <- 1 To n Step 1 Do
        If n Mod divisor = 0 Then
            divisors <- divisors + 1;
        EndIf
    EndFor
    Write n, " has ", divisors, " divisors";
EndProgram
```

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.

**Part 2: decide, and count the turns** (StepCode)

```stepcode
Program Prime
    Define n, divisor, divisors, turns As Integer;
    Write "Enter a number:";
    Read n;
    divisors <- 0;
    turns <- 0;
    For divisor <- 1 To n Step 1 Do
        turns <- turns + 1;
        If n Mod divisor = 0 Then
            divisors <- divisors + 1;
        EndIf
    EndFor
    If divisors = 2 Then
        Write "The number ", n, " is prime.";
    Else
        Write "The number ", n, " is not prime.";
    EndIf
    Write "The loop ran ", turns, " times.";
EndProgram
```

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.

*Figure: Divisors come in pairs, and the dashed line is the square root of n. The small partner of every pair is on the left, so a loop that stops at the line still finds a divisor when there is one. Try 1000003.*

**Part 3: a faster loop** (StepCode)

```stepcode
Program Prime
    Define n, divisor, turns As Integer;
    Define isPrime As Boolean;
    Write "Enter a number:";
    Read n;
    isPrime <- n > 1;
    divisor <- 2;
    turns <- 0;
    While divisor * divisor <= n Do
        turns <- turns + 1;
        If n Mod divisor = 0 Then
            isPrime <- False;
            Break;
        EndIf
        divisor <- divisor + 1;
    EndWhile
    If isPrime Then
        Write "The number ", n, " is prime.";
    Else
        Write "The number ", n, " is not prime.";
    EndIf
    Write "The loop ran ", turns, " times.";
EndProgram
```

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.

**Part 4: check many numbers** (StepCode)

```stepcode
Program Prime
    Define n, divisor As Integer;
    Define isPrime As Boolean;
    Repeat
        Write "Enter a number (0 to exit):";
        Read n;
        If n <> 0 Then
            isPrime <- n > 1;
            divisor <- 2;
            While divisor * divisor <= n Do
                If n Mod divisor = 0 Then
                    isPrime <- False;
                    Break;
                EndIf
                divisor <- divisor + 1;
            EndWhile
            If isPrime Then
                Write "The number ", n, " is prime.";
            Else
                Write "The number ", n, " is not prime.";
            EndIf
        EndIf
    Until n = 0;
    Write "Bye!";
EndProgram
```

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`.

*Figure: Where each loop checks its condition. Press Stop at once: While and For check first, so their body runs 0 times. Repeat checks last, so its body still runs once.*

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
```

**Solution: sum of a range** (StepCode)

```stepcode
Program SumRange
    Define start, finish, total, n As Integer;
    Write "Start:";
    Read start;
    Write "End:";
    Read finish;
    total <- 0;
    For n <- start To finish - 1 Step 1 Do
        total <- total + n;
    EndFor
    Write "Answer: ", total;
EndProgram
```

### 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 
```

**Solution: Fibonacci series** (StepCode)

```stepcode
Program Fibonacci
    Define n, previous, current, nextValue, i As Integer;
    Write "Enter n:";
    Read n;
    previous <- 0;
    current <- 1;
    For i <- 1 To n Step 1 Do
        WriteNoNewline previous, " ";
        nextValue <- previous + current;
        previous <- current;
        current <- nextValue;
    EndFor
    Write "";
EndProgram
```

### 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
```

**Solution: Collatz conjecture** (StepCode)

```stepcode
Program Collatz
    Define n As Integer;
    Write "Enter a number:";
    Read n;
    Write n;
    While n <> 1 Do
        If n Mod 2 = 0 Then
            n <- n Div 2;
        Else
            n <- n * 3 + 1;
        EndIf
        Write n;
    EndWhile
EndProgram
```

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
```

**Solution: average until done** (StepCode)

```stepcode
Program AverageUntilDone
    Define answer As String;
    Define total As Real;
    Define count As Integer;
    total <- 0;
    count <- 0;
    Write "Type done to calculate the average.";
    Write "Enter a grade or done:";
    Read answer;
    While Lower(answer) <> "done" Do
        total <- total + ToNumber(answer);
        count <- count + 1;
        Write "Enter a grade or done:";
        Read answer;
    EndWhile
    If count > 0 Then
        Write "The average is ", total / count;
    Else
        Write "No grades";
    EndIf
EndProgram
```

`Lower` makes the check work for `done`, `Done` and `DONE`. You will meet it, with the other text tools, in the [next lesson](/blog/programming-fundamentals-strings/#the-tools-for-strings). The `If` at the end protects against a division by zero when the first answer is already `done`.

All these editors run on [StepCode](/projects/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

- `While` checks before the body, `Repeat` checks after it, and `For` counts 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.
- `Break` leaves a loop early and `Continue` skips 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](/blog/programming-fundamentals-strings/), you use loops to work with text one character at a time.
