Why the error showing even after using the uint (non negative interger) for the index of the array?

Viewed 114

Please help with this code :

My cdoe :

 // SPDX-License-Identifier: GPL-3.0
 pragma solidity >=0.7.0 <0.9.0;


contract new_nth{

 function nth(int n,int a,int b,int c) pure public returns(int){
    int[100] memory arr;
    arr[0] = a;
    arr[1] =b;
    arr[2] = c;
    uint i;
    for(i =3;i<n;++i){
        arr[i] = arr[i-1]+arr[i - 2 ]+arr[i - 3];
    }
    return arr[n-1];
 }
}

Error :

TypeError: Operator < not compatible with types uint256 and int256 --> nth_term.sol:14:18: | 14 | for(i =3;i<n;++i){ | ^^^

TypeError: Type int256 is not implicitly convertible to expected type uint256. --> nth_term.sol:17:20: | 17 | return arr[n-1]; | ^^^

1 Answers

if you just convert uint n, it will work

// SPDX-License-Identifier: GPL-3.0
 pragma solidity >=0.7.0 <0.9.0;


contract new_nth{

 function nth(uint n,int a,int b,int c) pure public returns(int){
    int[100] memory arr;
    arr[0] = a;
    arr[1] =b;
    arr[2] = c;
    uint i;
    for(i =3;i<n;++i){
        arr[i] = arr[i-1]+arr[i - 2 ]+arr[i - 3];
    }
    return arr[n-1];
 }
}

Because array index is uint type. Since you specify int n compiler thinks that your array might have negative index

Related