Solidité - Boucle While

La boucle la plus élémentaire de Solidity est la whileboucle qui sera discutée dans ce chapitre. Le but d'unwhile boucle consiste à exécuter une instruction ou un bloc de code à plusieurs reprises tant qu'un expressionest vrai. Une fois que l'expression devientfalse, la boucle se termine.

Organigramme

L'organigramme de while loop ressemble à ceci -

Syntaxe

La syntaxe de while loop dans Solidity est la suivante -

while (expression) {
   Statement(s) to be executed if expression is true
}

Exemple

Essayez l'exemple suivant pour implémenter la boucle while.

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;
      
      while (_i != 0) { // while loop
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);
   }
}

Exécutez le programme ci-dessus en suivant les étapes fournies dans le chapitre Application Solidity First .

Production

0: string: 12