FOR LOOPS AND ARRAY EXERCISES IN SOLIDITY

13 April 2022, Abdulhakim Altunkaya

For loops are key concepts in every software language. Besides being useful and important to structure our code, they will also show themselves in most of the job interviews that we might hopefully have in the future. To succeed in the interviews and to have a better understanding of Solidity, here are some exercises to further our knowledge.

Execise 1: Create a uint array from 0 to 20 by using For Loop

To create this array, we follow these steps:

1. Create an empty uint array

2. Then create a write function so that we can update the state of our array.

3. Then by using for loop, we will push values to the array.

4. The limit for our for loop will be "21" because we want the array to be between 0 to 20.

5. Lastly we will create a view function, to see our array after each click.

6. You can copy-paste this to Remix, and play with it to practice and learn.

//SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.7;

contract Exercise {

//Creating empty array
uint[] myArray;

//Add values to our array.
function addArray() external {
for(uint i = 0; i < 20; i++ ) {
myArray.push(i);
}
}

//To see our array after the loop:
function getArray() external view returns(uint[] memory) {
return myArray;
}
}

Click on arrows for the next For loop & Array exercise: ⇨ ⇨