Open In App

Solidity For Loop

This is the most compact way of looping. It takes three arguments separated by a semi-colon to run. The for loop includes three most important parts:

Syntax:



for (initialization; condition; increment) {

       statement or block of code to be executed if the condition is True



}

The initialization is an expression that is executed only once before the loop begins. The condition is an expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. The increment is an expression that is executed at the end of each iteration.

 

Example: Below is the Solidity program to demonstrate the execution of a for loop and how an array can be initialized using the while loop.




// Solidity program to demonstrate the 
// use of 'For loop'
pragma solidity ^0.5.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;
  }
}

Output:

 

Article Tags :