Damjan25 Damjan25 - 8 days ago 5
C# Question

C# (find second largest number) How to split program in subprograms ?so I can reuse code later...?

I have this program that finds second largest number from users input, user needs to input atleast 2 numbers and maximum 10. I want to split program into subprograms(at least main and one function). And i cant get it to work :(

Org. code:

static void Main(string[] args)
{
int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0;

while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
n = int.Parse(Console.ReadLine());
//I want this part to be in a function from here.
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
//to here
if (n == smax)
{
ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1 it outputs error
}

i++;
}
if (smax != 0 && smax != ISsmaxrepeating)
{

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

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


So far I come up with this but it is not working :(

static int checking(int n, int max, int smax)
{
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
return n;
}
static void Main(string[] args)
{
int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0, result = 0;

while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
n = int.Parse(Console.ReadLine());

result = checking(n,max,smax);

if (n == smax)
{
ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1 it outputs error
}

i++;
}
if (smax != 0 && smax != ISsmaxrepeating)
{

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

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


}

Answer

You can output multiple variables from the function using ref keyword. However, it's better not to use a function for this kind of operation.

static void checking(int n, ref int max, ref int smax)
{
    if (n > max)
    {
        smax = max;
        max = n;
    }
    else if (n > smax)
    {
        smax = n;
    }
}

Call the function inside Main

checking(n, ref max, ref smax);
Comments