Given an array of integers A0 n 1 write C functions to com

Given an array of integers A[0, ..., n - 1]. write C++ functions to compute the prefix sum of A in the following ways. Output the prefix sum to a new array B. In other word, B[0] = A[0], B[1] = A[0] + A[1], B[2] = A[0] + A[l] + A[2], etc. Save the prefix sum in A itself.

Solution

#include <iostream>

using namespace std;

//method to calculate prefix sum. Takes array A, B and size of those arrays as input
void prefixSum(int A[], int B[], int size){

    //iterating through the array B
    for (int i=0; i<size; i++){
        B[i] = 0; //initialising each element of B to 0
        //iterating through the elements of array A less than the index of B
        for (int j=0; j<i+1; j++){
            B[i] += A[j]; //adding all those elements to element in B
        }
    }
}

int main(){
    int A[] = {1, 2, 5, 4, 5, 3}; //declaring array A
    int size = (sizeof(A)/sizeof(*A)); //getting size of input array
    int B[size]; //creating an array B to store prefix sum
    prefixSum(A, B, size); //calling prefixSum function

    //iterating through B to copy B to A
    for(int i=0; i<size; i++){
        A[i] = B[i];
        cout<<A[i]<<\", \"; //outputing A
    }
    cout<<endl;
    return 0;
}

 Given an array of integers A[0, ..., n - 1]. write C++ functions to compute the prefix sum of A in the following ways. Output the prefix sum to a new array B.

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site