w3resource

Java: Print all the LEADERS in the array


Write a Java program to print all the LEADERS in the array.

Note: An element is leader if it is greater than all the elements to its right side.

Pictorial Presentation:

Java Array Exercises: Print all the LEADERS in the array

Sample Solution:

Java Code:

// Import necessary Java libraries.
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Arrays; 

// Define a class named Main.
public class Main
{
    // The main method for executing the program.
    public static void main(String[] args)
    {
        // Define an array of integers.
        int arr[] = {10, 9, 14, 23, 15, 0, 9};
        int size = arr.length;
        
        // Loop through each element in the array.
        for (int i = 0; i < size; i++) 
        {
            int j;
            
            // Find the first element greater than or equal to arr[i].
            for (j = i + 1; j < size; j++) 
            {
                if (arr[i] <= arr[j])
                    break;
            }
            
            // If no greater element is found, print the current element.
            if (j == size) 
                System.out.print(arr[i] + " ");
        }
    }
}

Sample Output:

                                                                              
23 15 9

Flowchart:

Flowchart: Print all the LEADERS in the array

For more Practice: Solve these Related Problems:

  • Write a Java program to find all "trailing leaders" in an array (numbers greater than all elements to their left).
  • Write a Java program to find the leader with the highest value in an array.
  • Write a Java program to find the smallest leader in an array.
  • Write a Java program to determine if the first or last element in an array is a leader.

Java Code Editor:

Previous: Write a Java program to get the majority element from a given array of integers containing duplicates.
Next: Write a Java program to find the two elements from a given array of positive and negative numbers such that their sum is closest to zero.

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.