DEV Community

Cover image for Day 11 - Array Operations
Vedant Chainani
Vedant Chainani

Posted on • Updated on

Day 11 - Array Operations

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 11 of 30 in Solidity Series
Today I Learned About Array Operations in Solidity.

Array Operations

  • Accessing Array Elements
  • Length of Array
  • Push
  • Pop

Accessing Array Elements

The elements of the array are accessed by using the index. If you want to access nth element then you have to access (n - 1)th index.

Example -

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;  

contract MyContract {  

    uint[6] arr = [10, 20, 30, 40, 50, 60];

    function getValue(uint _index) public view returns(uint _value) {
        _value = arr[_index];
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -

When we pass Index as 2 we get

"0": "uint256: _value 30"
Enter fullscreen mode Exit fullscreen mode

Length of Array

Length of the array is used to check the number of elements present in an array. The size of the memory array is fixed when they are declared, while in case the dynamic array is defined at runtime so for manipulation length is required.

Example -

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    uint256[] arr_1 = [1, 5, 4, 7, 8, 9, 3, 2, 4, 7, 8, 5, 9, 7];

    function getLength() public view returns (uint256) {
        return arr_1.length;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -

"0": "uint256: 14"
Enter fullscreen mode Exit fullscreen mode

Push

Push is used when a new element is to be added in a dynamic array. The new element is always added at the last position of the array.

Example -

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    uint256[] arr_1 = [1, 5, 4, 7, 8, 9, 3, 2, 4, 7, 8, 5, 9, 7];

    function pushElement(uint256 _value) public returns (uint256[] memory) {
        arr_1.push(_value);
        return arr_1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -

If we pass the value as 30 then output is

"0": "uint256[]: 1,5,4,7,8,9,3,2,4,7,8,5,9,7,30"
Enter fullscreen mode Exit fullscreen mode

Pop

Pop is used when the last element of the array is to be removed in any dynamic array.

Example -

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    uint256[] arr_1 = [1, 5, 4, 7, 8, 9, 3, 2, 4, 7, 8, 5, 9, 7];

    function popElement() public returns (uint256[] memory) {
        arr_1.pop();
        return arr_1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -

"0": "uint256[]: 1,5,4,7,8,9,3,2,4,7,8,5,9"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)