Objectives: use Scite
1. Use recursion to solve a problem
2. Create classes to model objects
Problem : Find the largest element in an array
(filename: TestFindLargest.java)
Write a recursive method that returns the largest value in an array. Write a test program that creates an array of 5 integers, calls the method, and displays its largest value.
Hint: Find the largest value in the sublist containing all but the last element. Then compare that largest value to the value of the last element.
public class TestFindLargest {
public static void main(String[] args) {
int arr[] = { 10, 2, 15, 7, 8 };
System.out.println("Max element: " + getMax(arr, arr.length));
}
public static int getMax(int arr[], int n) {
if (n == 1)
return arr[0];
return Math.max(arr[n - 1], getMax(arr, n - 1));
}
}
Get Answers For Free
Most questions answered within 1 hours.