Loops

Learn about loops in this lesson.

In this lesson, we’ll explore the various looping constructs available in Solidity, which enable us to efficiently carry out repetitive tasks within our smart contracts. Loops are crucial tools for executing specific actions multiple times, optimizing code, and reducing redundancy. Solidity offers different types of loops, each serving unique purposes and scenarios.

The following loops are supported by Solidity:

  • while

  • do-while

  • for

Let’s explore examples of each loop type implemented in Solidity contracts.

The while loop

The while loop is a fundamental looping construct in Solidity. It repeatedly executes a block of statements as long as a specified condition remains true. Once the condition evaluates to false, the loop concludes. The while loop is particularly useful when we need to perform a set of instructions until a specific condition is met. Its syntax is as follows:

while (condition) {
// Perform operations until the condition evaluates to true
}
The syntax of a while loop

The following Solidity contract demonstrates the use of the while loop:

Press + to interact
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract LoopDemo{
// Declaring a dynamic array
uint[] store;
// Declaring a state variable
uint8 index = 0;
// Defining the whileLoop() Function to check the while loop operatopn
function whileLoop() public returns(uint[] memory){
// Loop run until this condition evaluates to true
while(index < 5)
{
index++;
store.push(index);
}
return store;
}
}
...