user9741196
user9741196

Reputation:

Finding a cummulative sum from elements in an array using a loop?

I would like to receive a running sum of an array, 'Array.' But, I am having difficulty trying to create a for loop that can iterate through this array and add through the values in Array. Any ideas would be appreciated.

#include <stdio.h>

void cSum (int Array[], int length);

int main (void) {

    int Array[5]={1,-1,92,5,432};
    int length=5;

    printSum(Array, length);
}

void cSum (int Array[], int length) {

    int i; 
    int sum[length]; 
    int running=0; 
    int product[length]; 

    for (i=0; i<length; i++) {
         //Difficulty trying to get the cummulative sum
        sum[i]=Array[i];
        running=running+1
    }

    printf("sum: ");
    for (i=0; i<length; i++) {
        printf("%d ", sum[i]);
    }
}

Upvotes: 0

Views: 80

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

A simple approach is to set up the first element of sum, and then proceed with the remaining elements in the loop:

sum[0] = array[0];
for (i = 1; i < length; ++i){
    sum[i] = sum[i - 1] + array[i];
}

I've taken the liberty of renaming Array to the less idiosyncratic array. Consider also using a size_t type for the indexing variable i rather than an int.

Upvotes: 1

Related Questions