our professor said that make it in 1d array :) :) |
The "simplest" solution would be the vector:
std::vector<int> array(size);
Sadly, courses seem to call it "advanced".
Explicit dynamic allocation is next:
int *array = new int [size];
It expects appropriate deallocation. Again, there is a "simple" solution: std::unique_ptr<int[]> array( new int [size] );[/code]
Which again seems too "advanced".
What is left is
sensible default.
1 2 3 4 5 6 7
|
const std::size_t Limit = 256;
int array[ Limit ];
...
std::cin >> size;
if ( Limit < size ) {
// Report the error. Exit or shrink size to Limit
}
|
Now we have a "simple static 1D array". Its size is fixed.
However, the program cannot have more than Limit elements in the array.
Furthermore, if typical program run has size much less than Limit, then much more memory is reserved than required.
It is up to you to decide what is sensible; 256 is way more than 5.
We already know that the sum can be computed without an array. Courses, however, do not focus on simple, safe, and clever, but on practice, practice, and practice (
of something). Therefore, a laborious student would not write one, but two loop; first loop to read values into array and second loop to calculate sum from array. It demonstrates the principle of dividing the task into simple, one-purpose subtasks.