In this tutorial, you learn how to use for loop in Solidity contract programming with the help of examples.
solidity for loop
Syntax:
for (Initialize; Conditional Expression; updateIteration;) {
// Code block
}
For loop execution process:
- Initialize code run only once
Conditional Expressionis evaluated, if the expression is true, the code block is executed, else false for loop exit from the loop- if the expression is true, the code block is executed and the
updateIterationcode is executed and updated - Conditional expression is evaluated with updated value, Repeat the loop until the expression is evaluated to false.
Here is an example of the sum of 10 numbers used for the loop in solidity
pragma solidity ^0.5.0;
// for loop test
contract whileTest {
uint result = 0;
function sum() public returns(uint data){
for(uint i=0; i<10; i++){
result=result+i;
}
return result;
}
}
Output
"0": "uint256: data 45"
solidity for loop continue and break statements
The Continue statement in for loop is used to continue the execution.
`` statement is used to break the execution from for loop.
continue and break are also used in while loop
Here is an example for a break and continue in for loop
pragma solidity ^0.5.0;
// for loop test
contract whileTest {
uint result = 0;
function sum() public returns(uint data){
for (uint i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
if (i == 5) {
break;
}
}
return result;
}
}