OverIQ.com

C Program to find the roots of a Quadratic equation

Last updated on July 27, 2020


What is Quadratic Equation? #

An equation of the form:

\begin{gather*}
a x^{2} + b x + c = 0
\end{gather*}

is known as a quadratic equation, where a, b and c are numbers and a is not equal to 0. The values of x which satisfies the equation are known as the roots of the equation.

To calculate the roots of a quadratic equation we use the following formula:

\begin{gather*}
x=\frac{-b^2 \pm \sqrt{b^2-4ac}}{2a}
\end{gather*}

where \(\sqrt{b^2 - 4ac}\) is called the discriminant.

If discriminant > 0, then the equation has two distinct real roots.
If discriminant = 0, then the roots of the equation are real and same.
If discriminant < 0, then the roots of the equation are imaginary.

The following is a C program which computes the roots of the quadratic equation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/***********************************************************
 * C Program to find the roots of a Quadratic equation
************************************************************/

#include<stdio.h> // include stdio.h
#include<math.h> // include math.h for mathematical functions

int main() 
{
    float a, b, c, discriminant, root1, root2;    

    printf("Enter coefficient of x^2: ");
    scanf("%f", &a);

    printf("Enter coefficient of x: ");
    scanf("%f", &b);

    printf("Enter constant term: ");
    scanf("%f", &c);

    discriminant = sqrt( b*b - 4*a*c );        

    if(discriminant >= 0)
    {
        root1 = ( -b + discriminant ) / (2.0*a);
        root2 = ( -b - discriminant ) / (2.0*a);
        printf("\nFirst root: %.2f\n", root1);
        printf("Second root: %.2f\n", root2);
    }

    else
    {
        printf("\nRoots are imaginary");
    }

    return 0;
}

Expected Output: 1st run:

1
2
3
4
5
6
Enter coefficient of x^2: 1
Enter coefficient of x: 7
Enter constant term: 12

First root: -3.00
Second root: -4.00

2nd run:

1
2
3
4
5
Enter coefficient of x^2: 1
Enter coefficient of x: 4
Enter constant term: 5

Roots are imaginary

Related Programs: