Program to find the Roots of Quadratic equation

In this example, you will learn to find the roots of a quadratic equation in C programming

C Program to Find Roots of a Quadratic Equation :

Every quadratic equation gives two values of the unknown variable and these values are called roots of the equation.

A quadratic equation has two roots which may be unequal real numbers or equal real numbers, or numbers which are not real. If a quadratic equation has two real equal roots α, we say the equation has only one real solution.

Example :

	
#include <math.h>
#include <stdio.h>
int main() {
    double a, b, c, discriminant, root1, root2, realPart, imagPart;
    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);

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

    // condition for real and different roots
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
    }

    // condition for real and equal roots
    else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        printf("root1 = root2 = %.2lf;", root1);
    }

    // if roots are not real
    else {
        realPart = -b / (2 * a);
        imagPart = sqrt(-discriminant) / (2 * a);
        printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
    }
    return 0;
} 
	

Output :

	
Enter coefficients a, b and c: 10
20
30
root1 = -1.00+1.41i and root2 = -1.00-1.41i
	

Share your thoughts

Ask anything about this examples