ProgrammingHard
For int a[1000][1000], which loop walks memory in address order (the cache-friendly order)?
- A. for (j = 0; j < 1000; j++) for (i = 0; i < 1000; i++) sum += a[i][j];
- B. for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) sum += a[j][i];
- C. for (i = 0; i < 1000000; i++) sum += a[i % 1000][i / 1000];
- D. for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) sum += a[i][j];
Correct answer: D. for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) sum += a[i][j];
C stores each row contiguously, so the last index must vary fastest. Column-major traversal jumps 4000 bytes between accesses, which makes it much slower on real hardware. All versions do the same 10^6 additions.
More C Programming questions
- Which declaration makes a 10^6 int matrix at run time without depending on the stack size?
- For a matrix of size n x n with n = 500, which algorithm is correct and fast enough within 1 second for C multiplication?
- Given int a[3][4] and int q = &a[0][0], which element does q[5] refer to?
- int m[2][3] = {{1}, {2, 3}}; What is m[0][0] + m[1][0] + m[1][1] + m[0][2]?
- int a[3][4]; what do sizeof a / sizeof a[0] and sizeof a[0] / sizeof a[0][0] give?
- char g[3][4] = {"abc", "de", "f"}; What is the value of g[1][2] when printed with %d?