Open In App

Solidity Do While Loop

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

In solidity do while loop is similar to the other programming languages firstly it won’t check the condition it executes the program at least once which is written in the do block and later it checks the condition in the while block.

Syntax:

do{

// Block  of code to be written for execution

}while(condition)

Flow Chart

Do-While Loop

 

Example: Below is the Solidity program to implement a do-while loop:

Solidity




// Solidity program to implement do-while loop
// SPDX-License-Identifier : MIT
pragma solidity 0.8.18;
 
contract Array{
   
  // Initializing array and making it as public
   
  // By default if we don't initialize any values
  // all values will be set to 0
  uint[6] public gfg_arr;
  uint public count;
   
  // Here we can't directly initialize the loops
  // as of in other languages
  // We need to write the loops in function in solidity
   
  // Basically in this loop we are incrementing the index
  // value by 1 and storing it in array
  function gfg_loop_func() public
  {
    do {
       
      // Incrementing the index value by 1
      gfg_arr[count] = count + 1;
      count++;
     
    //checking the condition
    }while(count<gfg_arr.length);
  }
}


Explanation: The above program performs the operation like it takes the index value and it adds plus 1 to the index and stores it in the array. For example at the 0th  index, it will store the value 1 and at the 1st index it will store the value 2, and so on it executes the loop till 5 because in while condition we have given a condition less than the length of the array and we declared the array length as 6 in the above program.

Output:

Do-while Output

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads