Program to Find Roots of a Quadratic Equation in C++
Finding Roots of a Quadratic Equation
A quadratic equation is in the form ax² + bx + c = 0. The roots of this equation can be real or complex depending on the discriminant (D = b² - 4ac).
We will explore three different methods to find the roots of a quadratic equation in C++.
Method 1: Using the Quadratic Formula
This method uses the quadratic formula: x = (-b ± sqrt(b² - 4ac)) / (2a).
#include <iostream>
#include <cmath>
using namespace std;
void findRoots(int a, int b, int c) {
float discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
float root1 = (-b + sqrt(discriminant)) / (2 * a);
float root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "Real and Distinct Roots: " << root1 << ", " << root2 << endl;
} else if (discriminant == 0) {
float root = -b / (2.0 * a);
cout << "Real and Equal Roots: " << root << endl;
} else {
float realPart = -b / (2.0 * a);
float imagPart = sqrt(-discriminant) / (2.0 * a);
cout << "Complex Roots: " << realPart << " + " << imagPart << "i, "
<< realPart << " - " << imagPart << "i" << endl;
}
}
int main() {
int a, b, c;
cout << "Enter coefficients a, b, and c: ";
cin >> a >> b >> c;
findRoots(a, b, c);
return 0;
}
Output: Real and Distinct Roots: 2.00, 1.00
Method 2: Using Factorization
Factorization is an alternative method where we break the middle term to find the roots.
#include <iostream>
using namespace std;
void findRootsByFactorization(int a, int b, int c) {
bool found = false;
for (int i = -100; i <= 100; i++) {
for (int j = -100; j <= 100; j++) {
if (i * j == a * c && i + j == b) {
cout << "Roots are: " << -j << "/" << a << " and " << -i << "/" << a << endl;
found = true;
break;
}
}
if (found) break;
}
if (!found) cout << "Cannot be factorized easily." << endl;
}
int main() {
int a, b, c;
cout << "Enter coefficients a, b, and c: ";
cin >> a >> b >> c;
findRootsByFactorization(a, b, c);
return 0;
}
Output: Roots are: 2/1 and 3/1
Method 3: Using Recursion
This method recursively calculates the discriminant and finds the roots.
#include <iostream>
#include <cmath>
using namespace std;
void findRootsRecursive(int a, int b, int c, float d) {
if (d > 0) {
float root1 = (-b + sqrt(d)) / (2 * a);
float root2 = (-b - sqrt(d)) / (2 * a);
cout << "Real and Distinct Roots: " << root1 << ", " << root2 << endl;
} else if (d == 0) {
float root = -b / (2.0 * a);
cout << "Real and Equal Roots: " << root << endl;
} else {
float realPart = -b / (2.0 * a);
float imagPart = sqrt(-d) / (2.0 * a);
cout << "Complex Roots: " << realPart << " + " << imagPart << "i, "
<< realPart << " - " << imagPart << "i" << endl;
}
}
void calculateDiscriminant(int a, int b, int c) {
float d = b * b - 4 * a * c;
findRootsRecursive(a, b, c, d);
}
int main() {
int a, b, c;
cout << "Enter coefficients a, b, and c: ";
cin >> a >> b >> c;
calculateDiscriminant(a, b, c);
return 0;
}
Output: Complex Roots: -1.00 + 2.00i, -1.00 - 2.00i