ShadowWesley77
ShadowWesley77

Reputation: 385

How to add all numbers in an array in C++?

Instead of typing

array[0] + array[1] //.....(and so on)

is there a way to add up all the numbers in an array? The language I'm using would be c++ I want to be able to do it with less typing than I would if I just typed it all out.

Upvotes: 21

Views: 88218

Answers (10)

SridharKritha
SridharKritha

Reputation: 9681

Adding one more point regarding std::accumulate usage:

When a C-style array is passed to a function then you should explicitly specify the array start and end(one-past-the-end) addresses when you use the std::accumulate.

Example:

#include <numeric>
void outsideFun(int arr[], int n) {
    int sz = sizeof arr / sizeof arr[0]; // 1=decays to a ptr to the 1st element of the arr
    // int sum = accumulate(begin(arr), end(arr), 0); // Error:begin/end wouldn't work here
    int sum = accumulate(arr, arr + n, 0);            // 15 (Method 2 Only works!)
    std::cout << sum;
}

int main() {    
    int arr[] = { 1,2,3,4,5 };
    int sz = sizeof arr / sizeof arr[0];           // 5
    int sum = accumulate(begin(arr), end(arr), 0); // 15 (Method 1 - works)
    int cum = accumulate(arr, arr + sz, 0);        // 15 (Method 2 - works)
    outsideFun(arr, sz);
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

Here is the idiomatic way of doing this in C++:

int a[] = {1, 3, 5, 7, 9};
int total = accumulate(begin(a), end(a), 0, plus<int>());

Note, this example assumes you have somewhere:

#include <numeric>
using namespace std;

Also see: accumulate docs and accumulate demo.

Upvotes: 50

Tony Tannous
Tony Tannous

Reputation: 14871

If your compiler supports c++17, you may use a combination of Parameter pack and fold expression to achieve this. A template parameter pack is a template parameter that accepts zero or more template arguments, and fold reduces the parameter pack over a binary operator. (+ in this case)

#include <iostream>
#include <array>
#include <utility>

/* 
 * References:
 *   [1] https://en.cppreference.com/w/cpp/language/fold
 *   [2] https://en.cppreference.com/w/cpp/language/parameter_pack
 */


template <typename ...T>
auto sum(T ...args)
{
    return (args + ...);
}

template <typename T, std::size_t ...Is>
auto sum(T t, std::index_sequence<Is...>)
{
    return sum(t[Is]...);
}

int main()
{
    std::array<int, 3> a1 = {1, 4, 3};
    int a2[5] = {1, 2, 3, 4, 0};

    std::cout << "Sum a1 = " << sum(a1, std::make_index_sequence<a1.size()>{}) << "\n";
    std::cout << "Sum a2 = " << sum(a2, std::make_index_sequence<5>{}) << "\n";
    return 0;
}

Upvotes: 0

Name_Guest
Name_Guest

Reputation: 1

int Sum;
for(int& S: List) Sum += S;

Upvotes: 0

rashedcs
rashedcs

Reputation: 3725

We may use user defined function.

Code Snippet :

#include<bits/stdc++.h>
using namespace std;


int sum(int arr[], int n)
{
    int sum=0;

    for(int i=0; i<n; i++)
    {
        sum += arr[i];
    }
    return sum;
}


int main()
{
  int arr[] = {1, 2, 3, 4, 5};
  int n = distance(begin(arr), end(arr));

  int total = sum(arr,n);

  printf("%d", total);

  return 0;
}

Upvotes: 0

Mohammad Alaggan
Mohammad Alaggan

Reputation: 3909

In C++17, one could use fold expressions:

template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
    return (a + ...);
}

If sum_impl had a constant number of parameters, we could have called it like this:

std::apply(sum_impl, arr);

assuming arr is std::array<int, N>. But since it is variadic, it needs a little push with helpers:

using namespace std;

template <class Array, size_t... I>
int sum_impl(Array&& a, index_sequence<I...>)
{
        return sum_impl(get<I>(forward<Array>(a))...);
}

template <class Array>
int sum(Array&& a)
{
        return sum_impl(forward<Array>(a),
                        make_index_sequence<tuple_size_v<decay_t<Array>>>{});
}

Therefore, assuming these helpers are in place, the code will look something like this:

template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
    return (a + ...);
}

int main()
{
    array<int, 10> arr{0,1,2,3,4,5,6,7,8,9};
    cout << sum(arr) << "\n";
    return 0;
}

Upvotes: 3

Kiersten Jay Raymond
Kiersten Jay Raymond

Reputation: 94

Try this:

int array[] = {3, 2, 1, 4};
int sum = 0;

for (int i = 0; i < 4; i++) {
    sum = sum + array[i];
}
std::cout << sum << std::endl;

Upvotes: 7

jbo5112
jbo5112

Reputation: 833

If you use a valarray, there is a member function sum() for that.

#include <iostream>     // std::cout
#include <valarray>     // std::valarray

int main () {
  std::valarray<int> myvalarray(4);
  myvalarray[0] = 0;
  myvalarray[1] = 10;
  myvalarray[2] = 20;
  myvalarray[3] = 30;
  std::cout << "The sum is " << myvalarray.sum() << '\n';

  return 0;
}

Upvotes: 4

Red Alert
Red Alert

Reputation: 3816

Say you have an int array[N].

You can simply do:

int sum = 0;
for(auto& num : array)
    sum += num;

Upvotes: 14

James Westman
James Westman

Reputation: 2690

The easiest way I can see to do this is to use a loop. The bonus is that you can use it on any integer array without rewriting much code at all. I use Java more often, so I hope there aren't too many syntax errors, but something like this should work:

int addArray(int[] array, int length){
    int sum=0;
    for(int count=0;count<length;count++){
        sum+=array[count];
    }
    return sum;
}

Upvotes: 3

Related Questions