Lecture 08: More Arrays

Feb 5, 2024  β”‚  Last updated Feb 2, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

  • Arrays vs Python lists
  • C-style arrays
  • Array indexing
  • Arrays in functions preview

Textbook Chapter 7

int cup_sizes[] = {8, 12, 16, 20};
for (int i = 0; i < 4; i++) {
    cout << cup_sizes[i] << " oz" << endl;
} 

Today’s topics

Textbook Chapter 7, 8.1

Passing arrays to functions

Better array passing

Arrays are always passed by reference

Side tangent: const in function headers

Summary of array passing

Returning arrays from functions

What about the following?

double[] get_temps() {
    const int FORECAST_DAYS = 7;
    double high_temps[FORECAST_DAYS] = {};
    for (int i = 0; i < FORECAST_DAYS; i++) {
        cout << "Enter high temp for day " 
             << i + 1 << ": ";
        cin >> high_temps[i];
    }
    return high_temps;
}

emoji Array check-in 1/2

What is the output from the following code?

  1. 0
  2. Random garbage
  3. The address of the array
  4. 4
  5. Runtime error
int arr[5] = {};
cout << arr[4] << endl;

emoji Array check-in 2/2

What is the output from the following code?

  1. 0
  2. Random garbage
  3. The address of the array
  4. 4
  5. Runtime error
int arr[5] = {};
cout << arr << endl;

Partially filled arrays

Partially filled array example

const int MAX_SIZE = 30;
double high_temps[MAX_SIZE] = {};
int num_temps = 0;
double temp = 0;
cout << "Enter the next temperature: ";
cin >> temp;
while (temp != -100 && num_temps < MAX_SIZE) {
    high_temps[num_temps] = temp;
    num_temps++;
    cout << "Enter the next temperature: ";
    cin >> temp;
}

Searching arrays

Sorting arrays

Multidimensional arrays

Multidimensional data types

Given this declaration:

const int ROWS = 3;
const int COLS = 3;
char board[ROWS][COLS] = {};

What is the type of each of the following?:

  1. board
  2. board[0]
  3. board[0][0]

Multidimensional array initialization

Multidimensional array passing

This is probably a good place to use a global constant

Processing row by row

Depending on the data, you might want to process one row at a time:

const int MAX_RECORDS = 100;
const int NUM_FIELDS = 5;
int records[MAX_RECORDS][NUM_FIELDS] = {};

for (int row = 0; row < MAX_RECORDS; row++) {
    read_record(records[row], NUM_FIELDS);
}

C-string Preview

Coming up next

Textbook Chapter 8.1, 8.2



Previous: Lecture 07: Arrays
Next: Lecture 09: C-Strings