Lesson 3

Ranges, loops & iteration

Goal

Write [1..n] ranges, iterate with for … do … od, and loop with while - the control flow underneath every script you'll reconstruct.

Concept

A range is a list in disguise: [1..10] is the list [1,2,…,10], stored compactly. Anywhere a list works, a range works. A for loop walks any list (or range), binding a variable to each element. GAP statements inside a loop end in ;, and the loop body is closed by od (that's do spelled backwards. Like BASH, GAP's block-closers are reversed keywords: od, fi, elif). You usually type a whole loop across several lines; GAP shows a > continuation prompt until you close it with od;.

Commands to try

[1..10];

Expect [ 1 .. 10 ], GAP prints it as a range, not expanded, but it behaves as the full list. Confirm:

[1..10][4];
Length([1..10]);
Sum([1..100]);

Expect 4, 10, 5050. (Sum of a list adds its elements.)

[2,4..10];

Step ranges: start, second element (sets the step), end. Expect [ 2, 4, 6, 8, 10 ]. The step is second - first.

A for loop

Type this across lines; GAP waits at > until od;:

total := 0;;
for k in [1..5] do
  total := total + k*k;
od;
total;

Expect 55 (the sum of the first five squares). k ranges over the list; the body runs once per element.

You can loop over any list, not just ranges:

for p in [2,3,5,7] do
  Print(p, " squared is ", p^2, "\n");
od;

Print writes without the [ ] decoration; "\n" is a newline. Note Print returns nothing: it's for side effects, unlike evaluating an expression.

A while loop

n := 1;;
while 2^n < 1000 do
  n := n + 1;
od;
n;

Predict n before running: the smallest n with 2^n ≥ 1000. (2^10 = 1024.)

Predict-then-check

Before evaluating, say what each returns:

Length([5,10..100]);
[1..0];

The first is a counting question. The second is the empty range. GAP allows [a..b] with b < a and gives [ ]. Predict both, then check.

Exercise

  1. Use a single Sum over a step-range to add the odd numbers 1,3,5,…,99.
  2. Write a for loop that builds a list cubes of the cubes of 1..6. Start with cubes := []; and Add inside the loop. (Next lesson shows the one-liner that replaces this, but do it the long way once.)
  3. Write a while loop to find the smallest k with Factorial(k) > 10^6. Predict k first.

Pitfalls

  • Block closers are reversed words: do…od, if…fi. Forgetting od; leaves you stuck at the > continuation prompt: type od; to finish.
  • [a,b..c]: the second entry sets the step, it is not "step then stop". [2,4..10] steps by 2; [2..10] steps by 1.
  • A range prints as [ 1 .. 10 ] but is a genuine list. Don't be thrown off.
  • Print has no return value and adds no brackets/quotes; evaluating x; shows GAP's structured view. Use Print for formatted output, bare x; to inspect.
  • Modifying the list you're looping over mid-loop is asking for trouble; build a new one instead.
← Back to Learning GAP - Part 1: Foundations