This code is wrong
if (array[choice_] >= 0) {
return array[choice_];
When you do array[choice_]
you are looking at the array value at index choice_
. That is not what you want. Instead you want to find out if the array at some index is equal to choice_
. That would be if (array[some_index] == choice_) return some_index;
Further, to make this a recursive approach, the function needs to call itself. Your code doesn't do that so it's not recursive.
Here is a recursive approach:
int searchArray(const int* array, const int choice_, const int size)
{
if (size > 0)
{
if (array[size-1] == choice_) return size-1; // Hit! Return the index
return searchArray(array, choice_, size-1); // Recursive call - pretend array is 1 shorter
}
return -1;
}
The code looks at the last element in the array.
If it is a hit it simply returns the index.
If it is not a hit, it calls itself but decrements size
to pretend that the array is one element shorter.
In this way it goes from the end of the array towards the start of the array while looking for choice_
.
BTW: Notice that it's a very bad idea to use recursion for this task - never do that! Use a simple for
loop. But I guess this is just another example of a very bad homework task...