Write and run a C++ program that sums numbers. Your program should:
Prompt the user to enter the number of values to be summed
Create a dynamic array of that size
Repeatedly prompt the user to enter values until the array is full
Print the sum of the values
Delete the dynamic array before terminating the program
Return the sum of the values from the main function
The sum of the values in the array should be calculated using a separate function with this header:
int sumArray(int arr[], int arrSize)
This function must use a loop to calculate the sum of the array
values and should work with an array of any size (note that the
parameter arrSize represents the number of items in the
array).
g++ -Wall -o sum_array sum_array.cppNote the -Wall option here (-W is for warnings, all is for all). This option tells the compiler to be extra picky, and give you warnings about potentially hazardous bits of code. It is a good idea to use this option always.
uname@hostname: ~$ ./test.pyIf you have correctly built an executable sum_array that solves this lab, you will see:
Running test 1... passed Running test 2... passed Running test 3... passed Passed 3 of 3 tests
If you have passed 3 of 3 tests, please ask a TA to take a look at this output and your source code (sum_array.cpp). If you have completed the requirements above, you will receive your 1 mark for this lab.
To get input and print output in C++, use the cin and cout functions. cin is used for input and cout for standard output (to the display). But first you need the appropriate library.
Your program must start with include statements to import the necessary libraries. The only library you will need for this program is the iostream library which contains the cin and cout functions. In addition you will need to open the standard namespace to access these functions. Add these two lines to the file just above the main function:
#include <iostream>
using namespace std;
To get input from the keyboard into a variable named x:
int x = 0;
cin >> x;
To send output to the display:
cout << x;
Note that this will not print the value of x on a new line, but you can use endl to specify a newline. Below I'm printing the value of x on a new line (with some explanatory text) and then printing another line:
cout << endl << "The value of x is: " << x << endl;
To declare an integer array:
int arr[4];
The size must be specified as either an integer or an integer constant:
const int ARR_SIZE = 4;
int arr[ARR_SIZE];
Note that there is no new keyword as arrays in C++ are not objects.
For the lab I've asked you to create a dynamic array. To do this you need to declare a pointer variable, find out how big the array should be and then create the new array in dynamic memory.
int *arr; //pointer variable
int arrSize = 0;
// Get the array size - you need to do this bit (you will want to use cin)!
arr = new int[arrSize]; //creating the array in dynamic array