File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < vector>
3
+
4
+ // Function to calculate the prefix sum of an array
5
+ std::vector<int > calculatePrefixSum (const std::vector<int >& arr) {
6
+ int n = arr.size ();
7
+ std::vector<int > prefixSum (n, 0 );
8
+
9
+ prefixSum[0 ] = arr[0 ];
10
+ for (int i = 1 ; i < n; i++) {
11
+ prefixSum[i] = prefixSum[i - 1 ] + arr[i];
12
+ }
13
+
14
+ return prefixSum;
15
+ }
16
+
17
+ int main () {
18
+ // Input the array size
19
+ int n;
20
+ std::cout << " Enter the size of the array: " ;
21
+ std::cin >> n;
22
+
23
+ if (n <= 0 ) {
24
+ std::cout << " Array size must be a positive integer." << std::endl;
25
+ return 1 ; // Exit with an error code
26
+ }
27
+
28
+ // Input the elements of the array
29
+ std::vector<int > arr (n);
30
+ std::cout << " Enter " << n << " elements of the array: " ;
31
+ for (int i = 0 ; i < n; i++) {
32
+ std::cin >> arr[i];
33
+ }
34
+
35
+ // Calculate the prefix sum
36
+ std::vector<int > prefixSum = calculatePrefixSum (arr);
37
+
38
+ // Display the prefix sum
39
+ std::cout << " Prefix Sum: " ;
40
+ for (int i = 0 ; i < n; i++) {
41
+ std::cout << prefixSum[i] << " " ;
42
+ }
43
+ std::cout << std::endl;
44
+
45
+ return 0 ;
46
+ }
You can’t perform that action at this time.
0 commit comments