Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to find second largest element in array.

Write a program to find second largest element in array.

Given a integer array we have to find second largest element in an array.

Example:

input:arr[]={21,3,7,9,12}
output:12

Logic:

step 1- declare max and min to -1
step 2- compare the value of max and min with array value.
step 3- print the max and min value

Code-

#include<bits/stdc++.h>
using namespace std;

int main()
{
	int arr[] = { 22, 85, 11, 90, 84, 12 };
	int n = sizeof(arr) / sizeof(arr[0]);
	int first =-1;
	int second=-1;
	
		for (int i=0; i<n; i++) 
		{
		if (arr[i] > first)
		{
			second = first;
			first = arr[i];
		}

	
		else if (arr[i] > second && arr[i] != first)
		{
			second = arr[i];
	}
		    
		}
	if (second == -1)
	{
		cout<<"not exist"<<endl;;
	}
	else
	{
		cout<<"The second largest element is "<<" "<<second<<endl;;
	}
	
	
}

Output:

The second largest element is  85

Time complexity:0(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments