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!




Get Free Tutorials by Email

About the Author

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

Today's Tech News

Amazon resists Echo murder evidence callPosted on Thursday February 23, 2017

Amazon issues formal legal response to requests to hand over information from its smart speaker Echo.

Router hacker suspect arrested at Luton AirportPosted on Thursday February 23, 2017

The "mastermind" behind a massive 2016 attack may face sabotage charges in Germany.

A guided tour of the cybercrime undergroundPosted on Wednesday February 22, 2017

Malware researcher Anton talks about who does what in the web's dark marketplaces.

Courtesy BBC News