Find Largest and Second Largest Number in C#

Hi Programmers, welcome to new article of c#.net. this article i’ll write the program to display Largest and Second Largest Numbers in given array in c# console application. we can achieve the output by using for loop and if else if statement or nested for loop. let’s see codes.

Example 1
Example 2
********************
Example 1
*******************
using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int n,i,max1,max2;
            Console.Write("Enter the size of array :");
            n = int.Parse(Console.ReadLine());

            int[] arr = new int[55];
            Console.WriteLine("Enter the Elements : ");
            for(i = 0;i<n;i++)
            {
                arr[i] = int.Parse(Console.ReadLine());
            }
            max1 = max2 = int.MinValue;
            for(i=0;i<n;i++)
            {
                if(arr[i]>max1)
                {
                    max2 = max1;
                    max1 = arr[i];
                    
                }
                else if(arr[i]>max2)
                {
                    max2 = arr[i];
                }
            }
            Console.WriteLine("First Largest Element : " + max1);
            Console.WriteLine("Second Largest Element : " + max2);
        }
    }
}


*********************
Example 2
*********************

using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            int[] arr = { 66,88,99,44,33 };
            int cnt = arr.Length;
            for (int i = 0; i < cnt; i++)
            {
                for (int j = i + 1; j < cnt; j++)
                {
                    if (arr[i] > arr[j])
                    {
                        a = arr[i];
                        arr[i] = arr[j];
                        arr[j] = a;
                    }
                }
            }
            Console.WriteLine("Largest: " + arr[cnt - 1]);
            Console.WriteLine("Second Largest: " + arr[cnt - 2]);
        }
    }
}

Happy Coding…Thanks.

Post Author: adama