Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read the second largest number in an array

I’ve written a console application (.NET 5.0) in C# in Visual Studio which sorts an array from high to low and then it has to print out the second largest element in that array.

Im getting close but ive been trying things for the past 2 hours and I don’t get why I always get an out of bounds error at the last ‘if’. The program is supposed to detect duplicates so for instance if the input is ‘1 1 2 2 5 5 9 9" it will print out "5" as it is the second largest.

My current code is below I can’t get it to work without crashing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System;

namespace second_largest
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] input = Array.ConvertAll(Console.ReadLine().Split(" "), Convert.ToDouble);

            for (int repeat = 0; repeat < input.Length; repeat++)
            {
                for (int j = 0; j < input.Length - 1; j++)
                {
                    if(input[j] < input[j+1])
                    {
                        double temp = input[j];
                        input[j] = input[j + 1];
                        input[j + 1] = temp;
                    }
                }
            }

            for (int i = 0; i < input.Length; i++)
            {
                if(input[i] == input[i + 1])
                {

                }
                else
                {
                    Console.WriteLine(input[i]);
                }
                Console.WriteLine(input[i]);
            }
        }
    }
}

>Solution :

You see the error because you iterate up to i < input.Length which means that i + 1 on the following if statement is out of bounds of the length of the input array. You need to do the same thing you’ve done on the previous nested for loop:

for(int i = 0; i < input.Length - 1; i++)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading