FOR LOOPS AND ARRAY EXERCISES IN SOLIDITY

13 April 2022, Abdulhakim Altunkaya

Execise 2: Create a uint array of odd numbers from between 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 values that we will push to our array should be even numbers. So we will use modulus. If the remainder of any number that is divided by 2 is not equal to 0, than those number are odd. So, if you divide 5 by 2, the remainder is 1, then 5 is odd. If you divide 6 by 2, the remainder is 0, then 6 is even.

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 an empty dynamic array
uint[] myArray;

//Add values to our array.
function addArray() external {
for(uint i = 0; i < 21; i++ ) {
if(i % 2 == 1) {
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: ⇨ ⇨