How to avoid copying values to a separate array?

c++

Solution

You don't need the two nested `for` loops. Move the initialization of `sum` out of the `for` loop to keep track of the `sum` as you iterate over `orig`. The simply overwrite the values in `orig` with `sum` as you go.

In psuedocode:

sum = 0
for each index i in array:
  sum += array[i]
  array[i] = sum

Problem

I have the following program that computes the "partial sum" of an array. For example, if I input the consecutive integers `1, 1, 1, 1` through `std::cin` my program will calculate the result into an array as `1, 2, 3, 4`. ``` #include <iostream> int main() { int orig[10], copy[10]; std::cout << "please enter 10 numbers:" << std::endl; for (int i = 0; i < 10; i++) { std::cin >> orig[i]; } for (int i = 0; i < 10; ++i) { int sum = 0; for (int k = i; k >= 0; --k) { sum += orig[k]; } copy[i] = sum; } std::cout << "the ascending order is:\n" << endl; for (int i = 0; i < 10; ++i) std::cout << copy[i] << std::endl; } ``` My problem is that I would like for there to be a way to do this without copying the value into another array. So far I haven't figured out how. As you can see, in the above code I have an integer array named `copy` into which I put the sum into its indicies. I know this can be done using `std::vector` and `partial_sum` but I would rather not use it as it does not allow me to fully understand how this works. Any ideas? Thanks.

Original source