Question 01 of 03

Roots of a Quadratic Equation using If-Else Ladder

Write a Turbo C++ program to find all roots of a quadratic equation (ax^2 + bx + c = 0). Calculate the discriminant (d = b^2 - 4ac) and handle real & equal, real & distinct, and imaginary roots.

C++
#include <iostream.h>
#include <conio.h>
#include <math.h>

void main() {
    float a, b, c, d, r1, r2, realPart, imgPart;

    clrscr();

    cout << "--- Quadratic Equation Solver (ax^2 + bx + c = 0) ---" << endl;
    cout << "Enter coefficient a: ";
    cin >> a;
    cout << "Enter coefficient b: ";
    cin >> b;
    cout << "Enter coefficient c: ";
    cin >> c;

    if (a == 0) {
        cout << "Error: Coefficient 'a' cannot be 0 for a quadratic equation." << endl;
    } else {
        d = (b * b) - (4 * a * c);

        if (d > 0) {
            r1 = (-b + sqrt(d)) / (2 * a);
            r2 = (-b - sqrt(d)) / (2 * a);
            cout << "\nRoots are Real and Distinct:" << endl;
            cout << "Root 1 = " << r1 << endl;
            cout << "Root 2 = " << r2 << endl;
        } else if (d == 0) {
            r1 = -b / (2 * a);
            cout << "\nRoots are Real and Equal:" << endl;
            cout << "Root 1 = Root 2 = " << r1 << endl;
        } else {
            realPart = -b / (2 * a);
            imgPart = sqrt(-d) / (2 * a);
            cout << "\nRoots are Complex and Imaginary:" << endl;
            cout << "Root 1 = " << realPart << " + " << imgPart << "i" << endl;
            cout << "Root 2 = " << realPart << " - " << imgPart << "i" << endl;
        }
    }

    getch();
}
Question 1 of 3