EECS183:Discussion06
Section023:Hiromichi Cho
1-DimentionalArrays
• Anarrayisacollectionofitemsofthesame datatypestored
consecutivelyinmemoryunderonename
• Arrayelementscanbeaccessedbyindexing,justlikestrings
• E.g.arr[2] isaccessingthesecondelementinanarray
• Notearrayarealso0indexede.g.firstelementisatindex0
arr
arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
1
25
11
-12
107
1D ArrayDeclarationandInitialization
• int arr[5]; //compilerwillinsert0s {0, 0, 0, 0, 0}
• int arr[] = {1, 2, 3, 4, 5};
• int arr[5] = {1, 2, 3, 4, 5};
• int arr[8] = {1, 2, 3, 4, 5}; //compilerwillinsert0safter5th element
• int arr[5] {1, 2, 3, 4, 5}; //noneedofequalsign
• string arr[3]; //compilerwillinsertemptystrings{“”, “”, “”}
• int arr[]; //invalidbecausenosizeorcontentisspecified
• Dependingonthecompiler,the0soremptystringsmaynotbeinserted
PassingArraystoFunctions
• Arraysarealwayspassedbyreference
• void foo(int arr[], int size);
• Youcannotreturnanarrayfromanarray
• However,thisisfinebecausearraysarepassedbyreference,andany
modificationmadetoanarraywithinafunctionwillpersist
IteratingThroughArrays
• What’s wrong with the following code snippet?
const int MAX_SIZE = 3;
int arr[MAX_SIZE] = {1, 2, 3};
for (int i = 0; i <= MAX_SIZE; ++i) {
cout << arr[i] << “ “;
}
IteratingThroughArrays
• What’s wrong with the following code snippet?
const int MAX_SIZE = 3;
int arr[MAX_SIZE] = {1, 2, 3};
for (int i = 0; i <= MAX_SIZE; ++i) {
cout << arr[i] << “ “;
}
// index 3 will be accessed, which is out of bounds
IteratingThroughArrays
• What’s wrong with the following code snippet?
const int MAX_SIZE = 3;
int arr[MAX_SIZE] = {1, 2, 3};
for (int i = 0; i < MAX_SIZE; ++i) {
cout << arr[i] << “ “;
}
// Correct version
Iterating Through Arrays (continued)
• Becarefulnottogoofftheendofanarray
• Since arrays are 0 indexed, you will have to start with index = 0
• Therefore, index <= size will always access one past the array,
which contains an undefined value (memory junk)
• Make sure to not go out of bounds (index < 0 and index >= size)
Practice using 1D Arrays
1. Writeafunctionthattakesinanarrayoftypeinteger,andprintsthe
sumoftheelements
2. Writeafunctionthattakesinanarrayoftypeinteger,andreplaces
anynegativenumberwithitsabsolutevalue
3. Writeafunctionthattakesinanarrayoftypeboolean,andreturns
whetherthearrayismoretrueormostlyfalse
4. Writeafunctionthattakesinanarrayoftypestring,andprintsout
everystringthatstartswiththeletter‘p’or‘h’
5. Writeafunctionthattakesinanarrayoftypedoubleandround
everyelementtoitscloserinteger
2-Dimensional Arrays
• You can visualize 2D arrays as a matrix or game board
• Elements are accessed by arr[i][j] or arr[row][col]
• col is used very often as a shorthand for column
1
2
3
a[0][0]
a[0][1]
a[0][2]
4
5
6
a[1][0]
a[1][1]
a[1][2]
7
8
9
a[2][0]
a[2][0]
a[2][2]
Initializing 2D Arrays
• int board[HEIGHT][WIDTH] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} }
• You can also use a nested for loop to initialize all elements of a 2D
array
Initializing 2D Arrays (continued)
• Which of these is/are invalid?
• int arr[10][2];
• int arr[][3] = {{1, 2, 3}, {4, 5, 6}};
• int arr[4][];
Initializing 2D Arrays (continued)
• Which of these is/are invalid?
• int arr[10][2];
• int arr[][3] = {{1, 2, 3}, {4, 5, 6}};
• int arr[4][]; // compile error
• 2D arrays must have a column size at compile time (2nd parameter)
• The row size is optional (1st parameter)
Iterating Through 2D Arrays
• E.g. Printing all elements of 2D array
const int MAX_SIZE= 3;
int arr[MAX_SIZE][MAX_SIZE] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for (int i = 0; i < MAX_SIZE; ++i) {
for (int j = 0; j < MAX_SIZE; ++j) {
cout << arr[i][j] << “ “;
}
cout << endl;
}
Output
--------------------123
456
789
Iterating Through 2D Arrays (reverse all)
• What if we wanted to print all elements in reverse order?
const int MAX_SIZE= 3;
int arr[MAX_SIZE][MAX_SIZE] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for (int i = MAX_SIZE - 1; i >= 0; --i) {
for (int j = MAX_SIZE - 1; j >= 0; --j) {
cout << arr[i][j] << “ “;
}
cout << endl;
}
Output
--------------------987
654
321
Iterating Through 2D Arrays (reverse row)
• What if we want to only reverse each row?
const int MAX_SIZE= 3;
int arr[MAX_SIZE][MAX_SIZE] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for (int i = 0; i < MAX_SIZE; ++i) {
for (int j = MAX_SIZE - 1; j >= 0; --j) {
cout << arr[i][j] << “ “;
}
cout << endl;
}
Output
--------------------321
654
987
Iterating Through 2D Arrays (reverse col)
• Challenge: What if we want to only reverse each column?
• Hint: think what this is equivalent in terms reversing the order of rows.
const int MAX_SIZE= 3;
int arr[MAX_SIZE][MAX_SIZE] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Iterating Through 2D Arrays (reverse col)
• What if we want to only reverse each column?
const int MAX_SIZE= 3;
int arr[MAX_SIZE][MAX_SIZE] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for (int i = MAX_SIZE - 1; i >= 0; ++i) {
for (int j = 0; j < MAX_SIZE; ++j) {
cout << arr[i][j] << “ “;
}
cout << endl;
}
Output
--------------------789
456
123
Initializing all to 0s
• 1D Array
• int arr[5] = {0};
• 2D Array
• int arr[5][5] = {0};
• Both of the above initializes every element in the array to 0
• Note, this is only the case with 0. If any other number is inside the
curly braces, only element 1 will be that number and the rest will be
0s.
Project 3: Tips
• ReadtheRMEcarefully
• Notallfunctionsrequiredanestedforloop
• Hint:Givenarow,youonlyneedtoiteratethroughthecolumns
• Ifyouaretofiguresomethingoutaboutarow,youmustiterate
throughthecolumnscorrespondingtothatrow(viseversaforcol)
• Becarefulnottogooutofboundsonarrays
• Youcanhavetwoseparateforloopsinafunction
• Functionscanuseotherfunctionse.g.board_has_no_threes()
• Makeuseoffunctionsinutility.cpp whereapplicable
row_has_no_threes_of_color()
• What’swrong
//RME:Printoutallthreeconsecutivetilesofagivenrow(i)
//Assumeyouhavetousej+1andj+2
for (int j = 0; j < SIZE; ++j) {
cout << board[i][j];
cout << board[i][j + 1];
cout << board[i][j + 2];
}
row_has_no_threes_of_color()
• What’swrong
//RME:Printoutallthreeconsecutivetilesofagivenrow(i)
for (int j = 0; j < SIZE; ++j) {
cout << board[i][j];
cout << board[i][j + 1];
cout << board[i][j + 2];
}
// This loop will go out of bounds
row_has_no_threes_of_color()
• What’swrong
//RME:Printoutallthreeconsecutivetilesofagivenrow(i)
for (int j = 0; j < SIZE; ++j) {
cout << board[i][j];
cout << board[i][j + 1];
cout << board[i][j + 2];
}
// Hint for fix: You do not need to iterate through all
//
the columns
© Copyright 2025 Paperzz