In Java:
The maximum-valued element of an int-valued array can be
recursively calculated as follows:
• If the array has a single element, that is its maximum (note that
a zero-sized array has no maximum
• Otherwise, compare the first element with the maximum of the rest
of the array-- whichever is larger is the maximum value.
Write an int method named max that accepts an int array, and the
number of elements in the array and returns the largest value in
the array. Assume the array has at least one element.
Required Function :
public static int max(int arr[], int size) {
if(size == 1)
return arr[0];
return Math.max(arr[size - 1], max(arr, size - 1));
}
Testing and output :
import java.util.*;
class Main {
public static int max(int arr[], int size) {
if(size == 1)
return arr[0];
return Math.max(arr[size - 1], max(arr, size - 1));
}
public static void main(String args[]) {
//Array declaration and
initialization
int arr[] = {65,-2,55,77,123,5,234,24};
//Find the size of the
array
int size = arr.length;
//Calling and printing the result
System.out.println(max(arr, size));
}
}
Output :
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)
Get Answers For Free
Most questions answered within 1 hours.