Quick Guide To Solidity Loops

In this discussion, we will explore the various types of Solidity loops and how they can be used in smart contract with examples.

As you are writing a contract, there is a possibility that you will encounter a situation where you will have to carry out an action again and again.

As a result, in such cases, a loop statement would be necessary so that there would be fewer lines to write.



Solidity Loops Types

Solidity loops are an essential tool for building smart contracts as they allow for efficient and precise execution of repetitive tasks.

It is extremely easy to write programs with Solidity, since it supports all the required loops to ease the programming process.

Solidity has three types of loops:

  1. The for loop
  2. The while loop
  3. The do-while loop

Each loop has its own unique syntax and use cases.

It’s important to use loops carefully in Solidity as they can consume a significant amount of gas, which can make the smart contract expensive to execute.

Gas is the unit of currency used in the Ethereum network to measure the computational resources required to execute a transaction or smart contract.

Remember: Each operation in Solidity requires a certain amount of gas, and loops are no exception.

To optimize gas usage in loops, it’s important to keep the number of iterations to a minimum and avoid unnecessary operations inside the loop.

Recommendation: it is recommended to use the uint256 data type for loop variables to avoid overflow errors.

Solidity For Loop

For loops are the simplest loops used in Solidity that used to execute a block of code a fixed number of times.

Three significant parts of the for loop are listed below.

 

Syntax StatementsOverview
Initialization statementThe first step in the loop is to initialize our variable to a starting value. Prior to starting the loop, the initialization statement is executed.
Test StatementAn expression that tests whether a given condition is true or not. In the event that the condition is true, the code within the loop is executed; otherwise, the loop is terminated.
Iteration StatementIteration statements allow you to increase or decrease your counter.

The three parts can be put on a single line by separating them using semicolons ;.

Syntax

The basic syntax of the for loop is given below:

for (initialization; test condition; iteration statement) {

//The given block of code will be executed if the condition is met

}

In below example for loop will prints all the even numbers till 30:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint[] data; uint loop_variable;function for_loop_working() public returns(uint[] memory){for(loop_variable=0;loop_variable<=30;loop_variable++){if(loop_variable%2==0){ data.push(loop_variable); } } return data; } }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>
The example below illustrates the working of for loop to print the value from the array:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{string[] america_Famous_Resturants=["Anajak Thai","Andiario","Apteka","Audrey","Bacanora","Bonnies","Brennans"];uint loop_variable;function for_loop_working() public returns(string[] memory){for(loop_variable=0;loop_variable<america_Famous_Resturants.length;loop_variable++){ america_Famous_Resturants[loop_variable];} return america_Famous_Resturants; } }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

While Loop In Solidity

The purpose of a while loop is to repeat the execution of a statement or code block over and over again for as long as a certain expression met true.

As soon as the expression becomes false, the loop will terminate.

Syntax

While loops in Solidity have the following syntax:

while (expression) {

//This statement (or statements) will be executed if the expression is true

}

You can implement a while loop by following the example below.

The following programme prints the natural numbers from 1 to 10:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint [] data; // An array of integer is created in order to store the elements at every iteration uint loop_variable=0; // The looping Element is initialized herefunction While_Loop_Working() public returns (uint[] memory){ // Function of While loop is declared herewhile(loop_variable<10){ // Loop is initialized here loop_variable++; // An increament in looping element is done here data.push(loop_variable); // Here we use the built in push function to keep elements in the data array } return data; // The value of data array is printed here}}
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>
The below example displays all the elements from an array of America’s Airports List:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{string[] list_of_Airports=["Denver International Airport","Los Angeles International Airport","Chicago O'Hare International Airport","Dallas/Fort Worth International Airport","Denver International Airport"]; // An array of integer is created in order to store the elements at every iteration uint loop_variable=0; // The looping Element is initialized herefunction While_Loop_Working() public returns (string[] memory){ // Function containing the while loop is declared herewhile(loop_variable<list_of_Airports.length){ // Loop is initialized here list_of_Airports[loop_variable]; // The increamented loop_variable will be used as an index to print the string array loop_variable++; // An increament in looping element is done here } return list_of_Airports; // The values of array list_of_Aiports is shown} }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

Do-while loop In Solidity

This loop is similar in many ways to the while loop except that it performs the condition check at the very end of the loop rather than at the beginning.

There will always be at least one execution of the loop regardless of whether the condition is true or false.

Syntax

In Solidity, you can create a do-while loop using the following syntax:

do {
//The following lines of code will be executed during the working of Do-While Loop;
} while (expression);

The given programme prints the table of 13 :

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint[] data; uint mrx=13;uint loop_variable=0;function get_Table() public returns(uint[] memory){do{ loop_variable++; uint value= mrx*loop_variable; data.push(value); } while(loop_variable<=10); return data; } }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>
The table will be printed till 11 as the condition is checked after execution.

Another example shows the numbers from 20 to 0 in a reverse order using the do while loop:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint[] data;uint loop_variable=21;function get_Value() public returns(uint[] memory){do{ loop_variable--; data.push(loop_variable); } while(loop_variable>0); return data; } }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

Solidity Loop Control

In Solidity, loops and switch statements can be handled with full control.

When you’re inside a loop, you may have circumstances where you want to exit it before you’ve reached the bottom of the loop.

Additionally, it may occur that there will be a situation where you want to skip a part of the code block and go straight to the next iteration of the loop in the meantime.

As a result, Solidity provides break and continue statements that can handle all such situations. If you use these statements, you will be able to immediately exit any loop or you will be able to start the next iteration of any loop immediately.


Solidity break Statement

Break statements, which were briefly introduced with the switch statement, are used as a way to break out of a loop.

This allows the skipping of the code under the curly brackets {}.

The following example shows the working of the break statement.

The following example prints all the odd number from 1 to 10 and then skips the loop because of the presence of the break statement:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint loop_Element; uint []odd_numbers;function get_Odd_Numbers() public returns(uint[] memory){for(loop_Element=1;loop_Element<=40;loop_Element++){ if(loop_Element % 2 ==1){ if(loop_Element==11){ break; }odd_numbers.push(loop_Element); } } return odd_numbers; } }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>
The following example shows the working of break statement in a more simplest form:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint loop_Element; uint []factorial_numbers; uint fact=1;function get_Factorial() public returns(uint[] memory){for(loop_Element=1;loop_Element<=20;loop_Element++){if(loop_Element == 10){ break; } else{ fact=fact*loop_Element;factorial_numbers.push(fact); } } return factorial_numbers; }}
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

Solidity continue Statement

When the interpreter encounters the continue syntax, it will immediately start the next iteration of the loop and skip the remainder of the remaining code blocks in the loop.

In the case of a continue statement, the program flow immediately moves to the loop check expression and if the condition remains true, then it initiates the next iteration, otherwise it exits the loop and prints the block of code outside the loop.

The given example shows the use of continue statement:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint loop_Element; uint []numbers;function get_Multiples_of_5() public returns(uint[] memory){for(loop_Element=1;loop_Element<=20;loop_Element++){if(loop_Element==5){continue; }uint value=loop_Element*5; numbers.push(value); } return numbers; } }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

The following example will shows string 10 natural numbers except 2,4,6 using continue statement:

Example: 

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract SolidityTest{uint loop_Element; uint []numbers;function get_Natural_Numbers() public returns(uint[] memory){for(loop_Element=1;loop_Element<=10;loop_Element++){if(loop_Element==2 || loop_Element==4 || loop_Element==6){continue;}uint value=loop_Element; numbers.push(value);} return numbers; } }
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

Conclusion

Solidity loops are a crucial part, allowing developers to execute a block of code repeatedly based on certain conditions.

When used effectively, Solidity loops can improve the efficiency and readability of your code, enabling you to perform complex operations with ease. However, it is important to use loops judiciously and avoid infinite loops, which can lead to performance issues and even crash your program.

With a solid understanding of Solidity loops, you can write efficient and effective smart contracts that can power a wide range of decentralized applications.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *