A two-dimensional array stores values in rows and columns. For int matrix[3][3], both row and column indexes range from 0 to 2.
#include <stdio.h>
int main(void) {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
printf("%d ", matrix[row][col]);
}
printf("\n");
}
return 0;
}
Output
1 2 3
4 5 6
7 8 9
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
printf("Value [%d][%d]: ", row, col);
if (scanf("%d", &matrix[row][col]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
}
To double the second row, second column element, use index [1][1] because indexing starts from zero:
matrix[1][1] *= 2;
#include <stdio.h>
int main(void) {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 2; col++) {
sum[row][col] = a[row][col] + b[row][col];
}
}
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 2; col++) {
printf("%d ", sum[row][col]);
}
printf("\n");
}
return 0;
}
Matrix Sum Matrix Multiplication
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.