We take the integer array Arr[] as input. The goal is to find the largest and smallest elements in an array using a recursive method.
Since we are using recursion, we will iterate through the entire array until we reach length = 1 and then return A[0], which forms the base case. Otherwise, the current element is compared to the current minimum or maximum value and its value is updated recursively for subsequent elements.
Input− Arr= {12,67,99,76,32};
Output− Maximum value in the array: 99
Explanation− Among all elements, 99 is the maximum value.
Input− Arr= {1,0,-99,9,3};
Output− Minimum value in the array: - 99
Explanation− Among all elements, -99 is the smallest value.
Take the array Arr[] as input.
The function recforMin(int arr[], int len) accepts an input array and its length, and uses recursion to return the minimum value in the array.
Get the integer variable minimum
If the current index len is 1, set minimum=arr[0] and return minimum.
Otherwise set minimum = arr[len] or the minimum value of recforMin(arr,len-1) and return it.
Finally the smallest element will be returned.
Print the result in the main function.
Take the array Arr[] as input.
The function recforMax(int arr[], int len) accepts an input array and its length and returns the maximum value in the array using recursion.
Get the integer variable maximum.
If the current index len is 1, set maximum=arr[0] and return maximum.
Otherwise set the maximum value of maximum = arr[len] or recforMax(arr,len-1) and return it.
Finally the largest element will be returned.
Print the result in the main function.
#includeusing namespace std; int recforMin(int arr[], int len){ int minimum; if (len == 1){ minimum=arr[0]; return minimum; } else{ return minimum=arr[len] Copy after login
If we run the above code, the following output will be generated
Minimum in the array :-89
#includeusing namespace std; int recforMax(int arr[], int len){ int maximum; if (len == 1){ maximum=arr[0]; return maximum; } else{ return maximum=arr[len]>recforMax(arr,len-1)?arr[len]:recforMax(arr,len-1); } } int main(){ int Arr[] = {-89,98,76,32,21,35,100}; int length = sizeof(Arr)/sizeof(Arr[0]); cout <<"Maximum in the array :"< Copy after login
If we run the above code, the following output will be generated
Maximum in the array :-100
The above is the detailed content of Recursive program to find minimum and maximum elements of array in C++. For more information, please follow other related articles on the PHP Chinese website!