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 Expression is evaluated, if the expression is true, code block executed, else false for loop exit from the loop
  • if the expression is true, code block executed and updateIteration code executed and updated
  • Conditional expression is evaluated with updated value, Repeat the loop until the expression is evaluated to false.

Here is an example to the sum of 10 numbers using for 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

Continue statement in for loop used to continue the execution. `` statement is used to break the execution from for loop.

continue and break 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;
    }
}