Exercice 1 Array and Loop

Published by Mario Oettler on

Now, we want to write a small smart contract that declares an array (fixed size = 10, uint256), fills it with numbers and implements a function to add the values of the array up to a certain index that is provided by the user when calling the function.

Try to write a smart contract

You can see the sample code here:

pragma solidity 0.8.20;

contract LoopOverArray{
    uint256[10] public numberArray = [12,8,1,2,36,5,8,11,21,10];

    function sumNumbers(uint256 range) public view returns(uint256){
        uint256 result;
        for(uint256 i = 0; i < range; i++){
            result = result + numberArray[i];
        }
        return result;
    }
}

Line 4: Here, we declare an array of the data type uint256. It is supposed to have 10 elements. The array is public. This means, it implements a function that returns the value of a given index. In the same line, we copy values [12,8,1,2,36,5,8,11,21,10] to the array.

Line 6: The function sumNumbers takes the range as input. The range is the index until the values of the array are added. It returns the value as uint256. Since nothing is written to the blockchain, the state modifier is set to view.

Line 7: Here, we declare our variable that takes the result.

Line 8: The head of the for loop starts the counter i at 0 and loops until the range is reached. The counter is incremented by 1 in each loop.

Line 9: The result is updated in every cycle.

Line 11: The result is returned

Categories:

if()