[Solidity] How to write for statements?

This section explains how to write for statements (repeat) in Solidity.

Syntax

Here is how to write a for statement in Solidity.

for (initialization; conditional expression; iterative expression) {
    Processing
}

Sample Code

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Test {

    uint[] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    function getSum() public view returns(uint) {
        uint sum = 0;
        // Loop over the numbers array by the number of elements (iterative processing)
        for (uint i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }

        return sum;
    }

}

The for statement is also used in the same way as in other programming languages. It is important to remember it in combination with arrays.

タイトルとURLをコピーしました