Theory
Rows માંથી columns
a એક 2×3 grid છે, જેની rows {1, 2, 3} અને {4, 5, 6} છે. દરેક cell માટે:
b[j][i] = a[i][j];
b કેવો દેખાય છે?
Think first
પહેલાં તમારો અંદાજ
b ને type કરો, દરેક row એક line માં.
Show the answer
1 4
2 5
3 6
b 3×2 છે: a ની દરેક row એક column બની ગઈ. આ જ transpose છે.
Theory
Loop એ જ, body અલગ
દરેક 2D operation એ જ nested loop છે, બસ અંદરની line અલગ છે. Addition અને subtraction એક જ order વાળા grids પર cell by cell ચાલે છે: c[i][j] = a[i][j] + b[i][j];. Search દરેક cell ને target સાથે સરખાવે છે.
Practical
2 grids નું addition
#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
ઉપરનો program શું 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 દરેક cell ને એના જોડીદાર cell સાથે ઉમેરે છે: 1 + 5, 2 + 6, 3 + 7, 4 + 8. બાકીના જવાબો જોડીદાર cells નો ગુણાકાર કરે છે, matrix product બનાવે છે, કે બંને grids ને જેમ છે તેમ print કરે છે.
Theory
Multiplication: ત્રીજો loop
Matrix multiplication ને ત્રીજો loop જોઈએ: cell (i, j) એટલે a ની row i ગુણ્યા b નો column j, જોડીએ જોડીએ, 0 થી શરૂ કરીને ઉમેરતાં. Line છે c[i][j] += a[i][k] * b[k][j];, અને a ના columns b ની rows જેટલા હોવા જોઈએ.
Think first
એક cell હાથે
Addition વાળા program ના a અને b લઈને, product a × b નો c[0][0] શોધો.
Show the answer
19: 1 × 5 + 2 × 7, a ની row 0 ગુણ્યા b નો column 0. c[i][j] = 0 છોડી દો તો garbage પણ ઉમેરાઈ જાય છે.
Theory
2 strings merge કરવી
"Ri" અને "ya" ને merge કરવા પહેલી string copy કરો, બીજીને પહેલીના '\0' ની જગ્યાએથી લખવાનું શરૂ કરો, અને છેલ્લે નવો '\0' મૂકો. C માં strings માટે + નથી; Unit 4 નું strcat આ કામ કરી આપે છે.
Practical
Exam-style: 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: ઉપરનો program શું print કરે છે?
- 4 6 10 12
- 2 4 10 14
- 2 0 3 12
- 2 7 6 15
Show the answer
4 6 10 12
a ની row 0 ગુણ્યા b નો column 0: 1 × 2 + 2 × 1 = 4. 2 4 10 14 એ b × a છે, અને 2 0 3 12 જોડીદાર cells નો ગુણાકાર કરે છે.
Summary
Key takeaways
- એ જ nested loops, અંદર એક અલગ line.
- Cell by cell ઉમેરો; transpose માટે b[j][i] = a[i][j].
- ગુણાકાર ત્રીજા loop k થી, c[i][j] ને 0 થી શરૂ કરીને.
- યાદ રાખવાની યુક્તિ: રસ્તો એ જ, કામ અલગ.