0

I want to write a program which takes an array of size N, loop over it and sum all the numbers before i (including i itself). I haven't done a lot so far because I don't know how to access the indexs before i. When I try for example arr[i - 1], it throws me an error that the index was outside the array bounds.

int N = int.Parse(Console.ReadLine());
int[] arr = new int[N];

// Input
for (int i = 0; i < arr.Length; i++)
    arr[i] = int.Parse(Console.ReadLine());

// Here we need to sum
for (int i = 0; i < arr.Length; i++)
// 

Example (N = 4)

Before = [1, 2, 3, 4]
After = [1, 3, 6, 10]
  • 1
    and https://stackoverflow.com/questions/4823467/using-linq-to-find-the-cumulative-sum-of-an-array-of-numbers-in-c-sharp , https://stackoverflow.com/questions/53759443/cumulative-sum-of-array-items , https://stackoverflow.com/questions/1184812/how-to-compute-a-running-sum-of-a-series-of-ints-in-a-linq-query – Drag and Drop Mar 19 '21 at 12:24
  • Does this answer your question? [Cumulative sum of an Array](https://stackoverflow.com/questions/24335660/cumulative-sum-of-an-array) – Drag and Drop Mar 19 '21 at 12:26
  • @DragandDrop It's weird that I haven't found that stuff, I already Googled. – Hassan Nasrallah Mar 19 '21 at 12:30
  • And yes `arr[i - 1]` when `i=0` is `arr[-1]` and -1 is out of bound perhaps start at i=1. Try to sum the first element with the previous non existing one. – Drag and Drop Mar 19 '21 at 12:30
  • Does this answer your question? [Cumulative sum of array items](https://stackoverflow.com/questions/53759443/cumulative-sum-of-array-items) – Lukas Thaler Mar 19 '21 at 15:45
  • Does this answer your question? [How to compute a running sum of a series of ints in a Linq query?](https://stackoverflow.com/questions/1184812/how-to-compute-a-running-sum-of-a-series-of-ints-in-a-linq-query) – CFreitas Mar 19 '21 at 16:48

2 Answers2

0

I don't know if this helps your learning process, but this is what I would do if I needed to do that logic.

Use Range to generate a collection of consecutive integers, up to n, then do a projection with LINQ of another collection from 1 to each value, then sum and convert to array.

int n = 10;
var result = Enumerable.Range(1, n)
 .Select(e => Enumerable.Range(1, e).Sum()).ToArray();
Crowcoder
  • 11,250
  • 3
  • 36
  • 45
-1

You can initialize the result array with the correct size beforehand and then use a plain loop to calculate the "running sum". You need a variable to track the current value:

int[] result = new int[arr.Length];
int currentSum = 0;
for (int i = 0; i < arr.Length; i++)
{
    currentSum += arr[i];
    result[i] = currentSum;
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939