Answer to Question #286061 in Java | JSP | JSF for Hamza

Question #286061

Page 11


Task #11: Using Arrays and Methods


In this task, you are being asked to write methods that manipulate arrays in Java.


Write a method that returns the smallest value from a given integer array.


You may use the following header for this method:


static int smallest(int[] array)


Write another method that returns the largest value from a given integer array.


You may use the following header for this method:


static int largest(int[] array)


Write a third method that returns the middle value from a given integer array if the array length is


odd, or returns the average of the two middle values if the array length is even.


You may use the following header for this method:


static double middle(int[] array)


NOTE: Declare and initialize the array without taking the input from user.


1. Create a program called ArrayValuesLab1.java.


2. Create appropriate variables and assign values using a Scanner object.


3. Correctly display appropriate messages.

1
Expert's answer
2022-01-13T12:31:34-0500
public class ArrayValuesLab1 {
    static int smallest(int[] array) {
        int min = array[0];
        for (int i = 0; i < array.length; i++) {
            if (array[i] < min) {
                min = array[i];
            }
        }
        return min;
    }

    static int largest(int[] array) {
        int max = array[0];
        for (int i = 0; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        return max;
    }

    static double middle(int[] array) {
        if (array.length % 2 == 0) {
            return ((double) array[(array.length - 1) / 2] + array[array.length / 2]) / 2;
        }
        return array[array.length / 2];
    }

    public static void main(String[] args) {
        int[] array = {1, 5, 0, 4, 7, 5, 1, 8, 4, 9};
        System.out.println(smallest(array));
        System.out.println(largest(array));
        System.out.println(middle(array));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog