w3resource

Java: Find the largest element between first, last, and middle values from an array of integers


Largest of First, Last, Middle

Write a Java program to find the largest element between the first, last, and middle values in an array of integers (even length).

Sample Solution:

Java Code:

import java.util.Arrays;

public class Exercise82 {
    public static void main(String[] args) {
        // Define an integer array, array_nums
        int[] array_nums = {20, 30, 40, 50, 67};
        
        // Print the elements of the original array
        System.out.println("Original Array: " + Arrays.toString(array_nums)); 
        
        // Initialize a variable max_val with the value of the first element
        int max_val = array_nums[0];
        
        // Check if the last element is greater than max_val
        if (max_val <= array_nums[array_nums.length - 1])
            max_val = array_nums[array_nums.length - 1];
        
        // Check if the middle element is greater than max_val
        if (max_val <= array_nums[array_nums.length / 2])
            max_val = array_nums[array_nums.length / 2];
        
        // Print the largest element among the first, last, and middle values
        System.out.println("Largest element between first, last, and middle values: " + max_val);  
    }
}

Sample Output:

Original Array: [20, 30, 40, 50, 67]                                   
Largest element between first, last, and middle values: 67 

Flowchart:

Flowchart: Java exercises: Find the largest element between first, last, and middle values from an array of integers


For more Practice: Solve these Related Problems:

  • Modify the program to find the smallest element among first, last, and middle.
  • Write a program to return the index of the largest element.
  • Modify the program to check if the middle element is larger than both first and last.
  • Write a program to swap the largest and smallest elements in an array.

Go to:


PREV : Swap First and Last Elements.
NEXT : Multiply Array Elements.


Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.