Solidity While Loop
Last Updated :
08 Apr, 2023
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.
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
pragma solidity ^0.5.0;
contract Types {
uint[] data;
uint8 j = 0;
function loop() public returns(uint[] memory)
{
while(j < 5)
{
j++;
data.push(j);
}
return data;
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...