This is not an optimal solution, because you may save the result of the recursive call in an int variable, but I wasn't allowed to in my exercise.
Anyway, this function searches the lowest value in an int array by using recursion.
As first it checks how many elements are in the array by checking if the size equals to 1 and then returns the first value as result. If the table is bigger than 1 (and technically also when lower) it compares the last value in the array with the recursive call with the rest of the array.
The recursion stops at the 0-index and then compares that value with the index 1. Then it compares the lowest value of index 0 and 1 with the value from index 3 and so on until it reaches last value.
int minimum(int array[], int size) {
if (size == 1) {
return array[0];
}
else {
return (array[size] < minimum(array, size - 1))
? array[size]
: minimum(array, size - 1);
}
}
int array[5] = {5, 99, 205, 1, 15};
int smallest = minimum(array, 4); // 4 = index of the last element
Rules in my exercise:
- Do not change the array
- Do not use any variable
- Use recursion