LearnFrenzy
Sign in Take a free test

Functions · Function Programs · Question 3

Find the maximum of an array using recursion in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Popular