C Program to Compute Determinant of a 3 x 3 Matrix

The program receives a 3 x 3 matrix and computes the determinant and prints the results. The user provides the values for the matrix.

We compiled the program using Dev-C++ 5.0 compiler, but you can use a different compiler such as Turbo C++ 3.0.

You must be familiar with the concept of matrix and its determinant to understand this example. See the problem definition section for a brief introduction.

Learn following C programming concepts before you learn the example.

Problem Definition

The determinant of a 3 x3 matrix is easy to calculate. Before we dive into the code, let’s understand the procedure to calculate the determinant of a 3 x 3 matrix.

Suppose you are given a 3 x3 matrix like one given below.

3 x 3 Matrix
3 x 3 Matrix

The next step is to find the co-factor of A11, A21 and A31.

A11 =  a1(b2 . c3 - c2 . b3)    A21 = -a2(b1 . c3 - c1 . b3)    A31 = a3( b1 . c2 - c1 . b2)  

Now the value of determinant for 3×3 matrix is

Determinant = a1(b2 . c3 - c2 . b3)     - a2(b1 . c3 - c1 . b3)     + a3( b1 . c2 - c1 . b2)

Program Code – Determinant of 3 x 3 Matrix

/*Program to compute the determinant of a matrix */    #include <stdio.h>    #include <stdlib.h>    int main()  {        int a[3][3],i,j,m,n,detval;        int r1,r2,r3;        r1 = 0;        r2 = 0;        r3 = 0;        detval = 0;        printf("Enter Elements of matrix rowise:\n");        for(i=0;i<3;i++)      {            for(j=0;j<3;j++)          {                scanf("%d",&a[i][j]);            }        }        r1 = a[0][0] * ((a[1][1] * a[2][2])       - (a[2][1] * a[1][2]));        r2 = a[0][1] * ((a[1][0] * a[2][2])       - (a[2][0] * a[1][2]));        r3 = a[0][2] * ((a[1][0] * a[2][1])       - (a[2][0] * a[1][1]));        detval= r1 - r2 + r3;        printf("determinant=%d\n",detval);        system("PAUSE");        return 0;    }

Output

When the program executes, it ask for input values for the matrix. You must enter the values row-wise. Upon entering the values, it computes the determinant and prints the output to the console.

You can enter negative values too, the compiler will consider that as an negative integer value.The output value as you can see is a negative integer value of -11.

You can verify the answer by doing the math on a paper and compare the results with program output. Try solving for different values for matrix.

Output - Determinant of a 3 x 3 Matrix
Output – Determinant of a 3 x 3 Matrix

 

Related Articles:

Advertisements


Advertisements