Write a program to find Minimum and Maximum numbers from the given array using Recursion.
✅ Step-by-Step Explanation
🔹 1. Input Array
- User enters array size and elements
- Example: arr = [5, 8, 2, 9, 1]
🔹 2. Recursive Max Function
int findMax(int arr[], int n) {
if(n == 1) return arr[0];
int maxRest = findMax(arr, n - 1);
return (arr[n - 1] > maxRest) ? arr[n - 1] : maxRest;
}
- Base case: When only one element remains, return it
- Recursive case: Compare current element with max of remaining elements
- Example: For [5,8,2,9,1], compares 1 with max of [5,8,2,9], etc.
🔹 3. Recursive Min Function
int findMin(int arr[], int n) {
if(n == 1) return arr[0];
int minRest = findMin(arr, n - 1);
return (arr[n - 1] < minRest) ? arr[n - 1] : minRest;
}
- Same logic as max function but compares for smaller values
- Example: For [5,8,2,9,1], compares 1 with min of [5,8,2,9], etc.
🔹 4. Result Output
- Prints the final minimum and maximum values
- Example output: Maximum = 9, Minimum = 1
🖨️ Example Run
Input:
Enter size of array: 5 Enter 5 elements: 5 8 2 9 1
Output:
Maximum element = 9 Minimum element = 1
📌 Key Concepts Covered
Recursion
Functions calling themselves with smaller subproblems
Base Case
Termination condition for recursive calls
Divide & Conquer
Breaking problem into smaller subproblems (n-1 elements)
Comparison Logic
Ternary operator used to compare elements
Array Processing
Handling array elements recursively
No comments:
Post a Comment