#include <iostream>
#define MYSIZE 10
int find_elem(int* array, int number)
{
if (array[0] == 0)
return -1;
elseif (array[0] == number)
return 0;
elsereturn 1 + find_elem(&array[1], number);
}
int main()
{
int array[MYSIZE] = {1, 2, 3, 66, 3, 4};
int result = find_elem(array, 5); //expected result = -1
result = find_elem(array, 3); //expected result = 4
//BUT...
result = find_elem(array, 0); // result = 5
return 0;
}
How can I change this function to return appropriate value for number=0 ?
And if the number = 0 was an existing element inside this array, how could I find the index of it?
If you use a "standard" array, then you are going to have to signify its end. If you aren't using a sentinel then you will have to pass the size of the array so one knows how to end the recursion.
Please put your code in a single runnable sample, so that we can test it in cpp.sh.
You are also going to have to avoid adding 1 if the element is not found further down the recursion.