The for loop
One of the most famous and most used loops is the for
loop, and we can use it in Solidity. The general structure of a for
loop is as follows:
for (initialize loop counter; check and test the counter; increase the value of counter;) {
Execute multiple instructions here
}
for
is a keyword in Solidity and it informs the compiler that it contains information about looping a set of instructions. It is very similar to the while
loop; however it is more succinct and readable since all information can be viewed in a single line.
The following code example shows the same solution: looping through a mapping. However, it uses the for
loop instead of the while
loop. The i
variable is initialized, incremented by 1
in every iterator, and checked to see whether it is less than the value of counter
. The loop will stop as soon as the condition becomes false; that is, the value of i
is equal to or greater than counter
: