Find the largest element of an array with a recursive function.
Solution
main.c
#include <stdio.h>
int max_of(const int *a, int n) {
if (n == 1)
return a[0]; /* base case: one element */
int rest = max_of(a + 1, n - 1); /* max of the remaining elements */
return a[0] > rest ? a[0] : rest;
}
int main(void) {
int a[] = {17, 42, 8, 99, 23};
printf("max = %d\n", max_of(a, 5));
return 0;
}
Output Verified by compiling and running
max = 99
The maximum of n elements is the larger of the first element and the maximum of the other n − 1. a + 1 passes the rest of the array without copying it.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!