C program to find the Roots of Quadratic equation

In this tutorial, we will be discussing a program to find the roots of a quadratic equation using the quadratic formula.

Given a quadratic equation of the form ax2 + bx + c = 0, our task is to find the roots x1 and x2 of the given equation. For this, we use the discriminant method where the discriminant D = b2 - 4ac determines the nature of the roots.

Syntax

D = b*b - 4*a*c
x1 = (-b + sqrt(D)) / (2*a)
x2 = (-b - sqrt(D)) / (2*a)

Nature of Roots

  • D > 0: Two distinct real roots
  • D = 0: Two equal real roots
  • D Two complex conjugate roots

Example

This program calculates the roots of a quadratic equation using the quadratic formula −

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

void calc_roots(int a, int b, int c) {
    if (a == 0) {
        printf("Invalid Equation: coefficient 'a' cannot be zero<br>");
        return;
    }
    
    int d = b * b - 4 * a * c;
    
    if (d > 0) {
        double sqrt_val = sqrt(d);
        printf("Roots are real and different:<br>");
        printf("x1 = %.2f<br>", (-b + sqrt_val) / (2 * a));
        printf("x2 = %.2f<br>", (-b - sqrt_val) / (2 * a));
    }
    else if (d == 0) {
        printf("Roots are real and equal:<br>");
        printf("x1 = x2 = %.2f<br>", -b / (2.0 * a));
    }
    else {
        double real_part = -b / (2.0 * a);
        double imaginary_part = sqrt(-d) / (2 * a);
        printf("Roots are complex:<br>");
        printf("x1 = %.2f + %.2fi<br>", real_part, imaginary_part);
        printf("x2 = %.2f - %.2fi<br>", real_part, imaginary_part);
    }
}

int main() {
    int a = 2, b = -5, c = 8;
    printf("Quadratic equation: %dx² + %dx + %d = 0<br>", a, b, c);
    calc_roots(a, b, c);
    return 0;
}
Quadratic equation: 2x² + -5x + 8 = 0
Roots are complex:
x1 = 1.25 + 2.50fi
x2 = 1.25 - 2.50fi

Key Points

  • The discriminant D = b2 - 4ac determines the nature of roots
  • Always check if coefficient 'a' is zero to avoid division by zero
  • For complex roots, use sqrt(-D) to calculate the imaginary part

Conclusion

The quadratic formula provides a systematic way to find roots of any quadratic equation. By checking the discriminant value, we can determine whether the roots are real or complex before calculation.

Updated on: 2026-03-15T12:26:46+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements