What: a java file containing your solution In this lab, you will learn the basic
ID: 3916900 • Letter: W
Question
What: a java file containing your solution In this lab, you will learn the basics of array manipulation and recursion. Problem: Write a program that given an array A of integers determines: a) Recursively the maximum element in A b) Iteratively the minimum element in A c) Recursively the sum of the elements in A d) Recursively the average (this is a fractional number) of the elements inA e) Recursively the mode of the elements in A, the value that appears the most inA f) Iteratively the median of the elements in A Note: each of the items above should be presented as a separate method. 1/ Describe how you want to solve this problem: write this description as a comment at the top of your java file. The description should be free of typos and grammatically correct. 2/ Put together a Java code that addresses the above problem. Each instruction of your code should be commented to explain what it does and why the whole piece of code is an actual solution to the above problem.Explanation / Answer
import java.util.Arrays;
class Main {
// part a)
public static int maximum(int[] a)
{
// base case 1
if(a.length == 1)
return a[0];
// base case 2
if(a.length == 2)
{
if(a[a.length-1] < a[a.length-2])
return a[a.length-2];
else
return a[a.length-1];
}
// comparing the last 2 and putting the greater number in last but one in the array
if(a[a.length-1] > a[a.length-2])
{
a[a.length-2] = a[a.length-1];
}
return maximum(Arrays.copyOfRange(a, 0, a.length-1));
}
// part b)
public static int minimum(int[] a)
{
int result = a[0];
for(int i=1; i<a.length; i++)
{
if(result > a[i])
result = a[i];
}
return result;
}
// part c)
public static int total(int[] a)
{
// base case
if(a.length == 1)
return a[0];
return a[a.length-1] + total(Arrays.copyOfRange(a, 0, a.length-1));
}
// part d)
public static double average(int[] a, int i)
{
// base case is to add the last number
if(i == a.length-1)
return a[a.length-1];
// dividing the sum by the total number
if(i == 0)
return ((a[i] + average(a, i+1))/a.length);
// adding all the elements recursively
return (a[i] + average(a, i+1));
}
public static void main(String[] args) {
int[] a = new int[]{4, 6, 5, 1, 7, 3, 2, 4};
System.out.println(maximum(a));
System.out.println(minimum(a));
System.out.println(total(a));
System.out.println(average(a, 0));
}
}
/*SAMPLE OUTPUT
7
1
34
4.25
*/
// Note: 4 sub parts at a time please -- Policy of Chegg
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.