I'm getting stuck on getting min value from array. every time when I run it, the minimum value is still zero. I know that the index has to go to minus one, but i just don't know how should I apply it on the code. sorry for my poor English, I hope you guys can help me out!
public partial class Form1 : Form
{
int[] numbers = new int[99];
int index = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public int Som()
{
//if the numbers are <99 they will be add to index.
int som = 0;
for (int i = 0; i < 99; i++)
{
som = som + numbers[i];
}
return som;
}
public int Average()
{
//
int answersom = Som();
int g = (answersom / index);
return g;
}
public int Max()
{
int Max = numbers[0];
foreach (int number in numbers)
{
if (number > Max)
{
Max = number;
}
}
return Max;
}
public int Min()
{// array gets de value thats on 0
int Min = numbers[0];
foreach (int number in numbers)
{// if the number is smaller then 0.
if (number < Min)
{// zero is the new number
Min = number;
}
}
return Min;
}
private void button1_Click(object sender, EventArgs e)
{
//if textbox doesnt contain numbers
if (textBox1.Text.All(chr => char.IsLetter(chr)))
{
//labeltext message 'please only fill in numbers'
label1.Text = "Vul alleen Cijfers in";
}
//else
else
{
//is putting the numbers on the right spot of the array
numbers[index] = Convert.ToInt32(textBox1.Text);
//index will add each time.
index++;
label4.Text = Convert.ToString(Som());
}
//
int g = Convert.ToInt32(textBox1.Text);
label5.Text = Convert.ToString(Average());
{
label6.Text = Convert.ToString(Min());
label7.Text = Convert.ToString(Max());
}
}
}
}
You can easily use with Linq,
Using System.Linq;
int min = numbers.Min();
The problem is that you always calculate the minimum with all numbers, which includes zeroes for all the numbers you haven't added yet with the button. That's why your minimum always returns 0 right now unless you add 99 numbers. You need to change your Min
function to:
public int Min() {
int min = numbers[0];
for (int i = 0; i < index; i++) {
int number = numbers[i];
if (number < min) {
min = number;
}
}
return min;
}
As you can see, the function will now only calculate the minimum using the numbers you have added (with index below index
) and not all numbers in the numbers
array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With