பாடம் 7 / 8 · Functions-ம் Arrays-ம் · படிக்க 2 min · புதுப்பிக்கப்பட்டது
Two-dimensional arrays
Rows, columns-ல values-ஓட tables: declare பண்றது, நிரப்புறது, total பண்றது, transpose பண்றது.
Two-dimensional array-ன்னா ஒரு table: int marks[3][4]-ல 3 rows, 4 columns — 3 மாணவர்கள், 4 tests-ன்னு வெச்சுக்குங்க. marks[1][2]-ன்னா row 1, column 2. ரெண்டு எண்ணிக்கையும் 0-ல ஆரம்பிக்கும்.
#include <stdio.h>
int main(void)
{
int marks[3][4] = {
{72, 85, 63, 91},
{55, 78, 88, 69},
{90, 61, 74, 82},
};
for (int s = 0; s < 3; s++) {
int total = 0;
for (int t = 0; t < 4; t++) {
printf("%4d", marks[s][t]);
total += marks[s][t];
}
printf(" total %d\n", total);
}
return 0;
}
72 85 63 91 total 311
55 78 88 69 total 290
90 61 74 82 total 307
ரெண்டு nested loops ஒவ்வொரு cell-க்கும் போகும்: வெளி loop row-ஐ தேர்ந்தெடுக்கும், உள் loop அதோட columns வழியா நடக்கும். அந்த pattern — for row, for column — கிட்டத்தட்ட எல்லா 2D program-ம் இப்படித்தான் ஆரம்பிக்கும்.
Matrix-ஐ transpose பண்றது
#include <stdio.h>
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int t[3][2];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
t[c][r] = a[r][c]; /* row becomes column */
}
}
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 2; c++) {
printf("%4d", t[r][c]);
}
printf("\n");
}
return 0;
}
1 4
2 5
3 6
Note
Memory-ல 2D array row row-ஆ ஒரே நீண்ட வரிசையா சேமிக்கப்படும் (row-major order). அதனால அதை வாங்குற function-க்கு column எண்ணிக்கையை சொல்லணும்: void show(int a[][4], int rows). Rows எண்ணிக்கையை விடலாம்; columns-ஐ விட முடியாது.
int m[3][5]; — இதுல எத்தனை int values இருக்கும்?
இப்போ இதை செஞ்சு பாருங்க
- ரெண்டு 3 × 3 matrices-ஐ கூட்டி result-ஐ print பண்ணுங்க.
- ஒவ்வொரு row-க்கு பதிலா ஒவ்வொரு column-ஓட (ஒவ்வொரு test-ஓட) total-ஐ print பண்ணுங்க.
- மூணு nested loops வெச்சு ரெண்டு 2 × 2 matrices-ஐ பெருக்குங்க.
- 4 × 4 matrix-ல diagonal elements-ஐ மட்டும் print பண்ணுங்க (row-ம் column-ம் சமமா இருக்கிற இடம்).
Create a free account to save your progress, or sign in.