How do you calculate the sum of arrays?

closed account (EA59E3v7)
I'm new to C++ language. I would like to random generate 5 numbers (between 0 and 50) and then calculate their sum. Could I see an example of this?

I know about the showSum(1,2,3) function. But if I generate 5 numbers and put them in a container or array, how could I showSum that? An example I would very much like to see. Where to start?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>

template < typename ARRAY_OR_CONTAINER_OF_INT >
auto sum( const ARRAY_OR_CONTAINER_OF_INT& array_or_container )
{
    int sum = 0 ;
    // http://www.stroustrup.com/C++11FAQ.html#for
    for( int value : array_or_container ) sum += value ;
    return sum ;
}

int main()
{
    const int array[] { 36, 678, -72, 0, 56 } ;
    std::cout << "sum: " << sum(array) << '\n' ;

    const std::vector<int> vec { 36, 678, -72, 0, 56 } ;
    std::cout << "sum: " << sum(vec) << '\n' ;
}
The same with C++ Standard Library algorithm std::accumulate (which is more generic than the sum() above):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
#include <numeric>      // std::accumulate

int main ()
{
  const int array[] { 36, 678, -72, 0, 56 } ;
  std::cout << "sum: " << std::accumulate( std::begin(array), std::end(array), 0 );
  std::cout << '\n';

  const std::vector<int> vec { 36, 678, -72, 0, 56 } ;
  std::cout << "sum: " << std::accumulate( std::begin(vec), std::end(vec), 0 );
  std::cout << '\n';

  return 0;
}
> which is more generic than the sum() above

It is not a wee bit more generic than the range-based loop version.

Both std::accumulate( std::begin(array), std::end(array), 0 ) ;
and int sum = 0 ; for( int value : array ) sum += value ; accumulate values into an integer.
The only pedantic difference is that std::acumulate uses the + operator, the range-based loop uses the += operator.

Both std::accumulate( std::begin(vec), std::end(vec), decltype( +vec.front() ){} ) ;
And decltype( +vec.front() ) sum {} ; for( const auto& value : vec ) sum += value ;
would be more generic.
Topic archived. No new replies allowed.