The while loop
There are times when we need to execute a code segment repeatedly based on a condition. Solidity provides while
loops precisely for this purpose. The general form of the while
loop is as follows:
Declare and initialize a counter
while (check the value of counter using an expression or condition) {
Execute the instructions here
Increment the value of counter
}
while
is a keyword in Solidity and it informs the compiler that it contains a decision control instruction. If this expression evaluates to true then the code instructions that follow in the pair of double-brackets {
and }
should be executed. The while
loop keeps executing until the condition turns false.
In the following example, mapping
is declared along with counter
. counter
helps loop the mapping
since there is no out-of-the-box support in Solidity to loop mapping
.
An event is used to get details about transaction information. We will discuss events in detail in the Events and Logging section in Chapter 8, Exceptions...