C PROGRAMMING PROGRAM • DECISION MAKING

Find the Roots of a Quadratic Equation

Learn how to find the roots of a quadratic equation using a clear C program.

IntermediateDiscriminantsqrt()Multiple branches

PROBLEM UNDERSTANDING

Input and expected output

Sample input
1 -5 6
Sample output
Roots = 3.00 and 2.00

COMPLETE C PROGRAM

Complete C implementation

quadratic-equation-roots.c
Open in compiler
#include <stdio.h>
#include <math.h>

int main(void)
{
    double a, b, c, discriminant, firstRoot, secondRoot;

    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);
    if (a == 0) {
        printf("The equation is not quadratic.\n");
        return 0;
    }
    discriminant = b * b - 4.0 * a * c;
    if (discriminant > 0) {
        firstRoot = (-b + sqrt(discriminant)) / (2.0 * a);
        secondRoot = (-b - sqrt(discriminant)) / (2.0 * a);
        printf("Roots = %.2f and %.2f\n", firstRoot, secondRoot);
    } else if (discriminant == 0) {
        printf("Repeated root = %.2f\n", -b / (2.0 * a));
    } else {
        printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi\n",
               -b / (2.0 * a), sqrt(-discriminant) / (2.0 * a),
               -b / (2.0 * a), sqrt(-discriminant) / (2.0 * a));
    }
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Roots = 3.00 and 2.00
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Use the discriminant b²−4ac to select two real, one repeated or two complex roots.
  3. Display the computed result.

Use the discriminant b²−4ac to select two real, one repeated or two complex roots.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.