Roots of Quadratic Equation: C

Quadratic Equations are of the form ax2 + bx + c = 0. To find roots(root1 and root2) of such an equation, we need to use the formula



Find Roots of Quadratic Equation: C Program



YouTube Link: https://www.youtube.com/watch?v=zRcFm8AVV7k [Watch the Video In Full Screen.]


To calculate the roots of a quadratic equation in a C program, we need to break down the formula and calculate smaller parts of it and then combine to get the actual solution.

So lets calculate square root of b2 – 4 * a * c and store it in variable root_part. Also store 2 * a in variable denom. Now calculate ( – b + root_part ) / denom and store it in root1 and ( – b – root_part ) / denom in root2. Output the values of root1 and root2 to the console window.

Calculating Roots of Quadratic Equation In C

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

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

    printf("Enter values of a, b and c\n");
    scanf("%f%f%f", &a, &b, &c);

    if(a == 0)
    {
        printf("If a is zero, equation becomes linear and not quadratic\n");
        printf("Please enter non-zero number for a\n");
    }
    else
    {
        root_part = sqrt(b * b - 4 * a * c);
        denom     = 2 * a;

        root1     = ( - b + root_part ) / denom;
        root2     = ( - b - root_part ) / denom;

        printf("Root1 = %f\nRoot2 = %f", root1, root2);
    }

    return 0;
}

Output 1
Enter values of a, b and c
1
4
4
Root1 = -2.000000
Root2 = -2.000000

Output 2
Enter values of a, b and c
0
4
4
If a is zero, equation becomes linear and not quadratic
Please enter non-zero number for a

Work Space: Cross Verification of Root values
Quadratic Equation: ax2 + bx + c = 0
Let,
a = 1
b = 4
c = 4
i.e., 1x2 + 4x + 4 =0
=> 1x2 + 2x + 2x + 4 = 0
=> x ( x + 2 ) + 2 ( x + 2 ) = 0
=> ( x + 2 ) + ( x + 2 ) = 0
=> x + 2 = 0 AND x + 2 = 0
=> x = -2 AND x = -2

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert