Loops
While loops
In a while loop, you execute a certain block of code while a condition is true. The syntax is as follows:
The example below counts from 1 to 10:
For loops
A for loop is a more controlled repetition structure when compared to the while loop. For loops support an initialization command, a condition and an increment command. The syntax is as follows:
The code just displayed is equivalent to:
The example below counts from 1 to 10:
Foreach
Foreach loops are used to iterate throughout iterable collections (such as Arrays and Dictionaries). Basically: for each element x
in the iterable collection, do something with x
. The syntax is as follows:
The example below counts from 1 to 10:
The example below iterates over a Dictionary:
dictionary = { "a": 1, "b": 2, "c": 3 };
foreach(entry in dictionary) {
Console.print(entry.key);
Console.print(entry.value);
}
Implementing your own iterable collections
The foreach loop can be used with any iterable collections, not only Arrays and Dictionaries. You may even implement your own!