Tech Point Fundamentals

Saturday, January 22, 2022

C# Program to Find the Third Largest Element in an Array

C# Program to Find the Third Largest Element in an Array

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


How can you find the third largest element in an array using only a single loop? Write a program to find the third largest element in an array.









C# Program to Find the Third Largest Element in an Array


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Third Largest Array Element

using System;

public class Program
{
public static void Main()
{
  int[] unsortedArray = new int[8] {5, 3, 6, 2, 1, 4, 8, 7};			
  		
  Console.WriteLine("Input UnSorted Array: ");	
  Console.WriteLine("------------------------------------------------ ");	
  for( int i = 0; i < unsortedArray.Length; i++)
  {
  	Console.WriteLine(unsortedArray[i]);
  }
  
  Console.WriteLine("\n\nThird Largest Element : " + ThirdLargetElement(unsortedArray));		
}		
		
static int ThirdLargetElement(int[] array)
{		
	int large = 0, small = 0, mid = 0;	
 
	for(int i = 0; i < array.Length; i++) 
	{
			if (large < array[i] && mid <= large)
			{
				small = mid;
				mid = large;
				large = array[i];
			}
			else if (mid < array[i] && small <= mid)
			{
				small = mid;
				mid = array[i];
			}
			else if (small <= array[i])
			{
				small = array[i];
			}
	}
	return small;  
}	
}





Output: 



                Input UnSorted Array: ------------------------------------------------ 5 3 6 2 1 4 8 7 Third Largest Element : 6


Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.