Second largest element of an array

C# code to print the second largest element of an array without using any extra variable:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace SecondLargest

{

    class SecondLargest

    {

        static void Main(string[] args)

        {

            //Program to display the second largest element in an array

            try

            {

                int[] array = { 10, 1, 3, 4, 5, 8, 9, 2, 6, 7};

                Array.Sort(array);

                for (int i = array.Length-1; i > 0 ; i–)

                {

                    if (array[i] != array[i – 1])

                    {

                        Console.WriteLine("Second largest element of the array is: " + array[i – 1]);

                        break;

                    }

                    else if (i == 1)

                    {

                        Console.WriteLine("All the array elements are equal.");

                    }

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s