CMPT 225 Lab 1: Dynamic Arrays


Write and run a C++ program that sums numbers. Your program should:

Implementation Requirements

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).


Solution Recipe

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.


C++ Syntax Notes

Input and Output

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.

Include statements

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;

Using cin and cout

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;

Static Arrays

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. 

Dynamic Arrays

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


Back to the CMPT 225 homepage.