1

Hi I am New to Solidity!. I have a simple array which adds some numbers in an array

pragma solidity ^0.4.11;
Contract TestArray{
    uint[] public numbers;
    function addNumber(uint number){
        numbers.push(number);
    }

This getNumbers() function is returning all the values

  function getNumbers() constant returns(uint[]){
        return numbers;
    }

But when I am trying to check if the no exists its returning true for only the first value. For the rest of the value it's returning false

function checkNoExists (uint no) constant returns(bool){
        for(uint i=0; i<numbers.length; i++){
            if(numbers[i]==no){
                return true;
            } else{
                return false;
            }
        }
    }

Please Help!

  • Have you tried it using Remix? – Aniket Sep 28 '17 at 11:06
1

There is an error in your checkNoexists function. If you check any no other than first if(numbers[i]==no), this conditions executes to false for i=0 and returns false. The code is working as it should, your logic is incorrect. Use this instead:

function checkNoExists (uint no) constant returns(bool){
    for(uint i=0; i<numbers.length; i++){
        if(numbers[i]==no){
            return true;
        }
    }
    return false;
}
  • Yes, it should work. – Aniket Sep 28 '17 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.