Maximum element in an array in Java


Q. Write a Java program to find maximum element in an array

 import java.util.Scanner;

public class MaxInArray {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Ask the user for the size of the array
        System.out.print("Enter the number of elements in the array: ");
        int n = scanner.nextInt();

        int[] arr = new int[n];

        // Read array elements
        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

        // Initialize max with the first element
        int max = arr[0];

        // Traverse the array to find the maximum
        for (int i = 1; i < n; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }

        // Display the maximum element
        System.out.println("Maximum element in the array is: " + max);

        scanner.close();
    }
}

Q. Write an algorithm to find maximum element in an array

1. Start
2. Read n (number of elements)
3. Read n integers into an array arr[]
4. Initialize max = arr[0]
5. Loop from i = 1 to n - 1:
    a. If arr[i] > max, then set max = arr[i]
       Print max
6. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.