Consider this code, which computes the maximum element of an array.
#include <stdio.h>
int maximum(int arr[], int n)
{
if (n == 1) {
return arr[0];
} else {
int max = maximum(arr, n-1);
printf("Largest element : %d\n", max);
return 5; // return arr[n-1] > max ? arr[n-1] : max;
}
}
int main()
{
int array[5] = {5, 23, 28, 7, 1};
printf("Maximum element of the array is: %d", maximum(array, 5));
return 0;
}
Why is the else
block called four (4) times?
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
Assuming it's unsorted, the simplest way would be to run through the array once, find the largest element, then run through again to find the largest element less than the largest. You could use recursion; it would recurse twice.
The function is recursive, thus it will be called multiple times.
When you first start, n=5. It will take the else block (n is not 1). Then, you call maximum again with n-1 (n=4). Again, the else block is taken.
All told, the function is called 4 times before n reaches 1, whereupon it takes the if block and returns ar[0].
As others have mentioned, the function as written will not return the maximum value of the list. Curiously, it seems to always return 5 unless the list array size is 1, in which case it returns the value of that element.
Instead, a recursive approach would typically involve splitting the list in half each time, then returning the max of each pair when the list finally broken into pairs of elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With