# I'm trying to reverse an array but the transaction keeps getting reverted even though the logic seems right. Can someone help me out?

Here is the code :

``````// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;

contract Day1 {

function reverseArray(uint[] memory arr1, uint length) public pure returns(uint[] memory){

uint[] memory arr2;
uint i = length-1;
uint j = 0;

while(i>=0 && j<length){
arr2[j] = arr1[i];
i--;
j++;
}

return arr2;

}
}
``````

The error:

So, two things:

1. you need to change how you declare your arr2
2. in your while loop, i gets to 0 and goes into the loop where you do i-- so you are doing '0 - 1' and you underflow, which reverts your transaction.

I got it to work by doing the last swap outside of the loop. I'm sure there is a better way but I don't have enough time to find it right now.

here is the code

``````pragma solidity >=0.5.0 <0.9.0;

contract Day1 {

function reverseArray(uint[] memory arr1, uint length) public pure returns(uint[] memory){

uint[] memory arr2 = new uint[](length);
uint i = length-1;
uint j = 0;

while(i>0 && j<length){
arr2[j] = arr1[i];
i--;
j++;
}

arr2[j] = arr1[i];

return arr2;

}
}
``````

Hope this helps!

• Thanks! this sure helps. Dec 17, 2022 at 10:43
• i tried changing all data types from uint to int to avoid the underflow problem but it still wouldn't work if the last loop is not declared out of the while loop. Why is it so? Dec 17, 2022 at 11:13
• @GimmeGinNtonic We would have to see that code. But my assumption is that it didn't work because your arrays were also unit[] type.
– Sky
Dec 17, 2022 at 11:34

There are number of syntax issues in the code you posted. But this should help;

``````// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;

contract RevertArray {

function reverseArray(uint[] memory array) public pure returns(uint[] memory) {

uint length = array.length;
uint numberOfElements = length -1;
uint[] memory reversed = new uint[](length);

uint i = numberOfElements;
uint j;

while( j < numberOfElements) {
reversed[j] = array[i];
i--;
j++;
}

reversed[j] = array[i];

return reversed;

}

}
``````
• actually this was an online challenge where length was supposed to be a function argument Dec 17, 2022 at 11:11
• Where are you doing this Challenge?
– Sky
Dec 17, 2022 at 11:25
• Great stuff Sky! Dec 17, 2022 at 11:45
• @Sky here - codedamn.com/30-days-of-solidity Dec 17, 2022 at 12:00