Solve a Linear Equation (ax + b = 0) in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to solve a linear equation of the form ax + b = 0 using C programming. You will start by reading the coefficients a and b from the user, then compute the solution x by applying the formula x = -b/a, while ensuring that the coefficient a is not zero. Finally, you will print the solution or indicate that no solution exists.

The lab covers the fundamental concepts of algebraic expressions and their implementation in C. By the end of this lab, you will have a solid understanding of how to solve simple linear equations programmatically.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/output -.-> lab-435195{{"`Solve a Linear Equation (ax + b = 0) in C`"}} c/variables -.-> lab-435195{{"`Solve a Linear Equation (ax + b = 0) in C`"}} c/operators -.-> lab-435195{{"`Solve a Linear Equation (ax + b = 0) in C`"}} c/if_else -.-> lab-435195{{"`Solve a Linear Equation (ax + b = 0) in C`"}} c/user_input -.-> lab-435195{{"`Solve a Linear Equation (ax + b = 0) in C`"}} end

Read Coefficients a and b

In this step, you will learn how to read coefficients a and b for solving a linear equation in C. We'll create a simple program that prompts the user to input the coefficients and stores them in variables.

First, let's create a new C file in the project directory:

cd ~/project
nano linear_equation.c

Now, enter the following code to read coefficients:

#include <stdio.h>

int main() {
    double a, b;

    // Prompt user to enter coefficient a
    printf("Enter coefficient a (must not be zero): ");
    scanf("%lf", &a);

    // Prompt user to enter coefficient b
    printf("Enter coefficient b: ");
    scanf("%lf", &b);

    // Print the entered coefficients
    printf("Coefficient a: %.2f\n", a);
    printf("Coefficient b: %.2f\n", b);

    return 0;
}

Compile and run the program:

gcc linear_equation.c -o linear_equation
./linear_equation

Example output:

Enter coefficient a (must not be zero): 2
Enter coefficient b: 4
Coefficient a: 2.00
Coefficient b: 4.00

Let's break down the code:

  • We use double to allow decimal inputs for coefficients
  • printf() is used to prompt the user for input
  • scanf() reads the user's input and stores it in variables a and b
  • We print the entered coefficients to confirm they were read correctly

Compute x = -b/a (Check if a ≠ 0)

In this step, you will modify the previous program to compute the solution of the linear equation ax + b = 0, with a special focus on handling the case when a is zero.

Open the previous file and update the code:

cd ~/project
nano linear_equation.c

Replace the contents with the following code:

#include <stdio.h>

int main() {
    double a, b, x;

    // Prompt user to enter coefficient a
    printf("Enter coefficient a (must not be zero): ");
    scanf("%lf", &a);

    // Check if a is zero
    if (a == 0) {
        printf("Error: Coefficient 'a' cannot be zero.\n");
        return 1;
    }

    // Prompt user to enter coefficient b
    printf("Enter coefficient b: ");
    scanf("%lf", &b);

    // Compute solution x
    x = -b / a;

    // Print the solution
    printf("Solution of the equation %.2fx + %.2f = 0:\n", a, b);
    printf("x = %.2f\n", x);

    return 0;
}

Compile and run the program:

gcc linear_equation.c -o linear_equation
./linear_equation

Example output for a valid input:

Enter coefficient a (must not be zero): 2
Enter coefficient b: 4
Solution of the equation 2.00x + 4.00 = 0:
x = -2.00

Example output for an invalid input (a = 0):

Enter coefficient a (must not be zero): 0
Error: Coefficient 'a' cannot be zero.

Key points in this code:

  • We add a check to ensure a is not zero before computing the solution
  • If a is zero, we print an error message and exit the program
  • The solution x is computed using the formula x = -b/a
  • We use %.2f to format the output to two decimal places

Print the Solution or State No Solution

In this final step, you will enhance the linear equation solver to handle different scenarios and provide clear output for the solution.

Open the previous file and update the code:

cd ~/project
nano linear_equation.c

Replace the contents with the following code:

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

int main() {
    double a, b, x;

    // Prompt user to enter coefficient a
    printf("Enter coefficient a: ");
    scanf("%lf", &a);

    // Prompt user to enter coefficient b
    printf("Enter coefficient b: ");
    scanf("%lf", &b);

    // Check different scenarios
    if (a == 0 && b == 0) {
        printf("Infinite solutions: Every real number is a solution.\n");
    } else if (a == 0 && b != 0) {
        printf("No solution: The equation cannot be solved.\n");
    } else {
        // Compute solution x
        x = -b / a;

        // Print the solution
        printf("Equation: %.2fx + %.2f = 0\n", a, b);
        printf("Solution: x = %.2f\n", x);
    }

    return 0;
}

Compile and run the program:

gcc linear_equation.c -o linear_equation
./linear_equation

Example output scenarios:

Scenario 1 (Normal solution):

Enter coefficient a: 2
Enter coefficient b: 4
Equation: 2.00x + 4.00 = 0
Solution: x = -2.00

Scenario 2 (No solution):

Enter coefficient a: 0
Enter coefficient b: 5
No solution: The equation cannot be solved.

Scenario 3 (Infinite solutions):

Enter coefficient a: 0
Enter coefficient b: 0
Infinite solutions: Every real number is a solution.

Key improvements in this version:

  • Handles three distinct scenarios for linear equations
  • Provides clear, informative messages for different cases
  • Uses precise mathematical logic to determine solution type

Summary

In this lab, you learned how to read coefficients a and b for solving a linear equation in C. You created a simple program that prompts the user to input the coefficients and stores them in variables. You also learned how to compute the solution of the linear equation ax + b = 0, with a special focus on handling the case when a is zero. The program checks if a is zero and provides an error message if it is, otherwise it computes the solution x = -b/a and prints it.

Other C Tutorials you may like