CMPT 225 - C++ Arrays

 

In this activity you are going to create a program to sum the contents of a dynamically allocated array. Most of this document is a discussion on creating arrays and using standard input and output functions in C++.

 

Description

Write and execute a C++ program that sums numbers entered by the user, your program should achieve this in the following steps:

Prompt the user to enter the number of values to be summed

Create an array in dynamic memory of that size

Repeatedly prompt the user to enter values until the array is full

Find the sum of the values in the array by calling the sumArray function (also written by you)

Print the sum of the values

Delete the dynamic array before terminating the program

 

C++ Arrays Discussion

C++ allows programmers to create statically or dynamically allocated arrays.  A statically allocated array variable is a constant pointer that points to a fixed size array in automatic storage (i.e. the call stack), the values of the elements of a static array can be changed but a new array cannot be assigned to a static array variable.  Note that it is also possible to create static arrays in static storage. In contrast, pointer variables can be used to point to arrays allocated in dynamic memory (known as the heap or free store) that can be assigned different addresses (of other arrays in dynamic memory).  Another way of putting this is that statically allocated arrays cannot change size but dynamically allocated arrays can; while this is a lot simpler explanation it is not completely correct!

 

Statically Allocated Arrays

To declare a statically allocated array, which you do not have to do for this activity, just declare the type of the array elements and indicate that it is an array by putting []s containing the size after the array variable's name. The size of the array must be specified as either an integer or an integer constant. Assume that we want to record daily rainfall.

 

const int DAYS = 365;
float rainfall[DAYS];

 

Since the size of a statically allocated array must be an integer literal or constant it is specified by the programmer and is determined at compile-time. This is acceptable in some circumstances (like the example shown above) but often does not give a program enough flexibility. Consider storing student data in an array. The number of students taking a course can vary considerably from semester to semester and the only way to ensure that an array is large enough is to intentionally create an array that is larger than necessary. Clearly, in this situation, a better solution would be to allow the user of the program to specify the size of the array; that is determine the size of the array while the program is running (i.e. at run-time).

 

Dynamically Allocated Arrays

To allocate space for an array in dynamic memory:

Declare a pointer variable of the appropriate type

Use new (not malloc or calloc) to allocate the appropriate amount of space and assign the result to the pointer

 

int* scores = NULL; // pointer to an int

scores = new int[123]; // allocates space for 123 integers

 

Unlike statically allocated arrays the size specified in the call to new can be a variable, here is another example:

 

int* scores = NULL; // pointer to an int

int nScores = 0;

std::cout << "Enter the number of scores: ";

std::cin >> nScores;

scores = new int[nScores]; // allocates space for 123 integers

 

Once you've created a dynamically allocated array you can use it just like a regular array by accessing individual elements with an index.  For example these lines of code would allow the user to set the elements of the scores array.

 

int val = 0;

for(int i = 0; i < nScores; i++){

std::cout << "Enter a number: ";

std::cin >> val;

scores[i] = val;
}

 

Memory allocated by new has to be later de-allocated with delete. The call to delete should be made when the memory is no longer required. To delete an array that has been allocated in dynamic memory:

 

delete[] scores;

 

Getting Input and Printing Output

To get standard input and print standard output in C++, use the cin and cout functions.  cin is used for input from the keyboard and cout for output to the display.  But first you need the appropriate library.

 

Include statements

Your program must start with include statements to import any 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 either need to qualify the names of the cin and cout functions with their namespace (they are part of the std namespace) or write a using statement to use their unqualified names. 

 

#include <iostream>
using namespace std;

 

Examples of Using cin and cout

In this activity the first two things you have to do are ask the user how large the array is going to be (how many numbers they want to sum) and then get the user's input from the keyboard.  This involves cout (asking the question) and cin (getting the input).

 

int size = 0; //variable to store the array size in
cout << "How many numbers do you want to sum? "; //output to console

 

And then to store the keyboard input in the variable size you just do this.

 

cin >> size;

 

You may want to print new lines to separate lines of output which be done either by printing the endl constant or by printing the newline character ('\n'). Here is the sort of thing you might do to implement the last part of the activity, with one newline printed before the output and one after the output.

 

cout << endl << "The sum of the array is " << sumArray(numbers, size) << endl;

 

Note that this one line contains a series of output operations.  The << is the output operator (and >> is the input operator).  Both << and >> are binary operators: that is, operators that take two operands like + in 3 + 5. 

 

Write the Program

Now go ahead and write the program, if you are having trouble you can use the sample shown below as a starting point.

 

// These two lines allow the use of cin and cout

#include <iostream>

using namespace std;

 

// Function Prototype

double sumArray(double arr[], int arrSize);

 

// Main function that is called when the program is executed

int main(){

int size = 0; //array size

double val = 0;

double* numbers;

cout << "How many numbers do you want to add up? "; //output to console

cin >> size;

//create dynamic array here

// Enter values into the array

for(int i = 0; i < size; i++){

}

// Sum the array contents and print the result

cout << endl << "The sum of the array is " << sumArray(numbers, size) << endl;

return 0;

}

 

 

// Define sumArray here - pretty much all you have left to do!

double sumArray(double arr[], int arrSize){

}

 

Note what I've referred to in comments as a function prototype (a type of forward declaration).  This introduces the name of the sumArray function so that the compiler will know its parameters and return type when it encounters it in the main function.  This allows us to define the main function first and put all the subsidiary function definitions underneath.

 

 

CMPT 225 Home

 

John Edgar (johnwill@sfu.ca)