Solve a System of Two Linear Equations in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to solve a system of two linear equations in C programming. The lab covers two main steps: reading the coefficients for the two equations, and then computing the solutions using the determinant method. You will create a C program that allows users to input the coefficients, and then the program will calculate and display the solutions or any special cases that may arise.

The first step involves prompting the user to enter the coefficients for the two linear equations in the standard form: ax + by = c. The program will then print the entered coefficients to verify the input. In the second step, you will extend the program to calculate the solutions using Cramer's rule, which involves computing the determinants of the coefficient matrices. The program will display the solutions or any special cases, such as no solution or infinitely many solutions.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/operators("`Operators`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435197{{"`Solve a System of Two Linear Equations in C`"}} c/variables -.-> lab-435197{{"`Solve a System of Two Linear Equations in C`"}} c/operators -.-> lab-435197{{"`Solve a System of Two Linear Equations in C`"}} c/user_input -.-> lab-435197{{"`Solve a System of Two Linear Equations in C`"}} c/math_functions -.-> lab-435197{{"`Solve a System of Two Linear Equations in C`"}} end

Read Coefficients for Two Equations

In this step, you will learn how to read coefficients for a system of two linear equations using C programming. We'll create a program that allows users to input coefficients for two equations in the standard form: ax + by = c.

First, let's create a new C file to implement our equation solver:

cd ~/project
nano linear_equations.c

Now, add the following code to read coefficients:

#include <stdio.h>

int main() {
    float a1, b1, c1;  // Coefficients for first equation
    float a2, b2, c2;  // Coefficients for second equation

    // Prompt and read coefficients for the first equation
    printf("Enter coefficients for the first equation (ax + by = c):\n");
    printf("a1: ");
    scanf("%f", &a1);
    printf("b1: ");
    scanf("%f", &b1);
    printf("c1: ");
    scanf("%f", &c1);

    // Prompt and read coefficients for the second equation
    printf("Enter coefficients for the second equation (ax + by = c):\n");
    printf("a2: ");
    scanf("%f", &a2);
    printf("b2: ");
    scanf("%f", &b2);
    printf("c2: ");
    scanf("%f", &c2);

    // Print the entered coefficients to verify
    printf("\nFirst Equation: %.2fx + %.2fy = %.2f\n", a1, b1, c1);
    printf("Second Equation: %.2fx + %.2fy = %.2f\n", a2, b2, c2);

    return 0;
}

Compile and run the program:

gcc linear_equations.c -o linear_equations
./linear_equations

Example output:

Enter coefficients for the first equation (ax + by = c):
a1: 2
b1: 3
c1: 8
Enter coefficients for the second equation (ax + by = c):
a2: 1
b2: 4
c2: 10

First Equation: 2.00x + 3.00y = 8.00
Second Equation: 1.00x + 4.00y = 10.00

Compute Solutions Using Determinants

In this step, you will learn how to solve a system of two linear equations using the determinant method. We'll extend the previous program to calculate the solutions using Cramer's rule.

Open the existing file and modify the code:

cd ~/project
nano linear_equations.c

Update the code with the determinant calculation method:

#include <stdio.h>

// Function to calculate determinant
float determinant(float a1, float b1, float a2, float b2) {
    return a1 * b2 - a2 * b1;
}

int main() {
    float a1, b1, c1;  // Coefficients for first equation
    float a2, b2, c2;  // Coefficients for second equation
    float det, detX, detY;
    float x, y;

    // Prompt and read coefficients for the first equation
    printf("Enter coefficients for the first equation (ax + by = c):\n");
    printf("a1: ");
    scanf("%f", &a1);
    printf("b1: ");
    scanf("%f", &b1);
    printf("c1: ");
    scanf("%f", &c1);

    // Prompt and read coefficients for the second equation
    printf("Enter coefficients for the second equation (ax + by = c):\n");
    printf("a2: ");
    scanf("%f", &a2);
    printf("b2: ");
    scanf("%f", &b2);
    printf("c2: ");
    scanf("%f", &c2);

    // Calculate main determinant
    det = determinant(a1, b1, a2, b2);

    // Check if the system has a unique solution
    if (det != 0) {
        // Calculate determinants for x and y
        detX = determinant(c1, b1, c2, b2);
        detY = determinant(a1, c1, a2, c2);

        // Calculate solutions
        x = detX / det;
        y = detY / det;

        printf("\nSolution:\n");
        printf("x = %.2f\n", x);
        printf("y = %.2f\n", y);
    } else {
        // Check if the system has no solution or infinite solutions
        if (determinant(c1, b1, c2, b2) != 0 || determinant(a1, c1, a2, c2) != 0) {
            printf("\nNo solution exists.\n");
        } else {
            printf("\nInfinite solutions exist.\n");
        }
    }

    return 0;
}

Compile and run the program:

gcc linear_equations.c -o linear_equations
./linear_equations

Example output for a unique solution:

Enter coefficients for the first equation (ax + by = c):
a1: 2
b1: 3
c1: 8
Enter coefficients for the second equation (ax + by = c):
a2: 1
b2: 4
c2: 10

Solution:
x = 2.00
y = 2.00

Example output for no solution:

Enter coefficients for the first equation (ax + by = c):
a1: 2
b1: 3
c1: 8
Enter coefficients for the second equation (ax + by = c):
a2: 4
b2: 6
c2: 16

No solution exists.

Print Solutions or Special Cases

In this final step, you will enhance the program to provide more detailed output for different types of solutions in a system of two linear equations.

Open the existing file and make final modifications:

cd ~/project
nano linear_equations.c

Update the code with improved output formatting:

#include <stdio.h>
#include <math.h>

// Function to calculate determinant
float determinant(float a1, float b1, float a2, float b2) {
    return a1 * b2 - a2 * b1;
}

int main() {
    float a1, b1, c1;  // Coefficients for first equation
    float a2, b2, c2;  // Coefficients for second equation
    float det, detX, detY;
    float x, y;
    float EPSILON = 1e-6;  // Small value for floating-point comparison

    // Prompt and read coefficients for the first equation
    printf("Linear Equation Solver\n");
    printf("Enter coefficients for the first equation (ax + by = c):\n");
    printf("a1: ");
    scanf("%f", &a1);
    printf("b1: ");
    scanf("%f", &b1);
    printf("c1: ");
    scanf("%f", &c1);

    // Prompt and read coefficients for the second equation
    printf("Enter coefficients for the second equation (ax + by = c):\n");
    printf("a2: ");
    scanf("%f", &a2);
    printf("b2: ");
    scanf("%f", &b2);
    printf("c2: ");
    scanf("%f", &c2);

    // Print input equations
    printf("\nInput Equations:\n");
    printf("Equation 1: %.2fx + %.2fy = %.2f\n", a1, b1, c1);
    printf("Equation 2: %.2fx + %.2fy = %.2f\n", a2, b2, c2);

    // Calculate main determinant
    det = determinant(a1, b1, a2, b2);

    // Determine and print solution type
    if (fabs(det) > EPSILON) {
        // Unique solution case
        detX = determinant(c1, b1, c2, b2);
        detY = determinant(a1, c1, a2, c2);

        x = detX / det;
        y = detY / det;

        printf("\n--- Solution Type: Unique Solution ---\n");
        printf("Solution:\n");
        printf("x = %.2f\n", x);
        printf("y = %.2f\n", y);
    } else {
        // Check for no solution or infinite solutions
        detX = determinant(c1, b1, c2, b2);
        detY = determinant(a1, c1, a2, c2);

        if (fabs(detX) > EPSILON || fabs(detY) > EPSILON) {
            printf("\n--- Solution Type: No Solution ---\n");
            printf("The system of equations has no solution.\n");
            printf("Equations are inconsistent and parallel.\n");
        } else {
            printf("\n--- Solution Type: Infinite Solutions ---\n");
            printf("The system of equations has infinitely many solutions.\n");
            printf("Equations are equivalent and dependent.\n");
        }
    }

    return 0;
}

Compile and run the program:

gcc linear_equations.c -o linear_equations
./linear_equations

Example output for unique solution:

Linear Equation Solver
Enter coefficients for the first equation (ax + by = c):
a1: 2
b1: 3
c1: 8
Enter coefficients for the second equation (ax + by = c):
a2: 1
b2: 4
c2: 10

Input Equations:
Equation 1: 2.00x + 3.00y = 8.00
Equation 2: 1.00x + 4.00y = 10.00

--- Solution Type: Unique Solution ---
Solution:
x = 2.00
y = 2.00

Example output for no solution:

Linear Equation Solver
Enter coefficients for the first equation (ax + by = c):
a1: 2
b1: 3
c1: 8
Enter coefficients for the second equation (ax + by = c):
a2: 4
b2: 6
c2: 16

Input Equations:
Equation 1: 2.00x + 3.00y = 8.00
Equation 2: 4.00x + 6.00y = 16.00

--- Solution Type: No Solution ---
The system of equations has no solution.
Equations are inconsistent and parallel.

Summary

In this lab, you first learned how to read coefficients for a system of two linear equations in C programming. You created a program that prompts the user to input the coefficients (a, b, c) for the two equations and then prints the equations to verify the input. Next, you will learn how to solve the system of equations using the determinant method and Cramer's rule to compute the solutions.

The program will extend the previous functionality to calculate the solutions for the system of equations. It will determine the determinant of the coefficient matrix and use Cramer's rule to find the values of the variables x and y that satisfy the system.

Other C Tutorials you may like