C Program to Find All Roots of a Quadratic Equation

Created with Sketch.

#include <stdio.h>
#include <math.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;
    
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("Roots are real and different.\n");
        printf("Root 1 = %.2lf\n", root1);
        printf("Root 2 = %.2lf\n", root2);
    } else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        printf("Roots are real and same.\n");
        printf("Root 1 = Root 2 = %.2lf\n", root1);
    } else {
        realPart = -b / (2 * a);
        imagPart = sqrt(-discriminant) / (2 * a);
        printf("Roots are complex and different.\n");
        printf("Root 1 = %.2lf + %.2lfi\n", realPart, imagPart);
        printf("Root 2 = %.2lf - %.2lfi\n", realPart, imagPart);
    }
    
    return 0;
}

In this program, we declare double variables “a”, “b”, and “c”, which represent the coefficients of the quadratic equation. We prompt the user to enter these values using the “scanf” function.

We then calculate the discriminant of the quadratic equation using the formula “b^2 – 4ac”. If the discriminant is greater than 0, it means that the equation has two real roots. We calculate these roots using the quadratic formula (-b +/- sqrt(discriminant)) / (2a), and print out a message indicating that the roots are real and different.

If the discriminant is equal to 0, it means that the equation has a single real root. We calculate this root using the formula -b / (2a), and print out a message indicating that the roots are real and same.

If the discriminant is less than 0, it means that the equation has two complex roots. We calculate these roots using the formula (-b +/- sqrt(-discriminant)i) / (2a), where i is the imaginary unit. We then print out a message indicating that the roots are complex and different.

Finally, we return 0 from the main function to indicate that the program has executed successfully. The output of this program would be:

Enter coefficients a, b and c: 1 -5 6
Roots are real and different.
Root 1 = 3.00
Root 2 = 2.00

If the user had entered coefficients such that the equation has a single real root, such as 1, -6, and 9, the output would be:

 
Enter coefficients a, b and c: 1 -6 9
Roots are real and same.
Root 1 = Root 2 = 3.00

If the user had entered coefficients such that the equation has two complex roots, such as 1, 2, and 10, the output would be:

Enter coefficients a

Leave a Reply

Your email address will not be published. Required fields are marked *