CSCI261
Lecture 18: Multi-Dimensional Arrays
CSCI261 Lecture 18: Multi-Dimensional Arrays ? Review An array is - - PowerPoint PPT Presentation
CSCI261 Lecture 18: Multi-Dimensional Arrays ? Review An array is a simple data structure Like a list or a set Arrays contain references to multiple values of a specific type ( int , char , etc) int myarray[10] // declaration
Lecture 18: Multi-Dimensional Arrays
‘a’ ‘b’ ‘c’
int array_size = 10; char myarray[array_size]; // myarray[10] for (int i = 0; i < array_size; i++) { cout << myarray[i]; }
char v[3] = {‘a’, ‘b’, ‘c’};
‘a’ ‘b’ ‘c’
char v[3] = {‘a’, ‘b’, ‘c’}; cout << v[5]; // index out of range cout << v[3]; // index out of range cout << v[-1]; // index out of range
‘a’ ‘b’ ‘c’ ‘q’ ‘r’ ‘s’ ‘x’ ‘t’ ‘c’
1 2 1 2 1 2
‘a’ ‘b’ ‘c’ ‘q’ ‘r’ ‘s’ ‘x’ ‘t’ ‘c’
1 2 1 2 1 2
‘a’ ‘b’ ‘c’ ‘q’ ‘r’ ‘s’ ‘x’ ‘t’ ‘c’
1 2 1 2 1 2
a b c q r s x t c
a b c q r s x t c
a b c q r s x t c
120 200 300 20 30 40 1 3 5 1.2 3.0 4.2 22.1 3.4 22.0 4.4 3.2 1.7
“Computer, create an array that can hold 4 elements, and inside each element create an array that can hold 2 elements.”
1 1 1 1
char my_array[4][2] = {{‘a’,’b’}, {‘o’,’j’}, {‘o’,’k’}, {‘c’, ‘d’}};
a b
1 1 1
c d
1
“Computer, create a 4 x 2 (rows x columns) table.”
“Fred” “Savage” “Corey” “Haim”
1 1
“Luke” “Perry”
1
string actors[3][2] = {“Fred”, “Savage”, “Corey”, “Haim”, “Luke”, “Perry” };
“Fred” “Savage” “Corey” “Haim”
1 1
“Luke” “Perry”
1
actors[1][1]; // ? actors[2][1]; // ? actors[0][0]; // ? actors[0]; // ? actors[2]; // ?
string actors[3][2] = {“Fred”, “Savage”, “Corey”, “Haim”, “Luke”, “Perry” };
Your brain may prefer the table idea...
“Fred” “Savage” “Corey” “Haim” “Luke” “Perry” “Mr.” “T”
actors[3][1]; // ? actors[2][1]; // ? actors[1]; // ? myarray[row][column];
string mycars[2][2] = {“BMW”, “M5”, “Porsche”, “911”}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { cout << mycars[i][j]; } }
int mydata[5][4]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { mydata[i][j] = i + j; } }
ifstream breakups(“breakupdata.txt”); string mybreakups[4][2]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 2; j++) { breakups >> mybreakups[i][j]; } }
2 3 2 2 1 3 2 1
i broke up with her | she broke up with me
// assuming mybreakups[4][2] is populated for (int i = 0; i < 4; i++) { cout << “During week “ << (i +1); cout << “ i broke up with her “ << mybreakups[i][0] << “ times and she broke up with me “ << mybreakups[i][1] << “ times.”; } }
2 3 2 2 1 3
i broke up with her | she broke up with me