C++ Program To Find The Roots Of Quadratic Equation

Last Updated : 3 Sep, 2026

A quadratic equation is a polynomial equation of degree two, commonly written as ax² + bx + c = 0. This program calculates the roots of the equation using a simple mathematical approach.

  • Handles real and complex roots.
  • Also checks whether the given equation is quadratic.

Examples

Input :  a = 1, b = -2, c = 1
Output:  Roots are real and same
              1

Input :  a = 1, b = 7, c = 12
Output:  Roots are real and different
              -3, -4

Input :  a = 1, b = 1, c = 1
Output:  Roots are complex 
              -0.5 + i1.73205
              -0.5 - i1.73205  

Quadratic Equation in C++

Below is the direct formula for finding the roots of the quadratic equation.

Formula for finding the roots

The value D = b² - 4ac is called the discriminant and determines the type of roots.

There are the following important cases:

1. If b*b < 4*a*c, then roots are complex (not real).
Example: Roots of x2 + x + 1, roots are: -0.5 + i0.86603 and -0.5 - i0.86603

2. If b*b == 4*a*c, then roots are real and both roots are same.
Example: Roots of x2 - 2x + 1 are 1 and 1

3. If b*b > 4*a*c, then roots are real and different.
Example: Roots of x2 - 7x - 12 are 3 and 4

Roots of Quadratic Equation Flowchart: 

Roots of Quadratic Equation Flowchart

The program first calculates the discriminant and then uses it to determine and print the roots.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find roots
void findRoots(int a, int b, int c)
{
    // A quadratic equation must have a non-zero
    // coefficient of x^2.
    if (a == 0) {
        cout << "Not a quadratic equation";
        return;
    }

    int d = b * b - 4 * a * c;

    if (d > 0) {
        double root1 = (-b + sqrt(d)) / (2.0 * a);
        double root2 = (-b - sqrt(d)) / (2.0 * a);

        cout << "Roots are real and different: "
             << root1 << ", " << root2;
    }
    else if (d == 0) {
        double root = -b / (2.0 * a);

        cout << "Roots are real and same: "
             << root;
    }
    else {
        double realPart = -b / (2.0 * a);
        double imaginaryPart = sqrt(-d) / (2.0 * a);

        cout << "Roots are complex: "
             << realPart << " + i" << imaginaryPart
             << ", " << realPart << " - i" << imaginaryPart;
    }
}

// Driver code
int main()
{
    int a = 1, b = -7, c = 12;

    findRoots(a, b, c);

    return 0;
}

Output
Roots are real and different: 4, 3

Explanation

  • Checks whether a is zero, as the equation is not quadratic in that case.
  • Calculates the discriminant b * b - 4 * a * c.
  • Uses the discriminant to calculate real, equal, or complex roots.
Comment