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
<code class="cpp">int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; }</code>
2. std::accumulate
<code class="cpp">int sum = std::accumulate(std::begin(arr), std::end(arr), 0);</code>
3. Range for loop
<code class="cpp">int sum = 0; for (int num : arr) { sum += num; }</code>
4. std::reduce (C 20 and above)
<code class="cpp">int sum = std::reduce(std::begin(arr), std::end(arr), 0, std::plus<int>{});</code>
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!