Coding Challenge Day-19: Problem 2: Find second largest number in integer array

Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 19: Problem 2! Be sure to post your answers, queries etc in the comments!

Problem: Find second largest number in integer array

Sample: int array[]= {4,2,6,1,9,5};
Output: Second largest number in array [4, 2, 6, 1, 9, 5] is 6

Solution:

package array;

import java.util.Arrays;

public class Program014find_second_largest_number {
	
	public static Integer second_largest (int [] array){
		if(array.length<2){
			return null;
		}
		int largest=array[0];
		int second=array[0];
		
		for(int i=0; i<array.length; i++){
			if(array[i]>largest){
				second=largest;
				largest=array[i];
			}
		}
		
		return second;
		
	}
	
	public static void main (String [] args){
		int array[]= {4,2,6,1,9,5};
		
		System.out.println("Second largest number in array " + Arrays.toString(array) + " is " + second_largest(array));
	}

}

Download Code

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close