In this post we are going to make the matrix in C and take all values from user.
Algorithm
This code first reads the number of rows and columns of the matrix from the user, then declares a two-dimensional array with the specified number of rows and columns. It then reads the values for each element of the matrix from the user and stores them in the array. Finally, it prints the matrix by iterating over each element and printing its value.
I hope this helps! Let me know if you have any questions.
Code
#include <stdio.h>
int main() {
int rows, columns;
printf("Enter the number of rows and columns of the matrix: ");
scanf("%d%d", &rows, &columns);
int matrix[rows][columns]; // Declare the matrix with the specified number of rows and columns
printf("Enter the values for the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("Enter value for matrix[%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]); // Read the value from the user
}
}
printf("\nThe matrix is:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d ", matrix[i][j]); // Print the value of the matrix element
}
printf("\n");
}
return 0;
}
Output
Enter the number of rows and columns of the matrix: 3
3
Enter the values for the matrix:
Enter value for matrix[0][0]: 1
Enter value for matrix[0][1]: 2
Enter value for matrix[0][2]: 3
Enter value for matrix[1][0]: 4
Enter value for matrix[1][1]: 5
Enter value for matrix[1][2]: 6
Enter value for matrix[2][0]: 7
Enter value for matrix[2][1]: 8
Enter value for matrix[2][2]: 9
The matrix is:
1 2 3
4 5 6
7 8 9