Sums in C can be expressed in the following ways: a normal loop, std::accumulate, a ranged for loop, and std::reduce (C 20 and later). The choice depends on the amount of data, the need to operate on the elements, and the C version.
Representation of summation in C
In C, summation can be expressed in the following ways:
1. Ordinary loop
int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; }
2. std::accumulate
int sum = std::accumulate(std::begin(arr), std::end(arr), 0);
3. Range for loop
int sum = 0; for (int num : arr) { sum += num; }
4. std::reduce (C 20 and above)
int sum = std::reduce(std::begin(arr), std::end(arr), 0, std::plus<int>{});
Selection scheme
Which summation representation to choose depends on the specific situation. Generally speaking:
The above is the detailed content of How to express sum in c++. For more information, please follow other related articles on the PHP Chinese website!