Reputation: 57
I need to find the value and position of the lowest entry in the table. Problem is, I don't know how to specify it. I can't put any numeric in the int value for minimum because the user can always specify a higher value. It works for the highest value but it doesn't for the smallest.
Console.WriteLine("Podaj wymiar tablicy.");
int dlugosc = Convert.ToInt32(Console.ReadLine());
int[] tablica = new int[dlugosc];
int max = 0;
int min = tablica[0];
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < tablica.Length; i++)
{
while (tablica[i] > max)
{
max = tablica[i];
}
}
for (int x = 0; x < tablica.Length; x++)
{
while (tablica[x] < min)
{
min = tablica[x];
}
}
int najmniejsze_miejsce = Array.IndexOf(tablica, min);
int najwieksze_miejsce = Array.IndexOf(tablica, max);
Console.WriteLine("Najwyzsza wartosc tablicy to {0}.", max);
Console.WriteLine("Najwieksza wartosc wystepuje na miejscu {0}.", najwieksze_miejsce);
Console.WriteLine("Najniższa wartość tablicy to {0}.", min);
Console.WriteLine("Najnizsza wartosc wystepuje na miejscu {0}", najmniejsze_miejsce);
Console.ReadKey();
Upvotes: 2
Views: 391
Reputation: 39277
When you do need to do a scan you typically set the min value to Int.MaxValue
and the max value to Int.MinValue
before the loop and then you are guaranteed to set it on the first element and any element that improves either value.
You can then do it all in one loop (and you don't need to use while
when you mean if
). You can also track the index as you go:
int max = Int.MinValue;
int min = Int.MaxValue;
int maxindex = -1;
int minindex = -1;
for (int i = 0; i < tablica.Length; i++)
{
if (tablica[i] > max) { max = tablica[i]; maxindex = i; }
if (tablica[i] < min) { min = tablica[i]; minindex = i; }
}
Upvotes: 0
Reputation: 1
You can find the first occurence of the min value in your table
int minIndex = Array.IndexOf(tablica, tablica.Min());
or simple:
Console.WriteLine(Convert.ToString(Array.IndexOf(tablica, tablica.Min())));
Upvotes: 0
Reputation: 26
The current code is below:
int min = tablica[0];
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
The min value being declared before the array is initialized means it will simply be zero. No value from your array can ever be less unless it's a negative number.
To fix, the min should be declared after the array is initialized:
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
int min = tablica[0];`
Upvotes: 0
Reputation: 3880
you can just use:
Console.WriteLine(tablica.Min());
since your using an integer array
Upvotes: 4