Open In App

Solidity While Loop

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Solidity, a while loop is a type of loop statement that allows you to execute a block of code repeatedly until a certain condition is met. 

Syntax:

while (condition) {

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

}

The condition is an expression that is evaluated before each iteration of the loop. If the condition evaluates to true, the code inside the loop is executed. Once the code inside the loop is executed, the condition is evaluated again, and the loop continues until the condition becomes false.

While Loop

 

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

Solidity




// Solidity program to demonstrate the use
// of 'While loop'
pragma solidity ^0.5.0;
  
// Creating a contract
contract Types {
    
  // Declaring a dynamic array
  uint[] data;
    
  // Declaring state variable
  uint8 j = 0;
    
  // Defining a function to
  // demonstrate While loop'
  function loop() public returns(uint[] memory)
  {
    while(j < 5) 
    {
      j++;
      data.push(j);
    }
    return data;
  }
}


Output:

Output While loop

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads