Compute the Determinant of a Matrix in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to compute the determinant of a square matrix in C programming. The lab covers the following steps: reading the dimension and elements of the matrix, using a recursive or LU decomposition method to calculate the determinant, and printing the final result. The step-by-step instructions guide you through the process of creating a program that can handle square matrices of up to 10x10 size, allowing you to input the matrix elements dynamically and display the computed determinant.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/recursion("`Recursion`") subgraph Lab Skills c/output -.-> lab-435157{{"`Compute the Determinant of a Matrix in C`"}} c/for_loop -.-> lab-435157{{"`Compute the Determinant of a Matrix in C`"}} c/arrays -.-> lab-435157{{"`Compute the Determinant of a Matrix in C`"}} c/user_input -.-> lab-435157{{"`Compute the Determinant of a Matrix in C`"}} c/recursion -.-> lab-435157{{"`Compute the Determinant of a Matrix in C`"}} end

Read Dimension and Elements (Square Matrix)

In this step, you will learn how to read the dimension and elements of a square matrix in C programming. We'll create a program that allows users to input the size of the matrix and its elements dynamically.

First, let's create a new C file for our matrix determinant program:

cd ~/project
nano matrix_determinant.c

Now, add the following code to read the matrix dimension and elements:

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

int main() {
    int n, i, j;
    int matrix[MAX_SIZE][MAX_SIZE];

    // Read matrix dimension
    printf("Enter the size of the square matrix (1-%d): ", MAX_SIZE);
    scanf("%d", &n);

    // Validate matrix size
    if (n < 1 || n > MAX_SIZE) {
        printf("Invalid matrix size. Please enter a size between 1 and %d.\n", MAX_SIZE);
        return 1;
    }

    // Read matrix elements
    printf("Enter the matrix elements:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    // Print the matrix to verify input
    printf("\nEntered Matrix:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Compile and run the program:

gcc matrix_determinant.c -o matrix_determinant
./matrix_determinant

Example output:

Enter the size of the square matrix (1-10): 3
Enter the matrix elements:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][0]: 7
Enter element [2][1]: 8
Enter element [2][2]: 9

Entered Matrix:
1 2 3
4 5 6
7 8 9

Let's break down the code:

  • We define a maximum matrix size of 10 to prevent excessive memory allocation.
  • The program first asks the user to input the matrix size.
  • It validates the input to ensure it's within the allowed range.
  • Then, it prompts the user to enter each matrix element individually.
  • Finally, it prints the entered matrix to verify the input.

Use a Recursive or LU Decomposition Method

In this step, we'll implement a recursive method to calculate the determinant of a matrix. We'll modify the previous program to include a determinant calculation function.

Update the matrix_determinant.c file:

nano matrix_determinant.c

Replace the previous content with the following code:

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

// Function to calculate determinant recursively
int determinant(int matrix[MAX_SIZE][MAX_SIZE], int n) {
    int det = 0;
    int submatrix[MAX_SIZE][MAX_SIZE];

    // Base case for 1x1 matrix
    if (n == 1) {
        return matrix[0][0];
    }

    // Base case for 2x2 matrix
    if (n == 2) {
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
    }

    // Recursive case for larger matrices
    int sign = 1;
    for (int k = 0; k < n; k++) {
        // Create submatrix
        int subi = 0;
        for (int i = 1; i < n; i++) {
            int subj = 0;
            for (int j = 0; j < n; j++) {
                if (j == k) continue;
                submatrix[subi][subj] = matrix[i][j];
                subj++;
            }
            subi++;
        }

        // Recursive calculation
        det += sign * matrix[0][k] * determinant(submatrix, n - 1);
        sign = -sign;
    }

    return det;
}

int main() {
    int n, i, j;
    int matrix[MAX_SIZE][MAX_SIZE];

    // Read matrix dimension
    printf("Enter the size of the square matrix (1-%d): ", MAX_SIZE);
    scanf("%d", &n);

    // Validate matrix size
    if (n < 1 || n > MAX_SIZE) {
        printf("Invalid matrix size. Please enter a size between 1 and %d.\n", MAX_SIZE);
        return 1;
    }

    // Read matrix elements
    printf("Enter the matrix elements:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    // Calculate and print determinant
    int det = determinant(matrix, n);
    printf("\nDeterminant of the matrix: %d\n", det);

    return 0;
}

Compile and run the program:

gcc matrix_determinant.c -o matrix_determinant
./matrix_determinant

Example output:

Enter the size of the square matrix (1-10): 3
Enter the matrix elements:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][0]: 7
Enter element [2][1]: 8
Enter element [2][2]: 9

Determinant of the matrix: 0

Key points about the recursive determinant calculation:

  • The determinant() function uses a recursive approach to calculate the matrix determinant.
  • For 1x1 and 2x2 matrices, we have base cases with direct calculations.
  • For larger matrices, we use the method of cofactor expansion along the first row.
  • The function creates submatrices and recursively calculates their determinants.

Print the Determinant

In this final step, we'll enhance our matrix determinant program by adding more detailed output and error handling to improve the user experience.

Update the matrix_determinant.c file:

nano matrix_determinant.c

Replace the previous content with the following improved code:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_SIZE 10

// Function to calculate determinant recursively
int determinant(int matrix[MAX_SIZE][MAX_SIZE], int n) {
    int det = 0;
    int submatrix[MAX_SIZE][MAX_SIZE];

    // Base case for 1x1 matrix
    if (n == 1) {
        return matrix[0][0];
    }

    // Base case for 2x2 matrix
    if (n == 2) {
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
    }

    // Recursive case for larger matrices
    int sign = 1;
    for (int k = 0; k < n; k++) {
        // Create submatrix
        int subi = 0;
        for (int i = 1; i < n; i++) {
            int subj = 0;
            for (int j = 0; j < n; j++) {
                if (j == k) continue;
                submatrix[subi][subj] = matrix[i][j];
                subj++;
            }
            subi++;
        }

        // Recursive calculation
        det += sign * matrix[0][k] * determinant(submatrix, n - 1);
        sign = -sign;
    }

    return det;
}

// Function to print matrix with formatting
void print_matrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
    printf("\nMatrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%5d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int n, i, j;
    int matrix[MAX_SIZE][MAX_SIZE];
    bool valid_input = false;

    while (!valid_input) {
        // Read matrix dimension
        printf("Enter the size of the square matrix (1-%d): ", MAX_SIZE);
        if (scanf("%d", &n) != 1) {
            printf("Invalid input. Please enter a number.\n");
            while (getchar() != '\n'); // Clear input buffer
            continue;
        }

        // Validate matrix size
        if (n < 1 || n > MAX_SIZE) {
            printf("Invalid matrix size. Please enter a size between 1 and %d.\n", MAX_SIZE);
            continue;
        }

        valid_input = true;
    }

    // Read matrix elements
    printf("Enter the matrix elements:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            while (scanf("%d", &matrix[i][j]) != 1) {
                printf("Invalid input. Please enter an integer for element [%d][%d]: ", i, j);
                while (getchar() != '\n'); // Clear input buffer
            }
        }
    }

    // Print the input matrix
    print_matrix(matrix, n);

    // Calculate and print determinant
    int det = determinant(matrix, n);

    // Formatted determinant output
    printf("\n--- Determinant Calculation ---\n");
    printf("Matrix Dimension: %d x %d\n", n, n);
    printf("Determinant: %d\n", det);

    return 0;
}

Compile and run the program:

gcc matrix_determinant.c -o matrix_determinant
./matrix_determinant

Example output:

Enter the size of the square matrix (1-10): 3
Enter the matrix elements:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][0]: 7
Enter element [2][1]: 8
Enter element [2][2]: 9

Matrix:
    1     2     3
    4     5     6
    7     8     9

--- Determinant Calculation ---
Matrix Dimension: 3 x 3
Determinant: 0

Key improvements:

  • Added input validation to handle invalid inputs
  • Created a separate function to print the matrix with better formatting
  • Enhanced output to show matrix dimension and determinant clearly
  • Improved error handling for user inputs

Summary

In this lab, you learned how to read the dimension and elements of a square matrix in C programming. You created a program that allows users to input the size of the matrix and its elements dynamically. The program validates the matrix size and then prompts the user to enter the matrix elements. Finally, it prints the entered matrix to verify the input.

The next steps in this lab will cover how to use a recursive or LU decomposition method to compute the determinant of the input matrix, and how to print the determinant.

Other C Tutorials you may like