Sponsored Ad

Saturday, March 12, 2011

How to Find the Second Highest Number in Array using C#

This C# program will help you to find the second highest number in C#. i tried to make it as much efficient as possible. Please comment if you have some good idea.

How to Find the Second Highest Number in Array using C#

using System;

namespace MyApp
{
    class second_highest_class
    {
        static void Main(string[] args)
        {
            int[] input_array = {-1,-5,10, 5, 20};
            int highest_number = input_array[0];
            int second_highest_number;

            if (input_array[1] > highest_number)
            {
                second_highest_number = highest_number;
                highest_number = input_array[1];               
            }
            else
            {
                second_highest_number = input_array[1];
            }

            for (int i = 2; i < input_array.Length; i++)
            {
                if (input_array[i] > highest_number)
                {
                    second_highest_number = highest_number;
                    highest_number = input_array[i];       
                }
                else if (input_array[i] > second_highest_number)
                {
                    second_highest_number = input_array[i];       
                }
            }

            Console.WriteLine("second highest number in array: {0}", second_highest_number);
            Console.ReadLine();
        }       
    }
}

No comments:

Post a Comment

Post a Comment

Sponsored Ad

Development Updates