DEV Community

Cover image for For Loop in Solidity
Shlok Kumar
Shlok Kumar

Posted on

For Loop in Solidity

The for loop in Solidity is used to execute a statement or block of statements repeatedly as long as the condition is true

The for loop is the most compact kind of loop available. It is comprised of the three essential components listed below:

  • Our counter is initially set to a starting value during the loop startup process. The initialization statement is executed before the start of the loop's execution.

  • The test statement is used to determine whether a particular condition is true or false. If the condition is met, the code contained within the loop will be performed; if it is not, the control will be released from the loop.

  • The iteration statement is where you can change the value of your counter by increasing or decreasing it.

You can put all three pieces on a single line and split them with a semicolon if you want.

Syntax

for (initialization; test condition; iteration statement) {
   Statement(s) to be executed if test condition is true
}
Enter fullscreen mode Exit fullscreen mode

For loop examples

Example 1

pragma solidity ^0.8.0; 
   
// Creating a contract
contract Types { 
     
    // Declaring a dynamic array 
    uint[] data; 
  
    // Defining a function 
    // to demonstrate 'For loop'
    function loop(
    ) public returns(uint[] memory){
    for(uint i=0; i<5; i++){
        data.push(i);
     }
      return data;
    }
} 
Enter fullscreen mode Exit fullscreen mode

Example 2

pragma solidity ^0.8.0;

contract SolidityTest {
   uint storedData=10; 
  
   function getResult() public returns(string memory){
      uint a = 10; 
      uint b = 2;
      uint result = a + b;
      return integerToString(result); 
   }

   function integerToString(uint i)public returns (string memory) {
      if (i == 0) {
         return "0";
      }
      uint j=0;
      uint len;
      for (j = i; j != 0; j /= 10) {  //for loop example
         len++;         
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      while (i != 0) {
         bstr[k--] = byte(uint8(48 + i % 10));
         i /= 10;
      }
      return string(bstr);//access local variable
   }
}
Enter fullscreen mode Exit fullscreen mode

For more content, follow me on - https://linktr.ee/shlokkumar2303

Top comments (0)