0

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?

4
  • 4
    As an aside, why are you using a fixed size array, not a vector<int>? Commented Feb 9, 2012 at 17:08
  • Is this homework? Or just learning? Unless you need to keep the data for something else (or this is specific to a homework problem), you may not need an array at all. Commented Feb 9, 2012 at 17:10
  • It's both learning and homework/project. Commented Feb 9, 2012 at 17:30
  • Further, I've not yet been introduced to dynamic arrays. Commented Feb 9, 2012 at 17:30

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer if all 50 elements are valid. How about std::accumulate(arr, arr+numberOfEntriesTheUserGives, 0);
0

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?

3 Comments

Thank you Kamil_H for your response. Would appreciate if you could kindly elaborate?
Hmmm. Maybe something like this: int myItems[50]; memset(myItems, 0, 50*sizeof(int)); //here user inserts items to array int result = 0; for(int i = 0; i < 50;i++) result+=myItems[i]; cout << result;`
Kamil_H, if you could supply me with your aforementioned code, it would really be of great use to me! Thanks a lot Kamil_H.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.