Question 3: Explaining pointers Here is some C++ code. It uses a single function
ID: 3737902 • Letter: Q
Question
Question 3: Explaining pointers
Here is some C++ code. It uses a single function, which takes a square matrix of non-negative integers as
an input and processes it. This question asks you to explain, in detail, what the code does.
#include <iostream>
using namespace std;
const int n = 3;
int* all(int v[n][n]) { // Assumption: v contains non-negative integers
int m = 0;
int *ret = NULL;
for (int i=0; i < n; i++)
for (int j=0; j < n; j++)
if (v[i][j] > m) {
m = v[i][j];
ret = &(v[i][j]);
}
return ret;
}
int main() {
int t[n][n] = {{1, 23, 1}, {4, 0, 6}, {0, 12, 3}}; // Every element >= 0
int *p = all(t);
while (p != NULL) {
cout << *p << endl;
*p = 0;
p = all(t);
}
return 0;
}
Specifically, in your explanation address the following aspects:
1. What does all() do? If you were to give it a better name, what might that be? Pointers are used—why are they used?
2. What does the code output? (There is a description with one or two simple sentences.) Answer this first with respect to the given input, but then generalize to explain what it does for other matrices t.
(For guidance, work out how many lines are printed. It this always the same number, or does it depend on particular properties of the matrix?)
3. What variables, if any, undergo important state changes?
Explanation / Answer
1.
all() function takes in a square matrix consisting of all whole numbers
and returns a pointer which points to the largest number in the matrix.
Pointers are used to pass the output of all function, which gives the advantage of security as the actual value is hidden.
2.
output:
23
12
6
4
3
1
1
The given code takes in a square matrix consisting of all whole numbers
and prints them in descending order except all zeroes. It does not print zeroes at all, it skips them.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.