COMP 1633: Intro to CS II
More Arrays
Charlotte Curtis
October 9, 2024
Where we left off
Arrays vs Python lists
C-style arrays
Array indexing
Passing arrays to functions, with and without const
Textbook Chapter 7
1
Today's topics
Partially filled arrays
Multi-dimensional arrays
C-style strings
Textbook Sections 7, 8.1
Assignment 1: Grace period extended to Tuesday at 5 PM due to Thanksgiving
I will answer any emails sent over the weekend on Tuesday
2
But first, a note on % ...
The % operator doesn't behave the same way in C++ as it does in Python
Python C++
print(30 % 27) # 3 cout << 30 % 27 << endl; // 3
print(-30 % 27) # 24 cout << -30 % 27 << endl; // -3
For assignment 1: make sure to test with negative shifts!
Think about how you might handle this case
See the Wikipedia article for more info 3
Summary of array passing
Any size indicated in the [] of the function header is ignored
The function receives a pointer to the first element of the array
sizeof information is lost
We'll talk more about pointers next week
Pass the size of the array as a separate parameter to have flexible functions
Arrays are always passed by reference, no & needed (or allowed)
If you only want to read the array, use const
4
Returning arrays from functions
Short answer: you can't! The following does not compile:
int [] fibonacci(int n) {
int fib[n] = {1, 1};
for (int i = 2; i < n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib;
}
Arrays must be declared outside the function, then passed by reference to be
modified
5
Partially filled arrays
Arrays of fixed-length seem quite limiting, especially coming from Python
high_temps = []
temp = float(input("Enter the next temperature: "))
while temp != -100:
high_temps.append(temp)
temp = float(input("Enter the next temperature: "))
A workaround for C-style arrays is to allocate the maximum size you think you
might need, then keep track of the fill size of the array
This is called a partially filled array
6
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;
}
Which is the fill size of the array?
7
Multi-dimensional arrays
So far we've only looked at one-dimensional arrays
Just like Python's list of lists, we can define 2D arrays in C++:
connect4 = [] const int ROWS = 6;
for i in range(6): const int COLS = 7;
[Link]([' '] * 7) char connect4[ROWS][COLS] = {};
Typically we think of the first dimension as the rows, the second as the columns
The data type of each "row" is (in this example) char[7]
This is different from a char[6] or a char[8] - the size is part of the type
8
Multi-dimensions means multiple loops
To process a 2D array, you'll (almost always) need nested loops
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
cout << connect4[r][c];
}
cout << endl;
}
Be careful with the order of the loops and indexing
connect4[r][c] is the c th element of the r th row
What if we wrote connect4[c][r] instead?
9
Passing multi-dimensional arrays to functions
Multidimensional arrays are passed by reference just like 1D arrays
An initialization function might have the following prototype:
void initialize(char connect4[][COLS], int size);
Like 1D arrays, the first dimension is ignored, however...
The second dimension must be specified, and it must be a constant!
This is because we have an array of char[COLS] elements
Let's see what Python Tutor sees
10
Processing row by row
Depending on the data, you might want to process one row at a time:
bool win = false;
for (int r = 0; r < ROW; r++) {
win = win || check_row(connect4[r]);
}
What should the function prototype for check_row be?
How could you process column by column?
Practice time!
11
C-style strings
C-style strings are arrays of characters
We said that you can't do this:
int primes[] = {2, 3, 5, 7, 11};
cout << primes << endl;
But what about this?
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
cout << vowels << endl;
We've almost got a C-style string here, but not quite
12
The null terminator
Issue: how long should the string be?
We could keep track of a partially filled array size, like this:
char letters[26] = {'a', 'e', 'i', 'o', 'u'};
int fill = 5;
Or, we could use a null terminator:
char letters[26] = {'a', 'e', 'i', 'o', 'u', '\0'};
The null terminator is a sentinel that marks the end of the string
An array of char s is not a C-string until it has a null terminator!
13
C-string shorthand
C++ has a shorthand for initializing C-strings:
char vowels[] = "aeiou";
The null terminator is automatically added
The length is one more than the number of characters
What happens in the following initializations?
char a_ch = 'a';
char a_str[] = "a";
char greeting[32] = "Hello!";
char hello[6] = "Hello!";
14
Some C-string gotchas
Initializing with a string literal is a shorthand - the following are identical:
char message[] = "Hello!";
char message2[] = {'H', 'e', 'l', 'l', 'o', '!', '\0'};
This means that you cannot reassign a C-string, just as you can only use the curly
bracket syntax when initializing an array
You can reassign individual characters:
char message[] = "Hello!";
message[0] = 'G';
15
C-strings plus functions
Since a C-string always has a null terminator, no need to pass the size
Example: a function to calculate the length of a string
int len(const char str[]) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
This is so common that C++ provides a function strlen in the <cstring> library,
along with other useful string manipulation functions
16
Coming up next
Assignment 1 is due Friday
Assignment 2 will be released Friday (lots of 2D arrays!)
Reading week already! No classes next week
I will be available by email and for office hours after the Monday holiday
After the break: More on C-strings, file I/O and command line arguments
17