21.6k views
1 vote
C++ Write a recursive function recursiveMinimum that takes an integer array, a starting subscript, and an ending subscript as arguments and returns the smallest element of the array. The function should stop processing and return when the starting subscript equals the ending subscript.

1 Answer

4 votes

Answer:

#include <iostream>

using namespace std;

int recursiveMinimum(int array[], int start, int end) {

if (start == end) {

return array[start];

}

return min(array[start], recursiveMinimum(array, start+1, end));

}

int main() {

int array[] = { 3, 7, 2, 23, 6, 1, 33, 88, 2 };

int nrElements = sizeof(array) / sizeof(array[0]);

cout << "The smallest value is "

<< recursiveMinimum(array, 0, nrElements-1) << endl;

}

Step-by-step explanation:

The recursive function will compare the element at the start of the range to the minimum of the rest of the range [start+1, end].

An end criterium for the recursion is always very important. It is the comparison start==end.

User Sergiu Toarca
by
5.2k points