11 July, 2019

Find the largest number from an array using java

In this article, we will see how to find the largest number from an array using java.  This is one of basic questions in technical interviews. Earlier post we had seen how to find the smallest element from array. Now we will see how to find the largest number from integer array using java. 


The logic is very simple here, see the below.

  • At first we need to assume any element as largest value. Example - 0th location.
  • Then iterate over the array and compare with each element , whether its larger than the assumed larger value or not. If array element is larger then assign the array element value to assumed variable. Repeat the entire until end. 


FindLarestNumerInArray.java



package com.javadevelopersguide.lab.basic;
/**
 * This program illustrate how to find the Largest number from an array.
 *
 * @author manoj.bardhan
 *
 */
public class FindLarestNumerInArray {
// Find the largest value from an array.
public static void main(String[] args) {
int[] arr = { 200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150 };
// Assume the largest value is 0th Index
int largest = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] >= largest) {
largest = arr[i];
}
}
System.out.println("Largest Number is ::" + largest);
}
}


Output - 

Largest Number is ::200


Using Java 8

int largest = IntStream.of(arr).boxed().max(Comparator.naturalOrder()).get().intValue() ;


 Happy Learning.

1 comment:

  1. CASINO REVIEWS | JTG Hub
    The casino at Harrah's Lake Tahoe has not been at 순천 출장안마 the top of my list for many years. The room is 성남 출장샵 perfect. 여수 출장마사지 But 김천 출장안마 I cannot find any reviews yet. 계룡 출장샵 Rating: 3.9 · ‎Review by JTG Staff

    ReplyDelete