Read Dimensions and Elements
In this step, you will learn how to read matrix dimensions and elements from user input in a C program for matrix subtraction. We'll create a program that allows users to input the size and values of two matrices.
First, let's create a new C file for our matrix subtraction program:
cd ~/project
nano matrix_subtraction.c
Now, add the following code to the file:
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int rows, cols;
int matrix1[MAX_SIZE][MAX_SIZE];
int matrix2[MAX_SIZE][MAX_SIZE];
// Read matrix dimensions
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Input elements for the first matrix
printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
// Input elements for the second matrix
printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
return 0;
}
Example output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
Enter element [0][0]: 5
Enter element [0][1]: 6
Enter element [1][0]: 7
Enter element [1][1]: 8
Enter elements of the second matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [1][0]: 3
Enter element [1][1]: 4
Let's compile and run the program:
gcc matrix_subtraction.c -o matrix_subtraction
./matrix_subtraction
Code Explanation:
- We define a maximum matrix size of 100x100 using
MAX_SIZE
rows
and cols
store the dimensions of the matrices
- Two 2D arrays
matrix1
and matrix2
are created to store matrix elements
scanf()
is used to read matrix dimensions and elements from user input
- Nested loops are used to input elements for both matrices