Solidity supports for and while loops, however, the number of iterations should be kept small to save gas. The syntax for loops is similar to other programming languages like JavaScript.
The continue keyword is used to skip one iteration when the specified condition is true and the exit keyword is used to break the loop and continue with other code.
In the example down below we have specified that the loop runs as long as n is smaller than 10. However, the condition for the break statement is set to n == 5. So the loop will run only till n is and not 9.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
// for loop in Solidity
contract ForLoop {
function exampleFor() external pure {
for (uint n = 0; n < 10; n++) {
if (n == 3) {
// skip iteration when n is 3
continue;
}
// code here
if (n == 5) {
// exit loop when n is 5
break;
}
}
}
}