Computer Programming
Lab Objectives
The objectives of this lab are to demonstrate.
1. Arrays & practice.
2. Access the Elements of an Array & practice.
3. Change an Array Element & practice.
4. Loop Through an Array & practice.
5. The foreach Loop & practice.
6. Omit Array Size & practice.
7. Omit Elements on Declaration & practice.
8. Get the Size of an Array & practice.
9. Loop Through an Array with sizeof() & practice.
10. Multi-Dimensional Arrays & practice.
11. Access the Elements of a Multi-Dimensional Array & practice.
12. Change Elements in a Multi-Dimensional Array & practice.
13. Loop Through a Multi-Dimensional Array & practice.
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"};
To create an array of three integers, you could write:
int myNum[3] = {10, 20, 30};
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
return 0;
}
Access the Elements of an Array
You access an array element by referring to the index number inside square brackets [].
This statement accesses the value of the first element in cars:
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.
Change an Array Element
To change the value of a specific element, refer to the index number:
cars[0] = "Opel";
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
return 0;
}
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
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
return 0;
}
This example outputs the index of each element together with its value:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
return 0;
}
And this example shows how to loop through an array of integers:
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
return 0;
}
The foreach Loop
There is also a "for-each loop" (introduced in C++ version 11 (2011), which is used
exclusively to loop through elements in an array:
Syntax
for (type variableName : arrayName)
{
// code block to be executed
}
The following example outputs all elements in an array, using a "for-each loop":
Example
#include <iostream>
using namespace std;
int main()
{
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers)
{
cout << i << "\n";
}
return 0;
}
Omit Array Size
In C++, you don't have to specify the size of the array. The compiler is smart enough to
determine the size of the array based on the number of inserted values:
string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements
The example above is equal to:
string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array elements
However, the last approach is considered as "good practice", because it will reduce the
chance of errors in your program.
Omit Elements on Declaration
It is also possible to declare an array without specifying the elements on declaration, and add
them later:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
for(int i = 0; i < 5; i++)
{
cout << cars[i] << "\n";
}
return 0;
}
Get the Size of an Array
To get the size of an array, you can use the sizeof() operator:
Example
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
return 0;
}
Output 20
Why did the result show 20 instead of 5, when the array contains 5 elements?
It is because the sizeof() operator returns the size of a type in bytes. 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
#include <iostream>
using namespace std;
int main()
{
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
return 0;
}
Output 5
Loop Through an Array with sizeof()
In the Arrays and Loops Chapter, we wrote the size of the array in the loop condition (i < 5).
This is not ideal, since it will only work for arrays of a specified size.
However, by using the sizeof() approach from the example above, we can now make loops
that work for arrays of any size, which is more sustainable.
Instead of writing:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
It is better to write:
Example
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
cout << myNumbers[i] << "\n";
}
return 0;
}
It is good to know the different ways to loop through an array, since you may encounter them
all in different programs.
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" }
}
};
Access the Elements of a Multi-Dimensional Array
To access an element of a multi-dimensional array, specify an index number in each of the
array's dimensions. This statement accesses the value of the element in the first row (0) and
third column (2) of the letters array.
Example
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2];
return 0;
}
Change Elements in a Multi-Dimensional Array
To change the value of an element, refer to the index number of the element in each of the
dimensions:
Example
#include <iostream>
using namespace std;
int main()
{
string letters[2][4] = {{ "A", "B", "C", "D" },{ "E", "F", "G", "H" }};
letters[0][0] = "Z";
cout << letters[0][0];
return 0;
}
The following example outputs all elements in the letters array:
Loop Through a Multi-Dimensional Array
Example
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {{ "A", "B", "C", "D" },{ "E", "F", "G", "H" }};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}
return 0;
}
This example shows how to loop through a three-dimensional array:
Example
#include <iostream>
using namespace std;
int main() {
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
cout << letters[i][j][k] << "\n";
}
}
}
return 0;
}
Why Multi-Dimensional Arrays?
Multi-dimensional arrays are great at representing grids. This example shows a practical use
for them. In the following example we use a multi-dimensional array to represent a small
game of Battleship:
Example
#include <iostream>
using namespace std;
int main() {
// 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 }
};
// 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;
cout << "Selecting coordinates\n";
cout << "Choose a row number between 0 and 3: "; // Ask the player for a row
cin >> row;
cout << "Choose a column number between 0 and 3: "; // Ask the player for a column
cin >> column;
if (ships[row][column]) // Check if a ship exists in those coordinates
{
ships[row][column] = 0; // If the player hit a ship, remove it by setting the
value to zero.
hits++; // Increase the hit counter
cout << "Hit! " << (4-hits) << " left.\n\n";// Tell the player that they have
hit a ship and how many ships are left
}
else
{
// Tell the player that they missed
cout << "Miss\n\n";
}
numberOfTurns++; // Count how many turns the player has taken
}
cout << "Victory!\n";
cout << "You won in " << numberOfTurns << " turns";
return 0;
}