ProgrammingHard
The function void zero(int n, int m[][n]) assigns zero to all cells. Which loop is correct for n x n data?
- A. for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) m[i][j] = 0;
- B. for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) m[i][n] = 0;
- C. for (int i = 0; i < n; i++) m[i] = 0;
- D. for (int i = 1; i < n; i++) for (int j = 1; j < n; j++) m[i][j] = 0;
Correct answer: A. for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) m[i][j] = 0;
Both indices must range over 0 to n - 1. The other loops write to a column past the end, assign a whole row to an int, or go one past the end.
More C Programming questions
- A 2D array is stored in memory and read in column-major order by mistake in a C program. What is the main consequence?
- The sum of i + j over all cells of a 3 x 3 grid with indices 0 to 2 is what?
- Which declaration creates a 3 x 3 identity matrix with C99 designators?
- For n = 10^5 cells in a 1D array viewed as a 316 x 317 grid, what is the total cell count?
- A matrix has R rows and C columns with R = 3 and C = 4 in a flat array of 12 ints. What flat index is cell (2, 3)?
- A square matrix is symmetric when a[i][j] equals a[j][i]. What is the time needed to test an n x n matrix for symmetry in C?