Write a C program to find inverse of the given matrix(order 2).
#include <stdio.h>
#define ORDER 2
int main() {
int i, j;
float matrix[2][2], cofactor[2][2];
float inverse[2][2], adj[2][2], det;
/* get the entries for the input matrix */
printf("Enter your entries for input matrix:\n");
for (i = 0; i < ORDER; i++) {
for (j = 0; j < ORDER; j++) {
scanf("%f", &matrix[i][j]);
}
}
/* find the co-factor for the input matrix */
cofactor[0][0] = matrix[1][1];
cofactor[0][1] = (-1) * matrix[1][0];
cofactor[1][0] = (-1) * matrix[0][1];
cofactor[1][1] = matrix[0][0];
/* tranpose of co-factor is the adjoint of the matrix */
for (i = 0; i < ORDER; i++) {
for (j = 0; j < ORDER; j++) {
adj[i][j] = cofactor[j][i];
}
}
/* finding determinant of the input matrix */
det = (matrix[0][0] * matrix[1][1]) -
(matrix[0][1] * matrix[1][0]);
det = (1.0 / det);
#define ORDER 2
int main() {
int i, j;
float matrix[2][2], cofactor[2][2];
float inverse[2][2], adj[2][2], det;
/* get the entries for the input matrix */
printf("Enter your entries for input matrix:\n");
for (i = 0; i < ORDER; i++) {
for (j = 0; j < ORDER; j++) {
scanf("%f", &matrix[i][j]);
}
}
/* find the co-factor for the input matrix */
cofactor[0][0] = matrix[1][1];
cofactor[0][1] = (-1) * matrix[1][0];
cofactor[1][0] = (-1) * matrix[0][1];
cofactor[1][1] = matrix[0][0];
/* tranpose of co-factor is the adjoint of the matrix */
for (i = 0; i < ORDER; i++) {
for (j = 0; j < ORDER; j++) {
adj[i][j] = cofactor[j][i];
}
}
/* finding determinant of the input matrix */
det = (matrix[0][0] * matrix[1][1]) -
(matrix[0][1] * matrix[1][0]);
det = (1.0 / det);
/*
* A^(-1) => (1 / |A|) * (adj A)
* Inverse of the given matrix calculation
*/
for (i = 0; i < ORDER; i++) {
for (j = 0; j < ORDER; j++) {
inverse[i][j] = (det * adj[i][j]);
}
}
/* printing the inverse of the given matrix */
printf("\nInverse of the given matrix:\n");
for (i = 0; i < ORDER; i++) {
for (j = 0; j < ORDER; j++) {
printf("%.2f ", inverse[i][j]);
}
printf("\n");
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your entries for input matrix:
-1 2
1 -4
Inverse of the given matrix:
-2.00 -1.00
-0.50 -0.50
Enter your entries for input matrix:
-1 2
1 -4
Inverse of the given matrix:
-2.00 -1.00
-0.50 -0.50
Learning Code Examples about java programming
ReplyDelete