In this tutorial, we will write a java program to find the largest element of an array. In theory, a largest element can be found by, storing the first element of the array in a variable largestElement
(can be given any name). Then comparing that variable with rest of the elements, if any element is found greater than the largestElement then store the value of that element into the variable. Repeat the process until all the elements are compared.
Program to print the largest element of a given array
In the following example, we have an int array arr
. The first element of this given array is stored into an int variable largestElement
. This is just the initialization of this variable, at the end of the program, this variable will hold the largest element of the array.
Running a loop from 0 till the size of the array. At every loop iteration, each element of the array is compared with the largestElement
, if any of the element is found greater than largestElement
, then the value of that element is assigned to largestElement
. This process continues until the whole array is traversed.
In the end, the variable largestElement
holds the largest element of the given array.
public class JavaExample { public static void main(String[] args) { //Initializing an int array int [] arr = new int [] {11, 22, 33, 99, 88, 77}; //This element will store the largest element of the array //Initializing with the first element of the array int largestElement = arr[0]; //Running the loop from 1st element till last element for (int i = 0; i < arr.length; i++) { //Compare each elements of array with largestElement //If an element is greater, store the element into largestElement if(arr[i] > largestElement) largestElement = arr[i]; } System.out.println("Largest element of given array: " + largestElement); } }
Output:
Largest element of given array: 99
Leave a Reply