Question: Write a C program to input and display a 3×3 matrix using a two-dimensional array.
C Program:
#include <stdio.h>
int main() {
int matrix[3][3];
int i, j;
// Input elements of the 3x3 matrix
printf("Enter elements of 3x3 matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Display the 3x3 matrix
printf("3x3 Matrix is:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
1. A two-dimensional array matrix[3][3] is declared to store the elements of a 3×3 matrix.
2. Two nested for loops are used to take input for each row and column of the matrix.
3. The scanf() function is used to read the matrix elements from the user.
4. Another set of nested loops is used to display the matrix in proper row and column format.
5. The printf() function is used to print the matrix elements on the screen.
6. This program demonstrates the use of a two-dimensional array in C programming.