Friday, October 6, 2017

Write the code to find 1st , 2nd and 3rd highest element in an array



Programming Question -  Write the code to find 1st , 2nd and 3rd highest element in an array. You don’t have to use sorting function. Same values should be skipped, means if input is [3,3,2,5], output must be 5,3,2
Solution:
There are many logic to do it. I am trying following logic. I am using C# language syntax and keywords.
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter number of elements of Array : "); // To take input from user
            int totNum = Convert.ToInt32(Console.ReadLine()); // Total number of elements in Array
            // int[] a = { 5, 5, 7, 1, 2,3 }; // use this code for fixed input
            int[] a = new int[totNum]; // creating array of input size
            Console.WriteLine("Input Array Elements : ");
            for (int j = 0; j < totNum; j++) // Loop to take input elements in the array
            {
                a[j] = Convert.ToInt32(Console.ReadLine());
            }
           
            int h1 = 0; // for first highest number
            int h2 = 0;// for second highest number
            int h3 = 0; // for third highest number
            for (int i = 0; i < a.Length; i++)
            {
                /*
                Inside this loop we are checking that if current value of array is greater than variable,
                we assign that value to the variable. In the same way, we do for all variables.
                */
                if (a[i]>=h1)
                {
                    if (a[i] == h1) // skip iteration if same value
                    {
                        continue;
                    }
                    h3 = h2;
                    h2 = h1;
                    h1 = a[i]; // Assigning First highest value. Always write this statement at last for no loss of assigned value
                }
                else if (a[i]>=h2)
                {
                    if (a[i] == h2)
                    {
                        continue;
                    }
                    h3 = h2;
                    h2 = a[i]; // Assigning Second highest value
                }
                else if (a[i]>=h3)
                {
                    if (a[i] == h3)
                    {
                        continue;
                    }
                    h3 = a[i]; // Assigning Third highest value
                }
            }
            Console.WriteLine("First highest:"+h1+", Second highest: "+h2+", Third highest: "+h3);
            Console.ReadLine();
        }
    }
Description – Please read comments for description.

I hope, it will help.

Happy Coding
Rudra Pratap Singh
Software Engineer

How to Get Organic Views on Your Channel/Content

 Hi Friends, This post will be very short and specific in the information.  If you are a content creator and want some help in getting organ...