Chapter 5 - Arrays
Chapter 5 - Arrays
Chapter 5: Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
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:
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"};
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
cars[0] = "Opel";
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
You can loop through the array elements with the for loop.
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:
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}
This is completely fine. However, the problem arise if you want extra space for future elements.
Then you have to overwrite the existing values:
If you specify the size however, the array will reserve the extra space:
Now you can add a ourth and fifth element without overwriting the others:
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Example
cars[3] = "Mazda";
cars[4] = "Tesla";
It is also possible to declare an array without specifying the elements on declaration, and add
them later:
Example
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
Result: 20
Why did the result show 20 instead of 5, when the array contains 5 elements?
You learned from the Data Types chapter that an int type is usually 4 bytes, so from the
example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
To find out how many elements an array has, you have to divide the size of the array by the size
of the data type it contains:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
Result:
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Multi-Dimensional Arrays
A multi-dimensional array is an array of arrays.
To declare a multi-dimensional array, define the variable type, specify the name of the array
followed by square brackets which specify how many elements the main array has, followed by
another set of square brackets which indicates how many elements the sub-arrays have:
string letters[2][4];
As with ordinary arrays, you can insert values with an array literal - a comma-separated list
inside curly braces. In a multi-dimensional array, each element in an array literal is another
array literal.
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Each set of square brackets in an array declaration adds another dimension to an array. An
array like the one above is said to have two dimensions.
Arrays can have any number of dimensions. The more dimensions an array has, the more
complex the code becomes. The following array has three dimensions:
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
This statement accesses the value of the element in the first row (0) and third column (2) of
the letters array.
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Remember that: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Example
// We put "1" to indicate there is a ship.
bool ships[4][4] = {
{ 0, 1, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
};
// Keep track of how many hits the player has and how many turns they have
played in these variables
int hits = 0;
int numberOfTurns = 0;
// Allow the player to keep going until they have hit all four ships
while (hits < 4) {
int row, column;
// Tell the player that they have hit a ship and how many ships are
left
cout << "Hit! " << (4-hits) << " left.\n\n";
} else {
// Tell the player that they missed
cout << "Miss\n\n";
}
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Problem 1: Write a program to input a sequence of n real numbers a[0], a[1],..., a[n-1], sort the
array of numbers in order from largest to smallest. Print the array of numbers after sorting.
Input: Please input n: 5 Output: 54321
15243
Problem 2: Write a program to sort an array in ascending order after removing duplicates.
Input: Please input n: 7 Output: 1234
1333422
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Input integer: 2
The value of 2 appeared 3 time(s). Locate at [0,2], [1,0], [1,1]
Problem 6: Write a program to convert the position from row to column of a square
(transposition matrix) of 4 rows and 4 columns. Then write for a general matrix of order m*n.
Input: Output:
1 2 3 4 1 2 9 1
2 5 5 8 2 5 4 5
9 4 2 0 3 5 2 8
1 5 8 6 4 8 0 6
Problem 7: Write a program to input an array of natural numbers. Let's output to the screen:
- Line 1: includes odd numbers, how many odd numbers in total.
- Line 2: includes even numbers, how many even numbers in total.
- Line 3: contains prime numbers.
- Line 4: contains numbers that are not prime.
Input: Please input n: 8
1 3 4 5 7 9 11 12
Output:
Odd numbers: 1 3 5 7 9 11
Even numbers: 4 12
Prime numbers: 3 5 7 11
Non-prime numbers: 1 4 9 12
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Problem 8: Write a program to calculate the sum of squares of negative numbers in an array of
integers.
Input: Please input n: 5 Output: The sum of squares of negative numbers: 29
Problem 10: Write a program to input two matrices A and B of level m, n. Print two matrices to
the screen. The sum of two matrices A and B is matrix C calculated by the formula:
𝑐𝑖𝑗 = 𝑎𝑖𝑗 + 𝑏𝑖𝑗 (𝑖 = 0,1,2, … , 𝑚 − 1, 𝑗 = 0,1,2, … , 𝑛 − 1)
Calculate the sum matrix C and print the result on the screen.
Problem 11: Write a program to input two matrices A with level, k and B with level k, n. Print
two matrices to the screen. The product of two matrices A and B is matrix C calculated by the
formula:
𝑐𝑖𝑗 = 𝑎𝑖1 ∗ 𝑏1𝑗 + 𝑎𝑖2 ∗ 𝑏2𝑗 + 𝑎𝑖3 ∗ 𝑏3𝑗 + ⋯ + 𝑎𝑖𝑘 ∗ 𝑏𝑘𝑗
(𝑖 = 0,1,2, … , 𝑚 − 1, 𝑗 = 0,1,2, … , 𝑛 − 1)
Calculate the product matrix C and print the result on the screen.
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Problem 12: Write a program to merge two ordered arrays into one ordered array.
Note: Cannot be merged and then sorted. When merging, it is necessary to take
advantage of the sorted property of two subsequences.
Input: Please input number of array A: 5
13568
Please input number of array B: 3
247
Output: 1 2 3 4 5 6 7 8
Lecturer: Quang-Thai Ho