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

Facebook to exclude billions from European privacy lawsPosted on Thursday April 19, 2018

A total of 1.5 billion international Facebook users will not be protected under GDPR.

TalkTalk and Vodafone top complaints chart againPosted on Thursday April 19, 2018

TalkTalk, Vodafone and BT drew the most complaints for their services, the regulator says.

Ikea's TaskRabbit app back online after data breachPosted on Thursday April 19, 2018

The odd jobs marketplace has been investigating a "cyber-security incident".

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×