C Program to Find All Roots of a Quadratic Equation - Source Code, Output & Execution Flow

C Program to Find All Roots of a Quadratic Equation

This C program finds the roots of a quadratic equation using the discriminant.

#include <stdio.h>
#include <math.h>
int main() {
    double a, b, c, d, r1, r2;
    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);
    d = b * b - 4 * a * c;
    if (d > 0) {
        r1 = (-b + sqrt(d)) / (2 * a);
        r2 = (-b - sqrt(d)) / (2 * a);
        printf("Roots are %.2lf and %.2lf
", r1, r2);
    } else if (d == 0) {
        r1 = -b / (2 * a);
        printf("Root is %.2lf
", r1);
    } else {
        printf("Roots are imaginary.
");
    }
    return 0;
}
Enter coefficients a, b and c: 1 -5 6
Roots are 3.00 and 2.00

In this program, the input is read first when required, the core logic is applied step by step, and the final result is displayed using printf(). Follow the execution flow beside the code to understand how each statement contributes to the output.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗