Recursive function finding index

Hi :)
I needed to write a recursive function returning index of the element I wanted to find, so this is it:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#define MYSIZE 10

int find_elem(int* array, int number)
{
	if (array[0] == 0)
		return -1;
	else if (array[0] == number)
		return 0;
	else
		return 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?

Thanks for help
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.