This program finds the Determinant of a Matrix in C.
Program Code:
//to find determinant, inverse and transpose
#include <stdio.h>
#include <stdlib.h>
//function to find determinant
int determinant(int matrix[10][10], int size)
{
int Det = 0, temp[10][10], idx, jdx, kdx, c1, c2, flag = 1;
//for 1x1 matrix
if (size == 1)
{
return matrix[0][0];
}
//for 2x2 matrix
if (size == 2)
{
Det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}
//for nxn matrix
else
{
for (idx = 0; idx < size; idx++)
{
c1 = 0, c2 = 0;
for (jdx = 0; jdx < size; jdx++)
{
for(kdx = 0; kdx < size; kdx++)
{
if ( jdx != 0 && kdx != idx)
{
temp[c1][c2] = matrix[jdx][kdx];
c2++;
if(c2 > size - 2)
{
c1++;
c2 = 0;
}
}
}
}
Det = Det + flag * (matrix[0][idx] * determinant(temp, size - 1));
flag = -1 * flag;
}
}
return Det;
}
int main()
{
//declaring variables
int matrix[10][10], row, col, idx, jdx, Det;
char ch;
do
{
//reading an action from the user and the order of the matrix
printf(" =================================");
printf(" \n Determinant of Matrix \n");
printf(" =================================\n");
printf(" Enter the Size for Matrix\n Row's = ");
scanf("%d", &row);
printf(" Col's = ");
scanf("%d", &col);
//reading the matrix
for (idx = 0; idx < row; idx++)
{
printf(" Enter %d numbers for Row %d : ", col, idx + 1);
for (jdx = 0; jdx < col; jdx++)
{
scanf("%d", &matrix[idx][jdx]);
}
}
if (row != col)
{
printf(" Determinant can't be calculated for the given order!\n");
break;
}
//printing determinant value returned from the function
else
printf(" Determinant is \"%d\"\n", determinant(matrix, row));
printf("\n To Continue press [Y/n] : ");
getchar();
} while ((ch = getchar()) && (ch == 'y' || ch == 'Y'));
return 0;
}
Program Output:
Post a Comment