Skip to content

SpecificationVI · Control flow

6.6

Walking collections with For Each

For Each visits the elements of a vector, an array or a dictionary one by one, without indices.

Markdown version

6.6.1 How to write it

For Each «elemento» In «colección» Do
  «instrucciones»
EndFor
For Each «clave», «valor» In «diccionario» Do
  «instrucciones»
EndFor

6.6.2 How it works

The collection is computed once. Then every element is visited in order: from position 0 onwards for vectors and arrays, and in insertion order for dictionaries. An empty collection does not run the body.

ProgramWalking a vector

Algorithm Mochila
  Define lista As Vector<String> <- vector();
  lista.append("pan");
  lista.append("leche");
  lista.append("huevos");
  For Each producto In lista Do
    Write "- ", producto;
  EndFor
EndAlgorithm

Output

- pan
- leche
- huevos

The program finishes normally.

  1. 1First round: producto is "pan".

  2. 2Second round: producto is "leche".

  3. 3Third round: producto is "huevos". There are no more and the traversal ends.

Figure 6.6-1.The traversal moves through the cells in order. On every round, producto holds a copy of the visited element.

A vector with pan, leche and huevos at positions 0, 1 and 2. A frame moves through each cell and producto takes the value of the framed cell.

With a dictionary two names are needed, the key and the value:

ProgramWalking a dictionary

Algorithm Edades
  Define edades As Dictionary<String, Integer> <- dictionary();
  edades["Ana"] <- 12;
  edades["Leo"] <- 11;
  For Each nombre, edad In edades Do
    Write nombre, ": ", edad;
  EndFor
EndAlgorithm

Output

Ana: 12
Leo: 11

The program finishes normally.

In short

  • For Each visits every element in order, without indices.
  • With dictionaries two names are written: key and value.
  • The element name cannot be assigned.
  • Changing the structure of the collection during the traversal is a failure.