Skip to main content

Command Palette

Search for a command to run...

Looping in Solidity

Published
2 min readView as Markdown
Looping in Solidity

Loops in Solidity

Solidity supports different types of loops that are similar to those found in other programming languages. Here are some examples:

  1. for loop

The for loop can be used to execute a block of code a specific number of times.

for (uint i = 0; i < 10; i++) {
  // code to execute
}

In this example, the loop will execute 10 times, starting from 0 and incrementing i by 1 each time.

  1. while loop

The while loop can be used to execute a block of code while a specific condition is true.

uint i = 0;
while (i < 10) {
  // code to execute
  i++;
}

In this example, the loop will execute while i is less than 10. i is incremented by 1 with each iteration.

  1. do-while loop

The do-while loop is similar to the while loop, but it will execute the block of code at least once before checking the condition.

uint i = 0;
do {
  // code to execute
  i++;
} while (i < 10);

In this example, the loop will execute at least once, and will continue to execute while i is less than 10. i is incremented by 1 with each iteration.

It's important to note that loops can be expensive in terms of gas costs, especially if they are nested or execute a large number of times. It's important to use loops judiciously and to optimize loop conditions and iterations whenever possible to minimize gas costs.

More from this blog