Windows application issue in array sum
Given an array initialized with numbers, how can I add all of its elements without using LINQ or foreach
?
My incomplete code is as follows:
namespace WindowsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
method1(sum1);
MessageBox.Show("The Sum Is = " + sum1.ToString(), "Addition",MessageBoxButtons.OK,MessageB…
}
int sum1;
int[] str = new int[4] { 1, 2, 3, 4 }; // i want to add this 4 values and to be printed on a messagebox//
public int method1(int str)
{
sum1 = str;
return sum1;
}
}
}
The output is showing "the sum is = 0", in开发者_Go百科stead of 10.
Thank you.
P.S: I don't want to use LINQ or foreach
.
For a start you have global variables which are bad. Without using LINQ
or Foreach
as you mentioned, try something like:
//Doesn't have to be a button click...just an example.
private void button1_Click(object sender, EventArgs e)
{
int[] values = new int[4] { 1, 2, 3, 4 };
int result = Sum(values);
MessageBox.Show(result.ToString());
}
int Sum(int[] values)
{
int sum= 0;
for (int i = 0; i < values.Length; ++i)
{
sum += values[i];
}
return sum;
}
The simplest options that don't use foreach
or LINQ
would be to use either a for
loop or recursion.
The recursive solution:
int Sum(int[] arr, int index = 0, int current = 0)
{
if(index == arr.Length)
return current;
return Sum(arr, index+1, current+arr[index]);
}
Using a for loop:
int Sum(int[] arr)
{
int result = 0;
for(int i = 0; i<arr.Length; i++)
result+=arr[i];
return result;
}
To take the sum of an array, you can simply say: int sum = myArray.Sum();
To do so you need to have: using System.Linq
since that's where the Sum extension method is defined.
If you don't have linq, then how about:
private int CalculateSum(int[] arr){
int total = 0;
foreach(int i in arr)
total += i;
return total;
}
I'm curious about why you're opposed to a for
loop. Could you enlighten us?
Unless I'm missing something, it seems like you've got two options:
1) use an existing method (in this case it would be the .Sum()
method, in LINQ
), or
2) write a method yourself to compute the sum (that would be the foreach
loop)
精彩评论