Exercise 14: In Java (please note 4 part assignment) One common algorithm is fin
ID: 656103 • Letter: E
Question
Exercise 14: In Java (please note 4 part assignment)
One common algorithm is finding the largest element in the array - that is, the array element with largest value- as well as finding the location of the element in the array. For all sections, assume that the array contains unique values (no repetitions.). initially , we assume that the first element in the list is the largest element and create a variable maxvalue that is initialized to the first element in the array. We then compare the element that maxValue is storing with every element in this list. Ehenever we find an element in the array larger than the element that maxValue is storing, we update maxValue so that it stores the index of the newer larger element.Explanation / Answer
MyArray.java
==============
package chegg;
public class MyArray {
public static void main(String[] args) {
int[] array1 = { 45, 38, 27, 46, 81, 72, 56, 61, 20, 48, 76, 91, 57, 35, 78 };
int[] array2 = { 300, 38, 27, 46, 81, 72, 56, 61, 20, 48, 76, 91, 57, 35, 800 };
int[] array3 = { 45, 38, 27, 46, 81, 72, 56, 61, 20, 48, 76, 91, 57, 35, 800 };
int[] array4 = { 100 };
myArray(array1);
myArray(array2);
myArray(array3);
myArray(array4);
}
public static void myArray(int[] array) {
int maxValue = array[0];
int maxIndex = 0;
int sum = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
maxIndex = i;
}
sum = sum + array[i];
}
System.out.println(" ===========================");
System.out.println("Largest Value: " + maxValue);
System.out.println("Largest Value Index: " + maxIndex);
System.out.println("Array Sum: " + sum);
System.out.print("Reversing the array : ");
reversePrint(array);
System.out.println("=========================== ");
}
public static void reversePrint(int[] array) {
for (int i = array.length; i > 0; i--) {
System.out.print(array[i - 1] + " ");
}
System.out.println(" ");
}
}
========
sample output
===========================
Largest Value: 91
Largest Value Index: 11
Array Sum: 831
Reversing the array : 78 35 57 91 76 48 20 61 56 72 81 46 27 38 45
===========================
===========================
Largest Value: 800
Largest Value Index: 14
Array Sum: 1808
Reversing the array : 800 35 57 91 76 48 20 61 56 72 81 46 27 38 300
===========================
===========================
Largest Value: 800
Largest Value Index: 14
Array Sum: 1553
Reversing the array : 800 35 57 91 76 48 20 61 56 72 81 46 27 38 45
===========================
===========================
Largest Value: 100
Largest Value Index: 0
Array Sum: 100
Reversing the array : 100
===========================
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.