Finding Determinant of 2x2 Matrix

CCBeginner
Practice Now

Introduction

In linear algebra, the determinant of a square matrix is a scalar value that can be calculated from the elements of the matrix. In this lab, we will learn how to find the determinant of a 2x2 matrix using C programming.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Understanding the Concept

Before we begin, let's understand the concept of a determinant. A 2x2 matrix is an array of 2 rows and 2 columns, and its determinant can be calculated using the formula:

determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1]

where a[0][0], a[0][1], a[1][0], and a[1][1] are the elements of the matrix.

Initializing the Variables

We will start by declaring and initializing the variables in the C program.

#include<stdio.h>

int main()
{
    int a[2][2], i, j;
    long determinant;

    printf("\n\nEnter the 4 elements of the array\n");
    for(i = 0; i < 2; i++)
    for(j = 0; j < 2; j++)
    scanf("%d", &a[i][j]);
}

Getting the Matrix Elements

Now, we will ask the user to enter the elements of the matrix.

printf("\n\nEnter the 4 elements of the array\n");
for(i = 0; i < 2; i++)
    for(j = 0; j < 2; j++)
    scanf("%d", &a[i][j]);

Printing the Entered Matrix

After getting the matrix elements, we will print the entered matrix.

printf("\n\nThe entered matrix is: \n\n");
for(i = 0; i < 2; i++)
{
    for(j = 0; j < 2; j++)
    {
        printf("%d\t", a[i][j]);   // to print the complete row
    }
    printf("\n"); // to move to the next row
}

Calculating the Determinant

Now we will calculate the determinant.

determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\n\nDeterminant of 2x2 matrix is : %d - %d = %ld", a[0][0]*a[1][1], a[1][0]*a[0][1], determinant);

Printing the Result

Finally, we will print the result.

printf("\n\nThe determinant of the 2x2 matrix is %ld.", determinant);

Summary

In this lab, we learned how to find the determinant of a 2x2 matrix using C programming. We initialized the variables, got the matrix elements, printed the entered matrix, calculated the determinant, and printed the result.

Other C Tutorials you may like