This is not an optimal solution, because you can save the result of a recursive call in an int variable, but I was not allowed in my exercise.
In any case, this function searches for the smallest value in the int array using recursion. How first he checks how many elements are in the array, checking if size is 1, and then returns the first value as a result. If the table is greater than 1 (and technically also lower), it compares the last value in the array with a recursive call with the rest of the array.
The recursion stops at the 0-index, and then compares this value with index 1. Then it compares the smallest value of index 0 and 1 with the value from index 3, and so on, until it reaches the 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);
The rules in my exercise:
- Do not change the array
- Do not use variable
- Use recursion
source share