Write a C program to find determinant of a N x N matrix.
int main() {
int order, output = 0, i, j, mat[3][3];
/* get the order of the matrix from user */
printf("Enter the order of the matrix(2/3):\n");
scanf("%d", &order);
if (order < 2 || order > 3) {
printf("Wrong input!!\n");
return 0;
}
/* get the input matrix */
printf("Enter your matrix input:\n");
for (i = 0; i < order; i++)
for (j = 0; j < order; j++)
scanf("%d", &mat[i][j]);
/* calculate the determinant for 2 x 2 matrix */
if (order == 2) {
output = (mat[0][0] * mat[1][1]) -
(mat[0][1] * mat[1][0]);
} else if (order == 3) {
/* calculate determinant for 3 x 3 matrix */
output = (mat[0][0] * mat[1][1] * mat[2][2]) -
(mat[0][0] * mat[2][1] * mat[1][2]) -
(mat[0][1] * mat[1][0] * mat[2][2]) +
(mat[0][1] * mat[2][0] * mat[1][2]) +
(mat[0][2] * mat[1][0] * mat[2][1]) -
(mat[0][2] * mat[1][1] * mat[2][0]);
}
/* print the determinant output */
printf("Determinant for the given matrix: %d\n", output);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the order of the matrix(2/3):
2
Enter your matrix input:
20 10
10 20
Determinant for the given matrix: 300
Enter the order of the matrix(2/3):
2
Enter your matrix input:
20 10
10 20
Determinant for the given matrix: 300
No comments:
Post a Comment