Open In App

Solidity For Loop

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Loop Initialization: The first one is ‘loop initialization’ where the iterator is initialized with starting value, this statement is executed before the loop starts. 
  • Test Statement: The second is the ‘test statement’ which checks whether the condition is true or not if the condition is true the loop executes else terminates. 
  • Iteration Statement: The third one is the ‘iteration statement’ where the iterator is increased or decreased. 

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.

For Loop

 

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




// 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:

For Loop Output

 


Last Updated : 08 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads