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?
-
4As an aside, why are you using a fixed size array, not a vector<int>?Pete– Pete2012-02-09 17:08:19 +00:00Commented 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.crashmstr– crashmstr2012-02-09 17:10:56 +00:00Commented Feb 9, 2012 at 17:10
-
It's both learning and homework/project.Ram Sidharth– Ram Sidharth2012-02-09 17:30:01 +00:00Commented Feb 9, 2012 at 17:30
-
Further, I've not yet been introduced to dynamic arrays.Ram Sidharth– Ram Sidharth2012-02-09 17:30:48 +00:00Commented Feb 9, 2012 at 17:30
Add a comment
|
2 Answers
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);
1 Comment
Robᵩ
Good answer if all 50 elements are valid. How about
std::accumulate(arr, arr+numberOfEntriesTheUserGives, 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
Ram Sidharth
Thank you Kamil_H for your response. Would appreciate if you could kindly elaborate?
Kamil_H
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;`Ram Sidharth
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.