Loops are very helpful when we need to repeat the execution of a piece of code a certain number of times. Rather than copying and pasting the same lines of code, making the code block longer, we use this programming construct to add brevity to our code. Loops can be finite or infinite in nature. For the infinite loop, we generally provide a break statement to come out of it.
The smart contract in Figure 3.16 is using a finite loop to calculate the summation of a finite number of integers:
Figure 3.16: Loop inside a Solidity smart contract
The output on remix IDE is shown in Figure 3.17. As discussed earlier, keep a watch on the amount of ethers that is getting decreased in the Account
tab for each call of the myFirstLoop
function:
Figure 3.17: Execution of myFirstLoop inside a smart contract
The best way to check the inner working of a loop in runtime is to go to the Launch debugger
tab and manually push the horizontal scroll bar from left to right, as shown in Figure 3.18. Try...