Reputation: 112
I wrote a program for calculating Sum, Average, Min & Max without inbulit functions or Methods. I found many techniques and locked in the below one. But the problem is, while doing in normal ways. Result came. While transferring into a windows form, I am unable to get the output. It always throws error.
private void button1_Click(object sender, EventArgs e)
{
int n = int.Parse(textBox7.Text);
int[] numbers = new int[n];
int sum = 0;
float average;
for(int i=0; i<n; i++)
{
numbers[i] = int.Parse(textBox1.Text);
}
Array.Sort(numbers);
for(int i=0; i<n; i++)
{
sum += numbers[i];
}
average = ((float)sum / n);
textBox4.Text = numbers[0].ToString();
textBox5.Text = numbers[-1].ToString();
textBox2.Text = sum.ToString();
textBox3.Text = average.ToString();
}
The output should be like,
sum : 45
avg : 15
min : 8
max : 10
Upvotes: 1
Views: 1153
Reputation: 566
change the code for this line:
textBox5.Text = numbers[n-1].ToString();
as -1 is not an index here, your picking the max value here, it will be at n-1 index.
and for the line of code :
numbers[i] = int.Parse(textBox1.Text);
use this:
numbers[i] = Convert.ToInt32(textBox1.Text);
Upvotes: 0
Reputation: 2237
I think, the problem in your code is here:
textBox5.Text = numbers[-1].ToString();
there will be no entry in your array having -1 index.
If you want to show max value in textBox5, you need to do like that:
textBox5.Text = numbers[n-1].ToString();
if you want to show min value in textBox5, you need to do like that:
textBox5.Text = numbers[0].ToString();
Thanks!
Upvotes: 1
Reputation: 2180
Use linq ,is very clean way and work properly :
int n = int.Parse(textBox7.Text); ;
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
numbers[i] = int.Parse(textBox1.Text);
}
// var array = new short[] { 4, 4, 5, 6,9 };
var sum = numbers.Select(x => (int)x).Sum();
var avg = numbers.Select(x => (int)x).Average();
var max = numbers.Select(x => (int)x).Max();
var min = numbers.Select(x => (int)x).Min();
textBox4.Text = sum.ToString();
textBox5.Text = avg.ToString();
textBox2.Text = min.ToString();
textBox3.Text = max.ToString();
Upvotes: 0
Reputation: 326
Set your array i to contain all the values passed in through the user input on your form. You can then use this code to get all the values you want. Then just write the variables iMax, iMin, iSum and flAvg to your output labels. In this example I've just put my own data in to illustrate the code.
int[] i = { 1, 2, 3, 4, 5 };
int iSum = 0;
float flAvg = 0.0f;
int iMax = 0;
int iMin = Int32.MaxValue;
foreach (int iElement in i)
{
iSum = iSum + iElement;
flAvg = flAvg + iElement;
if (iElement > iMax)
{
iMax = iElement;
}
if (iElement < iMin)
{
iMin = iElement;
}
}
flAvg = flAvg / i.Length;
//carry on to do stuff with the data down here.
Upvotes: 1