Reputation: 183
I'm using Visual C++ 2010 Express Edition. I declared an integer array capable of holding 50 elements. Depending on how many entries the user gives, each of those entries will be stored as a separate element in the array. I want to add up all these unknown elements and print the answer to the console. Is it possible to do this, and how?
Upvotes: 0
Views: 568
Reputation: 509
Maybe too simple, but what about settin all elements to 0 (zero) at the beginning and then add all items in loop and finally print out the result of addition?
Upvotes: 0
Reputation: 58667
You're looking for std::accumulate()
from header <numeric>
:
std::cout << std::accumulate(std::begin(arr), std::end(arr), 0);
If the user gives less then 50 elements then you need to account for that:
std::cout << std::accumulate(std::begin(arr), arr + element_count, 0);
Upvotes: 6