Chapter 4 - Worked Examples
Exercise 1 - Static Arrays
Create a C++ program as follows:
Create an integer array of size 3, called
numbers, with all its values initialised to3.Using the subscript notation (
[]), print out each element of the array.Using the same subscript notation (
[]), set the 3 elements to 10, 11, and 12 respectively.Again, using the subscript notation (
[]), print out each element of the array.
Exercise 2 - Dynamic Arrays
Create a C++ program as follows:
Declare 2 empty vectors, named
row1androw2respectively. (You do not need to specify a size, or initial values for these vectors.)Add the values 10 and 20 to
row1, using the.push_backmethod.Add the values 100 and 200 to
row2, again using the.push_backPrint the size of each vector, using the
.sizemethod.Print the contents of each vector, using the
.atmethod forrow1, and the subscript notation[]forrow2.Now, declare an empty 2D vector called
grid. (Remember, a 2D vector is a vector ofvector<int>s.Add
row1androw2togrid, using the.push_backmethod.Display all elements in
grid, using the.at()method.Display all elements in
grid, using the subscript notation[].Change
row1.at(0)to 1000Display again all elements in
grid, with your method of choice.
Exercise 3 - Tic Tac Toe
For the coming weeks, we will slowly learn how to create a tic-tac-toe program in C++.
We'll be implementing the relevant functions as we learn more concepts, and in the end we'll piece them together to create our program!
Creating a tic-tac-toe board
Create a 2D integer vector, called board, with 3 rows and 3 columns, all initialised to the value 0.
This is akin to drawing a tic-tac-toe board on a piece of paper, with each element of the 2D vector corresponding to a 'square' on board. We'll use this 2D vector to represent the state of our board.
A value of
0is meant to indicate that the 'square' represented by that element is empty.A value of
1will be used to indicate that the 'square' represented by that element is an 'X'.A value of
2will be used to indicate that the 'square' represented by that element is an 'O'.
Representing the state of each cell
Great, so we have our board - but note that since it's a 2D integer vector, there's nothing stopping programmers from accidentally putting 'invalid' numbers into each element - what would an element of the value '140' mean?
To fix this, we need to limit the range of values that can be held by each element. You might remember enums being a useful solution for such scenarios!
Create an enum, called Cell, that contains the following constants:
EMPTY, with value 0PLAYER_X, with value 1PLAYER_Y, with value 2
Now, go ahead and change the type of your 2D vector from vector<vector<int>> to vector<vector<Cell>>
Also make sure that each of the elements are initialised to EMPTY.
Great! Now we've restricted the values that each element can represent - going forwards we can be certain that each element will either be EMPTY, PLYAER_X, or PLAYER_Y.
Last updated
Was this helpful?