1

can someone explain how variable ans return the index of an array if my array is 9 8 10 8 and I want to search 10 and in recursion ans will return 1 and then it will ad with ans+1 and return 2.

enter code here

int firstIndex(int input[], int size, int x) {

if(size==0)

{

return -1;

}

if(input[0]==x)

{ return 0;

}

int ans=firstIndex( input+1,  size-1,  x);

if(ans!=-1)

{
    return ans+1;
    
}

else

{
    return ans;
}

}

1 Answer 1

1

Ok, so the function when it receive the first call, the vector looks like this: [9 8 10 8]. Then it compares 9 with 10 (the element in search). Since they are not equals, the function makes a recursive call, but with a new vector, [8 10 8]. in that moment we have in our stack the first call. Let's call it C1.

Then it compares 8 with 10 (the element in search). Since they are not equals, the function makes a recursive call, but with a new vector, [10 8]. in that moment we have in our stack the second and first call. Let's call it C2 C1.

Then it compares 10 with 10 (the element in search). Since they are equals, the function makes returns 0. So in our stack, the C2 function receive a 0 as a result. Since it is different to -1, then it returns 1 to the C1 call. Since 1 is not equal to -1, it returns 2 leaving the correct result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.