I have a problem with finding second largest number in my array.The thing is, it doesn't work for all my examples. After i read numbers from keyboard i put them in method test and then i sort them.. example:(user entered) 1,2,3,4,5,6,7,8,9,10 exit:10,9,..3,2,1 Now i want to display second largest number with for loop.. **The task is: find second largest number if its possible, if not CW("error") **
in code Comment //HERE i'm not sure how to writhe correct that part of code.
i hope my problem makes sense...
public static int test(int[] polje)
{
int temp = 0;
Console.WriteLine();
for (int c = 0; c < polje.Length; c++)
{
for (int b = c + 1; b < polje.Length; b++)
{
if (polje[c] > polje[b])
{
temp = polje[c];
polje[c] = polje[b];
polje[b] = temp;
}
}
}
int secondlargest = 0;
//HERE
for (int i = polje.Length - 1; i >= 0; i--)
{
if (polje[polje.Length - 2] == polje[polje.Length - 1] || polje[polje.Length - 2] == 0)
{
Console.WriteLine("Wrong!");
break;
}
else
{
Console.WriteLine("Second largest number is :{0}", polje[polje.Length - 2]);
secondlargest = polje[polje.Length - 2];
break;
}
}
return secondlargest;
}
static void Main(string[] args)
{
int[] polje = new int[10];
Console.WriteLine("Enter values");
for (int i = 0; i < 10; i = i + 1)
{
polje[i] = int.Parse(Console.ReadLine());
if (polje[i] == 0)
{
break;
}
}
test(polje);
Console.ReadLine();
}
}
}