Lecture 07: Arrays

Jan 31, 2024  │  Last updated Jan 30, 2024 by Charlotte Curtis

HTML Slides html │ PDF Slides PDF

Where we left off

  • while and for loops in C++
  • Event controlled vs counted loops
  • Some useful sentinels

Textbook Sections 3.3-3.4

while (brain_is_working()) {
    keep_programming();
}

Today’s topics

Textbook Chapter 7

Side note: some handy online resources

Python tutor also does C++!

C++ for Python Programmers is an open source interactive book

Caution: we are doing things the hard low level way, so all mention of string and vector etc should not be used for now

Python lists

C-style arrays

Arrays vs Python lists

prices = [1.99, 2.99, 3.99]
print(f"The cost is ${prices[0]}")
double prices[3] = {1.99, 2.99, 3.99};
cout << "The cost is $" 
     << prices[0] << endl;

Array syntax

datatype array_name[array_size];

emoji Uninitialized variables

What is the output from the following code?

  1. 0
  2. Random garbage
  3. -1
  4. inf
  5. Runtime error
void uninitialized() {
    int x;
    cout << x << endl;
}

Array initialization

Inferring size from initialization

Tangent: sizeof

Two meanings of []

Array indexing

Array operations

emoji Take a guess

What do you think will happen here?

  1. Compiler error
  2. Runtime error
  3. Prints 2
  4. Prints NULL
  5. Prints the memory address of primes
int primes[] = {2, 3, 5, 7, 11};
cout << primes << endl;

Invalid array operations

While many array operations are compile errors, others are logic errors:

int primes[] = {2, 3, 5, 7, 11};
int prime_cpy = primes;      // compile time
int prime_cpy[] = primes;    // compile time
cin >> primes;               // compile time

if (primes == prime_cpy) {   // logic!
    cout << "Equal" << endl;
}

So, how do we do any of these things?

Arrays + loops = ❤️

Array elements need to be processed one at a time

Preview: arrays + functions

What’s missing?

If we’re going to copy paste the equality code to the are_equal function, what additional information do we need to pass?

bool are_equal(int a[], int b[]) {
    bool equalness = true;
    // ... ?
    return equalness;
}

We’re going to need the size of the arrays:

bool are_equal(int a[], int b[], int size);

Coming up next

Textbook Chapter 7



Previous: Lecture 06: Loops
Next: Lecture 08: More Arrays