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:
- Initialize an array with some values.
- Initialize a variable
max
with the first element of the array. - Iterate through the array and compare each element with
the
max
variable. - If the element is greater than
max
, assign the element to themax
variable. - Finally, the
max
variable will have the largest number in the 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:
Space Complexity: O(1) - We are using a constant space to store the
The largest number in the array is: 50Time 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.
- Recommended Links
- Selenium Interview Questions