编写一段C++代码,实现前缀和
时间: 2024-05-05 07:19:01 浏览: 14
Sure, here's an example C code to implement prefix sum:
```
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}; // input array
int n = sizeof(arr) / sizeof(arr[0]); // calculate array size
int prefix_sum[n]; // output array for prefix sum
prefix_sum[0] = arr[0];
// calculate prefix sum
for (int i = 1; i < n; i++) {
prefix_sum[i] = prefix_sum[i - 1] + arr[i];
}
// print prefix sum
for (int i = 0; i < n; i++) {
printf("%d ", prefix_sum[i]);
}
printf("\n");
return 0;
}
```
This code takes an input array (arr) and calculates its prefix sum. The prefix sum of an array at index i is the sum of all elements from index 0 to i. The prefix sum is stored in an output array (prefix_sum). The code then prints the prefix sum array.
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)