Solidity – do…while loop

Solidity - do...while loop

This topic is about Solidity – do…while loop.

The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Flow Chart

The flow chart of a do-while loop would be as follows −

Syntax

The syntax for do-while loop in Solidity is as follows −

do {
   Statement(s) to be executed;
} while (expression);

Note − Don’t miss the semicolon used at the end of the do…while loop.

Example

Try the following example to learn how to implement a do-while loop in Solidity.

pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; 
   constructor() public{
      storedData = 10;   
   }
   function getResult() public view returns(string memory){
      uint a = 10; 
      uint b = 2;
      uint result = a + b;
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {
      
      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;
      
      while (j != 0) {
         len++;
         j /= 10;
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      
      do {                   // do while loop	
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      while (_i != 0);
      return string(bstr);
   }
}

Run the above program using steps provided in Solidity First Application chapter.

Output

0: string: 12

In this topic we learned about Solidity – do…while loop. To know more, Click Here.

This Post Has 2 Comments

Leave a Reply