Damjan25 - 1 year ago 57
C# Question

# Find Second Largest Number Without Arrays

I have to make program that will return the second highest number from user input.

The user can input a minimum of 2 numbers and a maximum of 10 numbers. The user can only input integers (not decimals), to stop the program I am using 0.

My problem is: if I input 1,2,2,0 it outputs 2 which is not correct, it should output 1.

Below is what I am doing currently:

``````static void checking(double n, ref double max, ref double smax)
{
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
}
static void Main(string[] args)
{
double n = 1, max = -99999999, smax = -99999999, ISsmaxrepeating = 0;
int i = 0;

while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
if (n % 1 == 0)
{
checking(n, ref max, ref smax);

i++;
}
else
{
smax =0;
break;
}
}
if (smax != 0)
{

Console.WriteLine("secondmax is {0}", smax);

}
else
{
Console.WriteLine("error");
}

}
``````

And here are some test cases:

example 1.:

input: 10 5 -4 8 5 0

output: 8

example 2.:

input: 5 5 5 5 0

output: "error"

example 3.:

input: 1 0

output: "error"

example 4.:

input: 1 2 3 4 5 6 7 8 9 10

output: 9

Just ignore a number if you already have it:

``````...
while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
if (n % 1 == 0)
{
if(n != max && n != smax)
checking(n, ref max, ref smax);

i++;
}
else
{
smax =0;
break;
}
}
...
``````

By the way, I am not convinced of the way you try to handle error cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download