Coding Lab - TechOnTechnology

Program in C# to find the second largest element in a single dimensional array.

using System;

namespace Lab_Ex_7
{
    class SecondLargest
    {
        public static void Main()
        {
            int[] a;
            Console.Write(" Enter the size of the array : ");
            a = new int[int.Parse(Console.ReadLine())];
            Console.WriteLine(" \n Enter the array elements ");
            for (byte i = 0; i < a.Length; i++)
                a[i] = int.Parse(Console.ReadLine());
            int max1, max2;
            max1 = max2 = a[0];
            for (byte i = 1; i < a.Length; i++)
            {
                if (a[i] > max1)
                {
                    max2 = max1;
                    max1 = a[i];
                }
                else
                    if ((a[i] > max2 && a[i] < max1) || max1 == max2)
                    {
                        max2 = a[i];
                    }
            }
            Console.WriteLine(" \n First largest element is: " + max1);
            Console.WriteLine(" \n Second largest element is: " + max2);
            Console.ReadLine();
        }
    }  
}

Name

Email *

Message *