Open In App

C Program for Quadratic Equation Roots

Last Updated : 14 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn to write a C program to find the roots of the quadratic equation.

Quadratic Equation is polynomial equations that have a degree of two, which implies that the highest power of the function is two. The quadratic equation is represented by ax2 + bx + c where a, b, and c are real numbers and constants, and a ≠ 0. The root of the quadratic equations is a value of x that satisfies the equation.

How to Find Quadratic Equation Roots?

The Discriminant is the quantity that is used to determine the nature of roots:

Discriminant(D) = b2 - 4ac;

Based on the nature of the roots, we can use the given formula to find the roots of the quadratic equation.

1. If D > 0, Roots are real and different

root1 = \dfrac{-b +\sqrt{(b^2 - 4ac)}}{2a}

root2 = \dfrac{-b -\sqrt{(b^2 - 4ac)}}{2a}

2. If D = 0, Roots are real and the same

root1 = root2 = \dfrac{-b}{2a}

3.If D < 0, Roots are complex 

root1 = \dfrac{-b}{2a} + \dfrac{i\sqrt{-(b^2 -4ac)}}{2a}

root2 = \dfrac{-b}{2a} - \dfrac{i\sqrt{-(b^2 -4ac)}}{2a}

Program to Find Roots of a Quadratic Equation

C

// C program to find roots of
// a quadratic equation
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
  
// Prints roots of quadratic
// equation ax*2 + bx + x
void findRoots(int a, int b, int c)
{
    // If a is 0, then equation is
    // not quadratic, but linear
    if (a == 0) {
        printf("Invalid");
        return;
    }
  
    int d = b * b - 4 * a * c;
    double sqrt_val = sqrt(abs(d));
  
    if (d > 0) {
        printf("Roots are real and different\n");
        printf("%f\n%f", (double)(-b + sqrt_val) / (2 * a),
               (double)(-b - sqrt_val) / (2 * a));
    }
    else if (d == 0) {
        printf("Roots are real and same\n");
        printf("%f", -(double)b / (2 * a));
    }
    else // d < 0
    {
        printf("Roots are complex\n");
        printf("%f + i%f\n%f - i%f", -(double)b / (2 * a),
               sqrt_val / (2 * a), -(double)b / (2 * a),
               sqrt_val / (2 * a));
    }
}
  
// Driver code
int main()
{
    int a = 1, b = -7, c = 12;
  
    // Function call
    findRoots(a, b, c);
    return 0;
}

                    


Output

Roots are real and different
4.000000
3.000000

Complexity Analysis

Time Complexity: O(log(D)), where D is the discriminant of the given quadratic equation.

Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads