Open In App

How to Find the Cumulative Sum of Array in C++?

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the cumulative sum, also known as the prefix sum of an array is the sum of all elements of the array at the current index including the sum of the previous elements. In this article, we will learn how to find the prefix sum of elements in an array in C++.

Example

Input: 
arr[]= {1,2,3,4,5}

Output:
Cumulative sum ={1, 3, 6, 10, 15}

Find the Prefix Sum of Elements in an Array in C++

To find the cumulative sum of the elements in an array, we can use a simple for loop to iterate through the array and update each element to be the sum of itself and all previous elements but make sure you are using the proper data type to store the sum so that it doesn’t overflow. Prefer to take a long long to be on the safe side.

C++ Program to Find the Cumulative Sum of Elements in an Array

The below program illustrates how we can find the cumulative sum of elements in an array in C++.

C++
// C++ Program to illustrate find the prefix sum of elements
// in an array
#include <iostream>
using namespace std;

int main()
{
    // Define the array of integers
    int array[] = { 1, 2, 3, 4, 5 };

    // Calculate the size of the array
    int n = sizeof(array) / sizeof(array[0]);

    // Declare an array to store the cumulative sum
    int cum_sum[n];

    // Calculate the cumulative sum
    cum_sum[0] = array[0];
    for (int i = 1; i < n; i++)
        cum_sum[i] = cum_sum[i - 1] + array[i];

    // Output the cumulative sum
    for (int i = 0; i < n; i++)
        cout << cum_sum[i] << " ";

    return 0;
}

Output
1 3 6 10 15 

Time Complexity: O(N), here N denotes the size of the array.
Auxiliary Space: O(N)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads