+ 2
How can we show sum of a numberr series and number series also like 1+2+3+4+5... =Sum in C# ?
C# Programming
2 odpowiedzi
+ 8
Could just use a for loop.
const int limit = 100;
// sum up to this value
int sum = 0;
for(int i = 1; i <= limit; i++)
sum += i;
+ 3
Thought there would be something like
Math.Sum()
But there is not. I found this one which is very neat too.
Make a list or a array or another Inumberable
And use their sum-method
int[] array1 = { 1, 3, 5, 7 };
List<int> list1 = new List<int>() { 1, 3, 5, 7 };
//
// Use Sum extension on their elements.
//
int sum1 = array1.Sum();
int sum2 = list1.Sum();
//
// Write results to screen.
//
Console.WriteLine(sum1);
Console.WriteLine(sum2);
https://www.dotnetperls.com/sum