Solve Quadratic Equations in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to solve quadratic equations in C programming. The lab covers the complete process, starting from reading the coefficients of the quadratic equation, computing the discriminant, and determining the real or complex roots. You will write a C program that prompts the user for the coefficients, performs the necessary calculations, and prints the solutions.

The lab is divided into two main steps. First, you will learn how to read the coefficients a, b, and c from the user. Then, you will modify the program to calculate the discriminant and use the quadratic formula to find the roots of the equation, handling both real and complex solutions.


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(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435199{{"`Solve Quadratic Equations in C`"}} c/variables -.-> lab-435199{{"`Solve Quadratic Equations in C`"}} c/if_else -.-> lab-435199{{"`Solve Quadratic Equations in C`"}} c/user_input -.-> lab-435199{{"`Solve Quadratic Equations in C`"}} c/math_functions -.-> lab-435199{{"`Solve Quadratic Equations in C`"}} end

Read a, b, c

In this step, you'll learn how to read input values for a quadratic equation in C. We'll create a program that accepts the coefficients a, b, and c from the user.

First, create a new file for your quadratic equation solver:

cd ~/project
nano quadratic_solver.c

Now, add the following code to the file:

#include <stdio.h>

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

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

    printf("Enter coefficient b: ");
    scanf("%lf", &b);

    printf("Enter coefficient c: ");
    scanf("%lf", &c);

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

    return 0;
}

Compile the program:

gcc quadratic_solver.c -o quadratic_solver

Run the program:

./quadratic_solver

Example output:

Enter coefficient a: 1
Enter coefficient b: -5
Enter coefficient c: 6
Coefficients entered:
a = 1.00
b = -5.00
c = 6.00

Let's break down the key parts of the code:

  • scanf() is used to read user input for each coefficient
  • %lf is the format specifier for double-precision floating-point numbers
  • We store the coefficients in variables a, b, and c
  • The program prints back the entered coefficients to confirm input

Compute Discriminant and Determine Roots

In this step, you'll modify the previous program to calculate the discriminant and determine the roots of the quadratic equation using the quadratic formula.

Open the existing file and update the code:

cd ~/project
nano quadratic_solver.c

Replace the previous code with the following:

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

int main() {
    double a, b, c;
    double discriminant, root1, root2;

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

    printf("Enter coefficient b: ");
    scanf("%lf", &b);

    printf("Enter coefficient c: ");
    scanf("%lf", &c);

    // Calculate discriminant
    discriminant = b * b - 4 * a * c;

    // Check discriminant to determine root types
    if (discriminant > 0) {
        // Two distinct real roots
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("Two distinct real roots:\n");
        printf("Root 1 = %.2f\n", root1);
        printf("Root 2 = %.2f\n", root2);
    } else if (discriminant == 0) {
        // One real root (repeated)
        root1 = -b / (2 * a);
        printf("One real root (repeated):\n");
        printf("Root = %.2f\n", root1);
    } else {
        // Complex roots
        double realPart = -b / (2 * a);
        double imaginaryPart = sqrt(-discriminant) / (2 * a);
        printf("Complex roots:\n");
        printf("Root 1 = %.2f + %.2fi\n", realPart, imaginaryPart);
        printf("Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart);
    }

    return 0;
}

Compile the program with the math library:

gcc quadratic_solver.c -o quadratic_solver -lm

Run the program with different scenarios:

./quadratic_solver

Example output (two real roots):

Enter coefficient a: 1
Enter coefficient b: -5
Enter coefficient c: 6
Two distinct real roots:
Root 1 = 3.00
Root 2 = 2.00

Example output (one real root):

Enter coefficient a: 1
Enter coefficient b: -2
Enter coefficient c: 1
One real root (repeated):
Root = 1.00

Example output (complex roots):

Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
Complex roots:
Root 1 = -1.00 + 2.00i
Root 2 = -1.00 - 2.00i

Key points in the code:

  • Uses the quadratic formula to calculate roots
  • Checks the discriminant to determine root types
  • Handles three scenarios: two real roots, one real root, complex roots
  • Uses sqrt() function from math.h library
  • Compiles with -lm flag to link math library

Print Real or Complex Solutions

In this step, you'll enhance the quadratic equation solver to provide more detailed output and handle different solution types with improved formatting.

Open the existing file and update the code:

cd ~/project
nano quadratic_solver.c

Replace the previous code with the following:

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

void printQuadraticSolutions(double a, double b, double c) {
    double discriminant = b * b - 4 * a * c;

    printf("Quadratic Equation: %.2fx² + %.2fx + %.2f = 0\n", a, b, c);
    printf("Discriminant: %.2f\n", discriminant);

    if (discriminant > 0) {
        double root1 = (-b + sqrt(discriminant)) / (2 * a);
        double root2 = (-b - sqrt(discriminant)) / (2 * a);

        printf("Solution Type: Two Distinct Real Roots\n");
        printf("Root 1: %.2f\n", root1);
        printf("Root 2: %.2f\n", root2);
    } else if (discriminant == 0) {
        double root = -b / (2 * a);

        printf("Solution Type: One Real Root (Repeated)\n");
        printf("Root: %.2f\n", root);
    } else {
        double realPart = -b / (2 * a);
        double imaginaryPart = sqrt(-discriminant) / (2 * a);

        printf("Solution Type: Complex Conjugate Roots\n");
        printf("Root 1: %.2f + %.2fi\n", realPart, imaginaryPart);
        printf("Root 2: %.2f - %.2fi\n", realPart, imaginaryPart);
    }
}

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

    printf("Quadratic Equation Solver\n");
    printf("------------------------\n");

    printf("Enter coefficient a: ");
    scanf("%lf", &a);

    printf("Enter coefficient b: ");
    scanf("%lf", &b);

    printf("Enter coefficient c: ");
    scanf("%lf", &c);

    printf("\n");
    printQuadraticSolutions(a, b, c);

    return 0;
}

Compile the program:

gcc quadratic_solver.c -o quadratic_solver -lm

Run the program with different scenarios:

./quadratic_solver

Example output (two real roots):

Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: -5
Enter coefficient c: 6

Quadratic Equation: 1.00x² + -5.00x + 6.00 = 0
Discriminant: 1.00
Solution Type: Two Distinct Real Roots
Root 1: 3.00
Root 2: 2.00

Example output (one real root):

Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: -2
Enter coefficient c: 1

Quadratic Equation: 1.00x² + -2.00x + 1.00 = 0
Discriminant: 0.00
Solution Type: One Real Root (Repeated)
Root: 1.00

Example output (complex roots):

Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5

Quadratic Equation: 1.00x² + 2.00x + 5.00 = 0
Discriminant: -16.00
Solution Type: Complex Conjugate Roots
Root 1: -1.00 + 2.00i
Root 2: -1.00 - 2.00i

Key improvements:

  • Created a separate function printQuadraticSolutions() for better code organization
  • Added more descriptive output with solution type and equation details
  • Maintained the same root calculation logic from previous step
  • Improved user interface with a title and clear formatting

Summary

In this lab, you will learn how to read input values for a quadratic equation in C, compute the discriminant, and determine the real or complex roots using the quadratic formula. The program prompts the user to enter the coefficients a, b, and c, and then calculates the discriminant to determine the nature of the roots. Finally, the program prints the real or complex solutions.

The key steps covered in this lab include reading user input for the coefficients, calculating the discriminant, and applying the quadratic formula to find the roots. The program also confirms the input coefficients and provides the computed solutions.

Other C Tutorials you may like