Damjan25 Damjan25 - 11 days ago 6
C# Question

c# find second largest number without using array

I have to make program that will return second highest number from user-s input. User can input min 2 and max 10 numbers and user can input only not decimal numbers(to stop the program i am using 0). I discovered that my algorithm has flaws... if I input 1,2,2,0 it outputs 2 which is not correct, it should output 1. Down bellow I have my code so far :) pls help me fix my algorithm

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

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");
n = double.Parse(Console.ReadLine());
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");
}

Console.ReadLine();


}

Answer

Just ignore a number if you already have it:

...
while (n != 0 && i < 10)
{
    Console.WriteLine("Input number");
    n = double.Parse(Console.ReadLine());
    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.