Welcome to Lesson 20!


Learning Objectives
By the end of today's class, you should know...
  • What is an array?
  • How do you declare an array?
  • How do you assign an array some values (2 ways):
    • using static initialization?
    • using non-static initialization?
  • How do you pass an array to a function as a parameter?
    • Will it be passed by reference or by value?
  • How do you use a for loop to iterate through the elements of an array?
  • What happens when you go out of bounds of an array?

Announcements

  • Final Exam: Tuesday from 4:00pm to 6:00pm in this classroom!
    • No makeups - the exam must be taken on the day and at the time given
    • How to study: Old Quizzes, Midterms, Programs (In and Out of Class)
    • Final will be cumulative from first day of class through today's lesson
    • Will select one function from your fun with functions worksheet
    • Will select one function from your fun with arrays worksheet (tonight's homework)
    • Expect a program from a homework assignment I assigned after Midterm 2
    • Start studying now!
  • Return Quiz 7
  • Quiz 8 on Thursday
    • Functions
    • File I/O
    • Arrays
  • Last lab due Friday at midnight
    • File I/O and arrays
  • Last chance to submit late work is Thursday's in person office hours!
    • Come early or I may not be able to take your work
    • Office hours will be packed!

Review Activity:

1. Given the following lines of code, write a loop to read in the file word by word:

string word;

int count = 0;

fin.open("inputFile.txt");

while(                        ) {    

    count++;

    cout << "Word " << count << ": " << word << endl;

}

2. Given the following lines of code, write a loop to read in the file line by line:


string line;

int count = 0;

fin.open("inputFile.txt");

while(                        ) {    

    count++;

    cout << "Line " << count << ": " << line << endl;

}

3. Write the following function which takes in a reference parameter:



void notString(string& str);
//Given a string, return a new string where "not " has been added to the front.
//However, if the string already begins with "not", return the string unchanged.
//notString("candy") → "not candy"
//notString("x") → "not x"
//notString("not bad") → "not bad"


int main() {

    string str = "candy";

    notString(str);

    cout << "Should print /"not candy/": " << str << endl;

}


//write notString here


Introduction to Arrays


Using Lists for Data

  • Often times we need to process a group of the same types of data
  • For instance:
    • Bank account transactions
    • Salaries for employees in a company
    • Test scores for a group of students
    • Temperature data over some period of time
  • Consider how we might process the following student test scores:
    90
    95
    87
    89
    98
    96
    85
    79
    95
    100
  • With this data, we can calculate statistics like:
    • Highest score
    • Lowest score
    • Average (mean) score
    • Difference (deviation) of each score from the average
  • We can write a program to read this data and make the calculations
  • However, to calculate the difference from the mean, we need to first find the mean
  • Thus, we have to process all the data twice: one to find the mean and another to calculate the difference of each score from the mean

Storing Lists of Data

  • If we know there are 10 inputs, we can use 10 separate variables.
int score1 = 90;
int score2 = 95;
int score3 = 87;
int score4 = 89;
int score5 = 98;
int score6 = 96;
int score7 = 85;
int score8 = 79;
int score9 = 95;
int score10 = 100;
  • However, declaring all of these variables and assigning them values is a very tedious process.
  • Now, imagine there were 100 test scores... Or, an unknown number of test scores...
  • We need another system!
  • Fortunately, C++ has techniques we can use to organize lists of data

Defining Arrays

  • An array is a collection of data items all of the same type
  • You declare an array like this:
    dataType variableName[size];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • size: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    int scores[10]
  • Arrays like this can never change size and the array size must be set when the program is compiled
  • When defining an array, you must guess the maximum number of elements you need to store:
    const int MAX_SCORES = 10;
    int scores[MAX_SCORES];
    
  • The programmer must keep track of the capacity
  • We use a constant to hold the capacity of the array as shown above
  • This allows us to know the size anywhere in our code
  • If we need to change the size, we change only a single constant and recompile
  • When a program executes this statement, it creates 10 contiguous slots in memory like this:
    scores = 
     
     
     
     
     
     
     
     
     
     
  • Each of the memory slots can hold one data value

Initializing Array Items

  • We specify which slot of an array to access with the [] operator:
    scores[4] = 98;
  • The indexes of arrays are numbered starting at 0
  • We can assign a value to an array element any time after it is declared:
    const int MAX_SCORES = 5;
    int scores[MAX_SCORES];
    scores[0] = 90;
    scores[1] = 95;
    scores[2] = 87;
    scores[3] = 89;
    scores[4] = 98;
    
  • We can also initialize array elements in the declaration statement:
    • Called static initialization
    • We use a comma-separated list inside curly-braces
  • For example:
    int scores[] = { 90, 95, 87, 89, 98 };
    
  • This produces the same array as in the previous example
  • The compiler computes the size automatically by counting the items in the list
  • If we want a larger array with only the first few elements initialized, we can use:
    int scores[MAX_SCORES] = {90, 95, 87};
    
  • Note that if we do not assign a value to an array element, its value is not known.

Accessing Array Items

  • To access the slots in an array, we must specify which slot to use with the [] operator
  • For instance:
    scores[4] = 98;
  • The number inside the brackets is called an index or subscript
  • In C++, the slots of an array are numbered starting at 0, as shown below:
    scores = 
     
     
     
     
    98
     
     
     
     
     
    [0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]
  • Thus, assignment to the slot with an index of 4 is put into the fifth slot

Using Slots

  • We declared our example array with a data type of int:
    int scores[10];
  • Because scores is an array containing int values, we can use a slot, such as scores[4], just like any variable of type int:
    scores[4]++;
    cout << scores[4] << endl;
    
  • This includes using a slot as an argument to a function with a parameter of the same type:
    void myFun(int singleScore);
    ...
    myFun(scores[4]);
    

Using Arrays to Collect Data Items

  • Note that the index of an array can be any integer value
  • Thus, we can use an integer variable for the index
  • We can use an integer variable with a loop to read data into the array
  • Also, we can display the contents of an array using a loop
  • The following program shows an example of collecting and displaying data items


Example Program Using Arrays to Collect and Display Data Items

#include <iostream>
using namespace std;

int main() {
    const int MAX_SCORES = 10;
    int scores[MAX_SCORES];

    cout << "Enter " << MAX_SCORES << " scores:\n";
    for (int i = 0; i < MAX_SCORES; i++) {
        cin >> scores[i];
    }

    cout << "You entered:\n";
    for (int i = 0; i < MAX_SCORES; i++) {
        cout << scores[i] << endl;
    }

    return 0;
}

Activity 20.1: My First Array (10pts)

  • Copy the following program into a text editor, save it as myarrays.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  • Inside main(), add a statement to define an array named names that is suitable for holding a list of three (3) names.
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • Assign values to each of the array elements like:
    names[0] = "Abel Ableson";
    
  • Add a for-loop to display all three array values.
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • When you are finished, upload your source code to Catalyst.

Arrays as Function Parameters

  • When writing a function with an array parameter, we place an empty [] after the parameter name:
    void print(int values[], int size);
    
  • We pass the size of the array to the function so the function knows the size of the array
    • There is no size() member function for an array
  • When we call the function, we do NOT include the []:
    print(data, size); // function call
    
  • Instead, we pass in the name of the array.
  • Unlike other parameters, you can pass the array into the function and then alter the array inside of the function without needing to return a new array.
  • For example, what do you think will be the result of running the following program?
#include <iostream>
using namespace std;
void fillArray(int data[], int size) {
    for (int i = 0; i < size; i++) {
       data[i] = i;
    }
} 
        int main() {
            const int SIZE = 5;
            int data[SIZE];
            fillArray(data, SIZE);
            for (int i = 0; i < SIZE; i++) {
                cout << data[i] << endl;
            }
        }
  • Note the use of size parameter
  • The programmer must keep track of the size when working with arrays
  • Note that arrays cannot be function return types
  • Returning an array with a return statement is not necessary

Using the const Modifier

  • Normally, a function can change the values of array elements
  • We can prevent the modification using the const modifier:
    void print(const int values[], int size);
    
  • The compiler will issue an error message if you try to change the value of an array element
  • If a function with a constant array parameter calls another function using the const array parameter as an argument, the called function must use a const array parameter as well
  • Otherwise, the compiler will issue an error
  • The following program shows arrays used with functions


Activity 20.2: Exploring Arrays (10 pts)
  • In this exercise we explore declaring, allocating and assigning values to arrays containing lists of data.
  • Create a source code file called myarrays.cpp:
  • Add the following function to the code:
    void print(const int values[], int size) {
        for (int i = 0; i < size; i++) {
            cout << values[i] << " ";
        }
        cout << endl;
    }
    
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • Declare and initialize an array for a list of 10 integer scores after the current arrays using the following code:
    const int NUM_SCORES = 10;
    int scores[NUM_SCORES] = {90, 91, 92, 93, 94, 95, 96, 97, 98, 99};
    
  • After declaring and initializing the array, call the print() function using the code:
    cout << "Integer scores:\n";
    print(scores, NUM_SCORES);
  • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like:
    Integer scores:
    90 91 92 93 94 95 96 97 98 99
    
  • Declare and initialize an array of double values holding the the temperature values 25.7, 30.3, and 40.9
  • Write another print() function with two parameters: one for the array of double values and one for the size of the array.
  • After declaring and initializing the array, call the print() function.
  • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like:
    Integer scores:
    90 91 92 93 94 95 96 97 98 99
    Double temperatures:
    25.7 30.3 40.9
    
  • Save your program source code and submit it to Catalyst when you are finished.


Working with Arrays

What Happens When You Go Out of Bounds

  • Trying to access an element (slot) that does not exist in the array is a logic error:
    int main() {
    int nums[] = {2,5,6,2,3};
    cout << nums[12];

    return 0;
    }
  • However, the standard C++ implementation of an array does not always generate an error message
  • When we make an error like this, C++ may silently read or overwrite another memory location
  • In a small program, we may not notice this error
  • However, in a larger program we would get strange errors and the occasional spectacular crash


Wrap Up
  • With your partner, answer the questions from today's learning objectives

Upcoming Assignments
  • Assignment 20 due Thursday at 3:20pm on Catalyst
  • Lab 9 due Friday at midnight