Programming Principles II A_lecturer.
Mohammed Yaseen
Programming In C++
Course 2: Lecture 2, Multiple Arrays
Prepared By A.Lecturer Mohammed Yaseen
Nineveh University- Faculty of IT- department of software
1
Programming Principles II A_lecturer. Mohammed Yaseen
Lecture 2
Arrays in C++
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
Declare an array
To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it
should store.
Syntax
type arrayName [arraySize];
Example
string cars[4];
We have now declared a variable that holds an array of four strings. To
insert values to it, we can use an array literal - place the values in a
comma-separated list, inside curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
string
cars "Volvo" "BMW", "Ford" "Mazda"
2
Programming Principles II A_lecturer. Mohammed Yaseen
To create an array of three integers, you could write:
Example
int myNum[3] = {10, 20, 30};
int
myNum 10 20 30
Access the Elements of an Array
You access an array element by referring to the index number.
string
cars "Volvo" "BMW", "Ford" "Mazda"
index 0 1 2 3
This statement accesses the value of the first element in cars:
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
Loop Through an Array
You can loop through the array elements with the for loop.
The following example outputs all elements in the cars array:
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}
The following example outputs the index of each element together with its
value:
3
Programming Principles II A_lecturer. Mohammed Yaseen
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}
Omit Array Size
You don't have to specify the size of the array. But if you don't, it will
only be as big as the elements that are inserted into it:
string cars[] = {"Volvo", "BMW", "Ford"};//size of array is always 3
This is completely fine. However, the problem arises if you want extra
space for future elements. Then you have to overwrite the existing values:
string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
If you specify the size, however, the array will reserve the extra space:
string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even
though it's only three elements inside it
Now you can add a fourth and fifth element without overwriting the others:
cars[3] = "Mazda";
cars[4] = "Tesla";
Omit Elements on Declaration
It is also possible to declare an array without specifying the elements on
declaration, and add them later:
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...
4
Programming Principles II A_lecturer. Mohammed Yaseen
Multidimensional arrays
In C++, we can create an array of an array, known as a multidimensional
array.
Syntax
type name[size1][size2]...[sizeN];
Two-Dimensional Arrays
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. To declare a two-dimensional integer array of size x,y, you would
write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid
C++ identifier.
A two-dimensional array can be think as a table, which will have x number
of rows and y number of columns. A 2-dimensional array a, which contains
three rows and four columns can be shown as below −
Example
int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
5
Programming Principles II A_lecturer. Mohammed Yaseen
Accessing Two-Dimensional Array Elements
An array is useful for storing and working with a set of data. Sometimes,
though, it’s necessary to work with multiple sets of data.
For example, in a grade-averaging program a teacher might record all of
one student’s test scores in an array of doubles. If the teacher has 30
students, that means she’ll need 30 arrays of doubles to record the
scores for the entire class. Instead of defining 30 individual arrays,
however, it would be better to define a two-dimensional array.
An element in 2-dimensional array is accessed by using the subscripts,
i.e., row index and column index of the array. For example −
int val = a[3][4];
The above statement will take 4th element from the 3rd row of the array.
Example
#include <iostream> using
namespace std;
int main () {
// an array with 5 rows and 2 columns.
int a[3][4] = { {85, 90, 78, 92}, { 76, 88, 95, 89}, { 90, 92, 85, 87}};
// output each array element's value cout <<
"Student Test Scores:\n";
for (int i = 0; i < 3; i++) { // Loop through
students (rows)
cout << "Student " << i + 1 << ": ";
for (int j = 0; j < 4; j++) { // Loop
through test scores (columns)
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
} cout << endl; 6
}
return 0;
}}
Programming Principles II A_lecturer. Mohammed Yaseen
Initialization 2-D array in C++
One way of initializing a two-dimensional array is
int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
Second way of assigning elements to array
hours[0][0] = 8
hours[0][1] = 5
hours[1][0] = 7
hours[1][1] = 9
hours[2][0] = 6
hours[2][1] = 3
Third way is using loops
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
cin >> hours[i][j] ;
7
Programming Principles II A_lecturer. Mohammed Yaseen
Three-dimensional array in C++
8
Programming Principles II A_lecturer. Mohammed Yaseen
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};
3 4 2 3 13 4 56 3
0 -3 9 11 5 9 3 5
23 12 23 2 5 1 4 9
The first dimension has the value 2. So, the two elements comprising the
first dimension are:
Element 1 = { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }
Element 2 = { {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
The second dimension has the value 3. Notice that each of the elements
of the first dimension has three elements each:
{3, 4, 2, 3}, {0, -3, 9, 11} and {23, 12, 23, 2} for Element 1.
{13, 4, 56, 3}, {5, 9, 3, 5} and {5, 1, 4, 9} for Element 2.
Finally, there are four int numbers inside each of the elements of the
second dimension:
Example
// C++ Program to Store value entered by user in
// three dimensional array and display it.
#include <iostream>
using namespace std;
int main() {
// This array can store up to 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};
9
Programming Principles II A_lecturer. Mohammed Yaseen
// Displaying the values with proper index.
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
cout << "test[" << i << "][" << j << "][" << k << "]
=
" << test[i][j][k] << endl;
}
}
}
return 0;
}
The basic concept of printing elements of a 3d array is similar to that of a
2d array. However, since we are manipulating 3 dimensions, we use a
nested for loop with 3 total loops instead of just 2:
• the outer loop from i == 0 to i == 1 accesses the first dimension of
the array
• the middle loop from j == 0 to j == 2 accesses the second
dimension of the array
• the innermost loop from k == 0 to k == 1 accesses the third
dimension of the array
As we can see, the complexity of the array increases exponentially with
the increase in dimensions.
10
Programming Principles II A_lecturer. Mohammed Yaseen
Dealing with strings in C++
This string is a one-dimensional array of characters that is terminated by
a null character '\0'. Thus a null-terminated string contains the
characters that comprise the string followed by a null.
Example
char greeting[6] = {'H', 'e', 'l', 'l', 'o'};
If you follow the rule of array initialization, then you can write the above
statement as follows −
char greeting[] = "Hello";
The C++ compiler automatically places the '\0' at the end of the string
when it initializes the array.
String Concatenation
The + operator can be used between strings to add them together to
make a new string. This is called concatenation:
Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
11