for loop solidity

A for loop in Solidity is used to execute a block of code repeatedly. It consists of three parts: the initialization, the condition, and the increment/decrement. Here is the general syntax of a for loop in Solidity:

for (initialization; condition; increment/decrement) {
    // code to be executed
  • The initialization is a statement that is executed before the loop starts. It is typically used to initialize a loop variable.
  • The condition is an expression that is checked before each iteration. If the condition evaluates to true, the loop continues executing. If it evaluates to false, the loop terminates.
  • The increment/decrement is a statement that is executed after each iteration. It is usually used to update the loop variable.

Here is an example of a for loop in Solidity:

pragma solidity ^0.8.0;

contract ForLoopExample {
    function loopExample() public pure returns (uint) {
        uint sum = 0;

        for (uint i = 1; i <= 10; i++) {
            sum += i;

        return sum;

In this example, the for loop initializes the variable i to 1, checks if i is less than or equal to 10, and increments i by 1 after each iteration. The loop calculates the sum of the numbers from 1 to 10 and returns the result.

Note that the syntax and usage of for loops in Solidity are similar to other programming languages like C and JavaScript.