Theory
Rows into columns
a is 2×3, with rows {1, 2, 3} and {4, 5, 6}. For every cell:
b[j][i] = a[i][j];
What does b look like?
Think first
Your guess first
Type b, one row per line.
Show the answer
1 4
2 5
3 6
b is 3×2: each row of a became a column. That is the transpose.
Theory
Same loop, different body
Every 2D operation is the same nested loop with a different line inside. Addition and subtraction go cell by cell on grids of the same order: c[i][j] = a[i][j] + b[i][j];. Search compares each cell with the target.
Practical
Adding two grids
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
printf("%d ", a[i][j] + b[i][j]);
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
What does the program above print?
- 6 8 10 12
- 5 12 21 32
- 19 22 43 50
- 1 2 3 4 5 6 7 8
Show the answer
6 8 10 12
Addition pairs each cell with its twin: 1 + 5, 2 + 6, 3 + 7, 4 + 8. Others multiply twins, form the matrix product, or print both grids.
Theory
Multiplication: a third loop
Matrix multiplication needs a third loop: cell (i, j) is row i of a times column j of b, pair by pair, added up from 0. The line is c[i][j] += a[i][k] * b[k][j];, and a's columns must equal b's rows.
Think first
One cell by hand
Using a and b from the addition program, work out c[0][0] of the product a × b.
Show the answer
19: 1 × 5 + 2 × 7, row 0 of a times column 0 of b. Skip c[i][j] = 0 and garbage joins in.
Theory
Merging two strings
To merge "Ri" and "ya", copy the first string, write the second starting at the first one's '\0', and end with a new '\0'. C has no + for strings; strcat (Unit 4) does it.
Practical
Exam-style: predict the output
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{2, 0}, {1, 3}};
int c[2][2], i, j, k;
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++) {
c[i][j] = 0;
for (k = 0; k < 2; k++)
c[i][j] += a[i][k] * b[k][j];
printf("%d ", c[i][j]);
}
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Exam-style: what does the program above print?
- 4 6 10 12
- 2 4 10 14
- 2 0 3 12
- 2 7 6 15
Show the answer
4 6 10 12
Row 0 of a times column 0 of b: 1 × 2 + 2 × 1 = 4. 2 4 10 14 is b × a, and 2 0 3 12 multiplies twin cells.
Summary
Key takeaways
- Same nested loops, a different line inside.
- Add cell by cell; transpose with b[j][i] = a[i][j].
- Multiply with a third loop k, starting c[i][j] at 0.
- Memory hook: same tour, different chore.