Arrays & Vectors Week 5
The simplest form of the multidimensional array is the two-dimensional array. A two- dimensional array is, in essence, a list of one-dimensional arrays. A two-dimensional array can be think as a table, which will have m number of rows and n number of columns. Multiple-Dimensional Arrays
Multiple dimension – a[ i ][ j ] – Tables with rows and columns – Specify row, then column – “Array of arrays” a[0] is an array of 4 elements a[0][0] is the first element of that array Row 0 Row 1 Row 2 Column 0Column 1Column 2Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript
Multiple-Dimensional Arrays To initialize – Default of 0 – Initializers grouped by row in braces int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Row 0Row 1
Multiple-Dimensional Arrays Next: Create a program which will calculate average points of students from exams – After, program to keep track of students grades – Multiple-dimensional array (table) – Rows are students – Columns are grades Quiz1 Quiz2 Student0 Student1
Multiple-Dimensional Arrays Next: Create a program which will check user login and password. – You will store string values of logins and passwords – Multiple-dimensional array (table) – Rows are users – Columns 0 is login and column 1 is password ilyas qwerty user2 asdf login password
VECTORS Array cannot change the length Vector the same purpose as arrays except can change length while the program is running Like an array, a vector has a base type, and like an array, a vector stores a collection of values of its base type. Vectors are sequence containers representing arrays that can change in size.
Vectors Library: #include Declaration: vector name; Example: vector v; vector v(10);
Vectors To add an element to a vector for the first time, you normally use the member function push_back. Example: vector sample; Sample[0]=1; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2);
Vectors The number of elements in a vector is called the size of the vector. The member function size can be used to determine how many elements are in a vector. Example: for (int i = 0; i < sample.size( ); i++) cout << sample[i] << endl;
// Create vector > vec(4, vector (4)); // Write vec[2][3] = 10; // Read int a = vec[2][3]; cout<<vec<<[0][1]<<endl; Vectors