How to find element in array using Solidity

Spread the love

An array is a collection of identical data elements stored in mounted memory locations. This is the simplest data structure, where any data element can be accessed directly simply by its index number.

How to find element in array using Solidity

For example, if we want to store the student’s score in 5 subjects, then it is not necessary to define individual variables for each subject. However, we can define a row that stores data elements in attached memory locations.

  • Array marks [5] describe marks obtained by the student in 5 different subjects, where each mark of the subject is placed at a certain place in the field, ie marks [0] relate to marks obtained in the first subject, score [1] average score achieved in the 2nd field and so on.

Accessing Array Elements

Array elements can be accessed using an index. You must have access to the (i-1) index to access this entry.

Example: In the example below, contract types first start with the [data] field and then take the value of the specific index 2.

// Solidity program to demonstrate

// accessing elements of an array

pragma solidity ^0.5.0;

 

// Creating a contract

contract Types {

 

// Declaring an array

uint[6] data; 

// Defining function to

// assign values to array

function array_example(

) public payable returns (uint[6] memory){

data

= [uint(10), 20, 30, 40, 50, 60];

return data;

}

// Defining function to access

// values from the array

// from a specific index

function array_element(

) public payable returns (uint){

uint x = data[2];

return x;

}

}

Example of finding an element

We shall first define an array and its value in this program. Then they will define a function in which function they have one return type unit. And then, inside the function, we define two variables: one to store the value of the array index value, and the other to hold the null value.

We’ll begin the loop at 0 and work our way up to the array length. And inside the loop we can declare a condition statement in this condition they will check the value stored in another variable to index the number value of an array. If it is greater then they will store the array value to another variable.

Then we will return the other variable because in this loop at last other variable values are greater than or equal to the array value.

pragma solidity ^0.8.0;

 

contract Test{

    uint[5] numbers = [2,14,6,7,19];

   

    

   function getLargest() public view returns(uint){

       

       uint store_var = 0;

        uint i;

        

       for(i=0;i<5;i++){

           if(store_var<numbers[i]){

               store_var = numbers[i];

           }

       }

       return store_var;

   }

}

Read further: How to Remove item from array in Solidity

Leave a Comment