Write C and Java programs to find the largest element in an array using recursion.

Here, we develop C and Java code to find the maximum element in an array using recursion. We develop a method revursiveMax that takes an array arr storing n integers, where n >= 1 and returns the maximum element in arr.

Following are the Java and C codes respectively to find the maximum element of an array using recursion.

Java program to find the maximum element of an array using recursion.

class RecursiveMax
{
  public static void main(String[] args)
  {
    int[] arr = {10, 5, 7, 9, 15, 6, 11, 8, 12, 2, 3};
    int max = recursiveMax(arr, arr.length);
    System.out.println("Maximum element: " + max);
  }
 
  static int recursiveMax(int[] arr, int length)
  {
    if (length == 1)
      return arr[0];
    return max(recursiveMax(arr, length - 1), arr[length - 1]);
  }
 
  private static int max(int n1, int n2)
  {
    return n1 > n2 ? n1 : n2;
  }	
}
 
OUTPUT
======
D:\JavaPrograms>javac RecursiveMax.java
 
D:\JavaPrograms>java RecursiveMax
Maximum element: 15

C program to find the maximum element of an array using recursion.

#include <stdio.h>
 
int recursiveMax(int[], int);
int max(int, int);
 
int main()
{
  int arr[] = {10, 5, 7, 9, 15, 6, 11, 8, 12, 2,};
  int max = recursiveMax(arr, 10);
  printf("Maximum element: %d\n", max);
}
 
int recursiveMax(int* arr, int length)
{
  if (length == 1)
    return arr[0];
  return max(recursiveMax(arr, length - 1), arr[length - 1]);
}
 
int max(int n1, int n2)
{
  return n1 > n2 ? n1 : n2;
}
 
OUTPUT
======
Maximum element: 15

Hope you have enjoyed reading C and java programs to find maximum number in an array by recursion. However, recursive solution in this case has no advantage over iterative one because there is more overhead associated with making recursive calls due to the fact that all recursive calls are saved at call stack.

Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.