Input and Print a 2x2 Matrix in C
Problem:
Write a C program to take input for a 2x2 matrix and display the matrix.
Example:
Input: 1 2 3 4 Output: 1 2 3 4
🔍 Explanation:
- A 2x2 matrix has 2 rows and 2 columns.
- We use a 2D array
matrix[2][2]
in C to store the values. scanf()
takes input from the user.printf()
prints the matrix in proper format.
✅ C Program:
#include <stdio.h>
int main() {
int matrix[2][2];
// Taking input
printf("Enter 4 elements of 2x2 matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Printing the matrix
printf("The 2x2 matrix is:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
📤 Output:
The 2x2 matrix is: 1 2 3 4
💡 Tips:
- Change the array size to create a 3x3 or 4x4 matrix.
- Nested loops are essential for matrix operations.
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন