Skip to main content

Exercises 14.11 Exercises

Note 14.11.1.

When you fail a CHECK the vector will not automatically be displayed. Each problem declares a print function you can use to help debug your code.

1.

Write code for the function additiveInverse. It should take the 2D matrix given and change it into its additive inverse by multiplying each value in the matrix by -1.

2.

Write the function vector<vector<int>> create(int rows, int cols);. It should return a 2D vector of integers that is the correct dimensions. All the values should be 0
Hint.
This should only take 1 or 2 lines of code and should not require any loops. Refer back to the first page in the chapter for an example.

3.

Complete the function maxValue that returns the largest value from a 2D vector of integers.
The logic should be the same as finding the maximum value in a 1D vector, you just multiple loops.

4.

Complete the function diagonalAdder that adds up the numbers on the diagonal (from upper left to lower right) of a 2D vector. You can assume the vector is β€œsquare” - it has the same number of rows as columns. For example, in this matrix:
1 2 3
4 5 6
7 8 9
The diagonal is 1, 5, 9. Adding those up should result in 15.
Hint 1.
What is true of the row and column number for all elements on the diagonal?
Hint 2.
You should only need one loop to do this.

5.

Complete the function revDiagonalAdder that adds up and returns the numbers on the reverse diagonal (from upper right lower left) of a 2D vector of integers. You can assume the vector is β€œsquare” - it has the same number of rows as columns. For example, in this matrix:
1 2 3
4 5 6
0 8 9
The reverse diagonal is 3, 5, 0. Adding those up should result in 8.
Hint.
There is a relationship between the row and column number. As the row number increases, the column number decreases. Row 0 uses the last column. Row 1 uses the column before that. Row 2 uses the column before that. The last row uses column 0.

6.

Complete the function secondRowProduct that computes the product of all of the items in the second row of a 2D vector of integers. Given this data:
1 2 3
4 5 6
0 8 9
You would return 120 (4 * 5 * 6).
Tip: When multiplying, you will want to start your accumulator variable with 1 not 0.

7.

Complete the function mirror. Given a 2D vector of integers:
1 2 3
4 5 6
It should produce a new vector where the data is mirrored horizontally:
3 2 1
6 5 4
You may assume that the data is always 2 rows and 3 columns.
You have attempted of activities on this page.