Find the Sum of an Array of Numbers in C#
Let’s say you have an array of numbers (either doubles or integers) and want to be able to find the sum of these numbers. To my knowledge, there is not a built-in way to do this in the .NET Framework, so I created a little utility method that does this for doubles and for integers. See below.
public static double Sum(params double[] values) { if (values.Length == 0) return 0.0; double result = 0.0; foreach (double value in values) result += value; return result; } public static int Sum(params int[] values) { if (values.Length == 0) return 0; int result = 0; foreach (int value in values) result += value; return result; }
int n1, n2, sum;
Console.WriteLine(“plz type the 1st number”);
n1 = int .Parse (Console .ReadLine ());
Console.WriteLine(“plz type the 2nd number”);
n2 = int .Parse (Console .ReadLine ());
sum = n1 + n2;