Approach recursive functions like "how to solve this problem, solving a smaller problem"? And - to all functions - with the requirement that the function performs one logical action. Your function both looks for and displays the answer - these are completely different things.
So, there is an array, its length, the key value. How are we looking for an item? Let's go with the end (so as not to suffer with the displacement of the index from the beginning). If the last element of the array is the one we need, we will return it. If not, we will look in the array for one less element:
int find(int* array, int size, int key) { if (array[size-1] == key) return size-1; // Искомый элемент найден // Иначе ищем его среди `size-1` элементов return find(array,size-1,key); }
Everything? No, because you still have to decide what to do if the element is not found (in this case, our function will call itself all the time - endless recursion will result). Since there are no indices less than 0, let's return -1 as a sign of absence. When do we know that the item is not? When searching in an empty array. So you need to first add a check.
if (size == 0) return -1; // не найден
So finally:
int find(int* array, int size, int key) { if (size == 0) return -1; // Не найден if (array[size-1] == key) return size-1; // Искомый элемент найден // Иначе ищем его среди `size-1` элементов return find(array,size-1,key); }
Everything. Now we organize the output in another function, for example,
void find_message(int* array, int index) { if (index < 0) { cout << "Key not found\n"; return; } cout << "Key " << array[index] << : was found in position " << index << endl; }
Well, in main() or somewhere else ...
int array[SIZE] = ... ... int idx = find(array,SIZE,key); find_message(array,idx);