How to Find the Largest Element in an Array in Java | Program Feed Blog | Vinayak Sutar



public class BiggestElement {

public static void main(String[] args) {
int[] numbers = new int[] { 12, 54, 21, 53, 62, 48, 57, 41 };
//Let's assume that the first element of the array is
// the biggest element
       int biggestNumber = numbers[0];
for (int i = 0; i < numbers.length; i++) {
/*
* Iterating through each element and checking whether
* the number is bigger or not
*/
if (biggestNumber < numbers[i]) {
biggestNumber = numbers[i];
}
}

System.out.println("Biggest Element : " + biggestNumber);

}
}

    Take a look at the above code. We have an array which consists of many integer elements. We have to find out which is the biggest number. To find it out let's assume that the first element is the biggest. This assumption is just a guess. It is not our answer. For now, we don't know which is the biggest number. So let's start with an assumption. It may be the biggest number, but now we don't know.

    To ensure that the assumed number is the biggest, we iterate through every element of the array. In each step, we check whether the assumed number is the biggest. If we find that the current number in the array is bigger than our assumed number then we will replace it with our assumed number and continue our iteration. After iterating through the array we will get the biggest number at the end.

Comments

Post a Comment