Like any programming language, Solidity provides the following while loops

  • while loop
  • do-while loop

It is used to execute multiple lines of code over multiple based on a conditional expression.

Solidity while loop

While loop executes the statements multiple times based on the condition that is true

Syntax:

while(conditional expression){
    // code block
}

a conditional expression is evaluated as true or false. If true, the code block wrapped inside a {} executed until expression is false.

while is a keyword in solidity.

Here is an example


pragma solidity ^0.5.0;

// While loop test
contract whileTest {

    uint8 i = 0;
    uint8 result = 0;

    function sum(
    ) public returns(uint data){
    while(i < 3) {
        i++;
        result=result+i;
     }
      return result;
    }
}

Output

"0": "uint256: data 6"

Solidity do while loop example

the do-while loop is similar to the while loop except that It runs at least one time irrespective of whether the condition is true or false.

If the condition is true, It runs multiple times and stops its execution when the condition is false.

Syntax:

do{
// code block
}while(conditional expression);

conditional expression: evaluated to true or false code block executes for the first time, and executes the second time onwards if the condition is true.

do and while are keywords in solidity.

the do-while loop always ends with a semicolon separator

Here is an example do while loop in solidity.

pragma solidity ^0.5.0;

// While loop test
contract whileTest {

    uint8 i = 0;
    uint8 result = 0;

    function sum(
    ) public returns(uint data){
    do{
        i++;
        result=result+i;
          }
    while(i < 3) ;
      return result;
    }
}