Like most other languages, Grace has a for ... do
statement that allows you to repeat
a block of code a fixed number of times — very much like a repeat ... times
statement.
It looks like this:
for («collection») do { «variable» →
«statements»
}
where the quoted components «collection»
, «variable»
, and «statements»
must be replaced by Grace program elements.
Compared to repeat, there are two important differences.
- The first argument to
for(_)do(_)
is not a single number, but some kind of collection of objects. One of the simplest kinds of collection is a range of numbers, like2..6
, which contains the five numbers2
,3
,4
,5
and6
.
The block of code that followsdo
will be executed as many times as there are elements in this collection. So, for this example,for (2..6) do { «variable» → «statements» }
it will be executed five times.
- The second argument — the block of code after
do
— must declare a single variable to play the role of parameter to the block. The«variable»
comes immediately after the opening brace, and is separated from the body of the block by an arrow→
(or->
), like this:for (2..6) do { num → «statements» }
Here the variable
num
is used as the parameter. On each execution of the block, the«variable»
num
takes on a new value: the next element of the collection. The variablenum
is like a parameter in a method, because each time the block is executed,num
takes on a potentially different value. So, in the example above, on the first execution thenum
will have the value2
, on the second executionnum
will be3
, and so on, until on the last execution,num
will be 6.
We say that the for loop iterates over the collection.
Like any other variable, you can call the variable anything you want, but it’s wise
to use a name that reminds the reader of what it is. So if you are iterating over numbers,
num
or n
might be a good choice; for characters in a string, ch
might be good.
For indexes in a list, you might use i
or ix
, and so on. I often use the name
each
if no better name suggests itself.
Of course, to make this example runnable, you have to replace «statements»
by the
Grace statements that you want to execute repeatedly. These statements make
up what is called the body of the for loop, and they will normally mention the
loop variable — if they don’t mention it, you might not want to use a for loop!
Here is the complete example:
Another kind of collection object, which you have already met, is a String
.
You can think of a string as a single piece of text, but you can also think
of it as a sequence of individual letters, digits and symbols. A for loop that
uses a string as the first argument is said to iterate over the string.
Here is an example using a string:
If you are still confused about the rôles of the two arguments to for(_)do(_)
,
look at some for loop examples.