David
David

Reputation: 23

Add a set of numbers in C++

I know I can store the numbers in an array first like arr[] = {1,2,3}; then call a sum function to add all the numbers like sum(arr);

But what if I want to not use the arr[] and just call sum(1,2,3)?

The values will be determined by the user so it can be sum(1,2), sum(1,2,3,4,5) or sum(1,2,5)

#include <iostream>
#include <math.h>
using namespace std;

int addition (int arr[]) {
    int length = log2(*(&arr + 1) - arr);
    int res = 0;
    for (int n=0; n<length + 1; n++){
        res += arr[n];
    }
    cout << res << endl;
    return 0;
}

int main ()
{
  int array[] = {5, 10, 15,20};
  int array1[] = {10,15,20,25,30};
    
  addition (array);
  addition (array1);

  return 0;
}

Upvotes: 1

Views: 927

Answers (2)

neutrino_logic
neutrino_logic

Reputation: 1299

Another option is to use stringstreams to handle the process. I imagine the variadic template approach @cigien is going to be more efficient, but stringstreams are really useful for many purposes:

#include <sstream>
#include <iostream>

int ssum(std::stringstream &obj) {
    int accumulator = 0;
    std::string buffer;
    while (obj >> buffer) {            //read the stream number by number
        accumulator += stoi(buffer);   //convert to int and add
    }
    return accumulator;
}

int main() {
    int arr[] = {1,2,3,4,5,6,7,8,9,10};
    std::stringstream os;
    for (auto i : arr) {                  //feed the array into the stream obj
        os << i << " ";
    }
    std::cout << ssum(os) << std::endl;
    return 0;
}

[edit remove string conversion step, just pass stringstream object directly]

Upvotes: 0

cigien
cigien

Reputation: 60208

You can write the function like this:

template<typename ...Ts>
auto sum(Ts ...ts)
{
    int arr[]{ ts... };
    addition(arr);
}

which stores the variadic arguments into an array, and the calls addition on that array.

Here's a demo.


However, you can also simply write sum like this:

template<typename ...Ts>
auto sum(Ts ...ts)
{
    return (ts + ...);
}

Here's a demo.


Also, if you use a std::vector instead of an array, you could write addition like this:

void addition (std::vector<int> const & v) {
    std::cout << std::accumulate(v.begin(), v.end(), 0) << "\n";
}

Here's a demo. Note that you can use accumulate with an array as well, but the function has to be a template, like this:

template<int N>
void addition (int const (&arr)[N]) {
    std::cout << std::accumulate(arr, arr + N, 0) << "\n";
}

Here's a demo.

Upvotes: 3

Related Questions