Solve Linear Equations Using Cramer's Rule in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to solve linear equations using Cramer's Rule in C. The lab will guide you through the process of reading the coefficients and constants of a system of linear equations, computing the determinants, and finally printing the solutions for the variables. You will create a C program that allows users to input the coefficients and constants, and then the program will provide the solutions using Cramer's Rule. This lab covers essential matrix and linear algebra concepts, and the skills learned can be applied to a variety of real-world problems.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435198{{"`Solve Linear Equations Using Cramer's Rule in C`"}} c/data_types -.-> lab-435198{{"`Solve Linear Equations Using Cramer's Rule in C`"}} c/arrays -.-> lab-435198{{"`Solve Linear Equations Using Cramer's Rule in C`"}} c/user_input -.-> lab-435198{{"`Solve Linear Equations Using Cramer's Rule in C`"}} c/math_functions -.-> lab-435198{{"`Solve Linear Equations Using Cramer's Rule in C`"}} end

Read Coefficients and Constants

In this step, you will learn how to read coefficients and constants for solving linear equations using Cramer's Rule in C. We'll create a program that allows users to input the coefficients of a system of linear equations.

First, let's create a C source file for our linear equation solver:

cd ~/project
nano cramer_solver.c

Now, add the following code to the file:

#include <stdio.h>

#define MAX_SIZE 3

int main() {
    float matrix[MAX_SIZE][MAX_SIZE];
    float constants[MAX_SIZE];
    int n;

    // Input the size of the system of equations
    printf("Enter the number of equations (max 3): ");
    scanf("%d", &n);

    // Input coefficients
    printf("Enter the coefficients of the matrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("Enter coefficient a[%d][%d]: ", i+1, j+1);
            scanf("%f", &matrix[i][j]);
        }
    }

    // Input constants
    printf("Enter the constants:\n");
    for (int i = 0; i < n; i++) {
        printf("Enter constant b[%d]: ", i+1);
        scanf("%f", &constants[i]);
    }

    // Print the input matrix and constants
    printf("\nInput Matrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%.2f ", matrix[i][j]);
        }
        printf("| %.2f\n", constants[i]);
    }

    return 0;
}

Compile the program:

gcc -o cramer_solver cramer_solver.c

Run the program:

./cramer_solver

Example output:

Enter the number of equations (max 3): 2
Enter the coefficients of the matrix:
Enter coefficient a[1][1]: 2
Enter coefficient a[1][2]: 1
Enter coefficient a[2][1]: -3
Enter coefficient a[2][2]: 4
Enter the constants:
Enter constant b[1]: 4
Enter constant b[2]: 5

Input Matrix:
2.00 1.00 | 4.00
-3.00 4.00 | 5.00

Let's break down the code:

  1. We define a maximum size of 3x3 for the system of linear equations.
  2. The program first asks the user to input the number of equations.
  3. It then prompts the user to enter the coefficients of the matrix.
  4. Next, it asks for the constants of the linear equations.
  5. Finally, it prints the input matrix and constants for verification.

This step prepares the groundwork for implementing Cramer's Rule by allowing users to input the coefficients and constants of a system of linear equations.

Compute Determinants

In this step, you will learn how to compute determinants for solving linear equations using Cramer's Rule in C. We'll extend the previous program to include determinant calculation functions.

Open the existing source file:

cd ~/project
nano cramer_solver.c

Update the code with determinant calculation functions:

#include <stdio.h>

#define MAX_SIZE 3

// Function to compute determinant of a matrix
float computeDeterminant(float matrix[MAX_SIZE][MAX_SIZE], int n) {
    if (n == 1) {
        return matrix[0][0];
    }

    if (n == 2) {
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
    }

    float det = 0;
    float submatrix[MAX_SIZE][MAX_SIZE];
    int sign = 1;

    for (int x = 0; x < n; x++) {
        int subi = 0;
        for (int i = 1; i < n; i++) {
            int subj = 0;
            for (int j = 0; j < n; j++) {
                if (j == x) continue;
                submatrix[subi][subj] = matrix[i][j];
                subj++;
            }
            subi++;
        }
        det += sign * matrix[0][x] * computeDeterminant(submatrix, n - 1);
        sign = -sign;
    }

    return det;
}

int main() {
    float matrix[MAX_SIZE][MAX_SIZE];
    float constants[MAX_SIZE];
    int n;

    // Previous input code remains the same
    printf("Enter the number of equations (max 3): ");
    scanf("%d", &n);

    // Input coefficients
    printf("Enter the coefficients of the matrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("Enter coefficient a[%d][%d]: ", i+1, j+1);
            scanf("%f", &matrix[i][j]);
        }
    }

    // Input constants
    printf("Enter the constants:\n");
    for (int i = 0; i < n; i++) {
        printf("Enter constant b[%d]: ", i+1);
        scanf("%f", &constants[i]);
    }

    // Compute and display determinant
    float mainDeterminant = computeDeterminant(matrix, n);
    printf("\nMain Determinant: %.2f\n", mainDeterminant);

    return 0;
}

Compile the updated program:

gcc -o cramer_solver cramer_solver.c

Run the program:

./cramer_solver

Example output:

Enter the number of equations (max 3): 2
Enter the coefficients of the matrix:
Enter coefficient a[1][1]: 2
Enter coefficient a[1][2]: 1
Enter coefficient a[2][1]: -3
Enter coefficient a[2][2]: 4
Enter the constants:
Enter constant b[1]: 4
Enter constant b[2]: 5

Main Determinant: 11.00

Key points about the determinant calculation:

  1. The computeDeterminant() function uses recursion to calculate matrix determinants.
  2. It handles 1x1 and 2x2 matrices as base cases.
  3. For larger matrices, it uses the cofactor expansion method.
  4. The function works for square matrices up to 3x3.

The code demonstrates how to compute the main determinant of the coefficient matrix, which is a crucial step in Cramer's Rule for solving linear equations.

Print Solutions for Variables

In this step, you will complete the Cramer's Rule implementation by calculating and printing the solutions for variables in a system of linear equations.

Open the existing source file:

cd ~/project
nano cramer_solver.c

Update the code with Cramer's Rule solution calculation:

#include <stdio.h>

#define MAX_SIZE 3

// Previous computeDeterminant function remains the same
float computeDeterminant(float matrix[MAX_SIZE][MAX_SIZE], int n) {
    if (n == 1) {
        return matrix[0][0];
    }

    if (n == 2) {
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
    }

    float det = 0;
    float submatrix[MAX_SIZE][MAX_SIZE];
    int sign = 1;

    for (int x = 0; x < n; x++) {
        int subi = 0;
        for (int i = 1; i < n; i++) {
            int subj = 0;
            for (int j = 0; j < n; j++) {
                if (j == x) continue;
                submatrix[subi][subj] = matrix[i][j];
                subj++;
            }
            subi++;
        }
        det += sign * matrix[0][x] * computeDeterminant(submatrix, n - 1);
        sign = -sign;
    }

    return det;
}

// Function to solve linear equations using Cramer's Rule
void solveUsingCramersRule(float matrix[MAX_SIZE][MAX_SIZE], float constants[MAX_SIZE], int n) {
    float mainDeterminant = computeDeterminant(matrix, n);

    // Check if the system has a unique solution
    if (mainDeterminant == 0) {
        printf("The system has no unique solution (determinant is zero).\n");
        return;
    }

    // Create temporary matrices for each variable
    float tempMatrix[MAX_SIZE][MAX_SIZE];
    float solutions[MAX_SIZE];

    // Calculate solutions for each variable
    for (int i = 0; i < n; i++) {
        // Copy original matrix
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < n; k++) {
                tempMatrix[j][k] = matrix[j][k];
            }
        }

        // Replace i-th column with constants
        for (int j = 0; j < n; j++) {
            tempMatrix[j][i] = constants[j];
        }

        // Calculate determinant for this variable
        solutions[i] = computeDeterminant(tempMatrix, n) / mainDeterminant;
    }

    // Print solutions
    printf("\nSolutions:\n");
    for (int i = 0; i < n; i++) {
        printf("x%d = %.2f\n", i+1, solutions[i]);
    }
}

int main() {
    float matrix[MAX_SIZE][MAX_SIZE];
    float constants[MAX_SIZE];
    int n;

    // Input code remains the same
    printf("Enter the number of equations (max 3): ");
    scanf("%d", &n);

    // Input coefficients
    printf("Enter the coefficients of the matrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("Enter coefficient a[%d][%d]: ", i+1, j+1);
            scanf("%f", &matrix[i][j]);
        }
    }

    // Input constants
    printf("Enter the constants:\n");
    for (int i = 0; i < n; i++) {
        printf("Enter constant b[%d]: ", i+1);
        scanf("%f", &constants[i]);
    }

    // Solve using Cramer's Rule
    solveUsingCramersRule(matrix, constants, n);

    return 0;
}

Compile the updated program:

gcc -o cramer_solver cramer_solver.c

Run the program:

./cramer_solver

Example output:

Enter the number of equations (max 3): 2
Enter the coefficients of the matrix:
Enter coefficient a[1][1]: 2
Enter coefficient a[1][2]: 1
Enter coefficient a[2][1]: -3
Enter coefficient a[2][2]: 4
Enter the constants:
Enter constant b[1]: 4
Enter constant b[2]: 5

Solutions:
x1 = 2.00
x2 = 1.00

Key points about the solution calculation:

  1. The solveUsingCramersRule() function implements Cramer's Rule.
  2. It checks if the system has a unique solution by verifying the main determinant.
  3. For each variable, it creates a temporary matrix and calculates its determinant.
  4. Solutions are computed by dividing each variable's determinant by the main determinant.

The program now fully solves a system of linear equations using Cramer's Rule.

Summary

In this lab, you will learn how to read the coefficients and constants of a system of linear equations, which is the first step in solving them using Cramer's Rule in C. The program allows users to input the coefficients of the matrix and the constants, and then it prints the input matrix for verification. This step lays the foundation for the subsequent steps of computing determinants and printing the solutions for the variables.

The next step will involve calculating the determinants of the coefficient matrix and the modified matrices, which is a crucial part of Cramer's Rule. The final step will be to print the solutions for the variables by dividing the determinants of the modified matrices by the determinant of the coefficient matrix.

Other C Tutorials you may like