Java Program to Find the Largest Number in an Array

In this Java program, we will learn how to find the largest number in an array.

Java Program to Find the Largest Number in an Array

We will follow the below steps to find the largest number in an array:

  1. Initialize an array with some values.
  2. Initialize a variable max with the first element of the array.
  3. Iterate through the array and compare each element with the max variable.
  4. If the element is greater than max, assign the element to the max variable.
  5. Finally, the max variable will have the largest number in the array.
Here is the Java program to find the largest number in an array:
public class FindLargestNumberInArray {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        int max = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }

        System.out.println("The largest number in the array is: " + max);
    }
}
Output:
The largest number in the array is: 50
Time Complexity: O(n) - We are iterating through the array once to find the largest number.
Space Complexity: O(1) - We are using a constant space to store the max variable.