Loading...

Published on 5 Jul 2021

How to get the largest element in an array - Solidity

Let's play with Array

0

Like2090

Array is simply known as it's a data collection with the same data type. For example, They have five different positive integers means it's the group of five-element with the data-type number.

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

They have two types:-

- Fixed array
- Dynamic array

```
// fixed array
uint[5] numbers = [2,14,6,7,19];
// dynamic array
uint size =5;
uint numbers[] = new uint[](size);
```

```
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;
}
}
```

In this program, we will first define an array and its given value. Then they will define a function in which function they have one return type unit. And inside the function firstly we define the two variables one for store the value of array index value and the second one is for store the null value.

We will start the loop from 0 to 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 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 greater than or equal to the array value.

Enjoyed the SmartBook?

Like