ProgrammingVery hard
An n x n matrix of ints is read row by row. Which code reads it correctly into int a[n][n] when n is a run-time value?
- A. void read(int n, int a[n][n]) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &a[i][j]); }
- B. void read(int a[n][n], int n) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &a[i][j]); }
- C. void read(int n, int a[][]) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &a[i][j]); }
- D. void read(int n, int a[n][n]) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &a[i][n]); }
Correct answer: A. void read(int n, int a[n][n]) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &a[i][j]); }
The size n must be a parameter declared before a. The other versions use n before it is declared, leave an inner size empty, or pass the value of an element instead of its address.
More C Programming questions
- A 1000 x 1000 grid of cells must be checked for the connected component containing a start cell. Which method is correct and fast enough?
- int a[3][3] = {{2,7,6},{9,5,1},{4,3,8}}; Are all of the row sums, column sums and both diagonal sums equal to 15?
- Row-major storage of int a[4][5] means a[i][j] is at flat index i 5 + j. What flat index holds a[3][2]?
- int a[2][3] with a pointer p = &a[0][0]. Which expression gives the number of elements between a[0][0] and a[1][2]?
- The sum of the elements of a[i][j] = i j over the 4 x 4 matrix equals what?
- Which statement about matrix multiplication in C is correct for an m x k matrix times a k x n matrix?