C++ Program To Find Roots Of Quadratic Equation Using Class
In this article, you will learn how to efficiently calculate the roots of a quadratic equation using a C++ class, ensuring a structured and reusable approach to solve this common mathematical problem.
Problem Statement
A quadratic equation is a polynomial equation of the second degree, typically expressed as $ax^2 + bx + c = 0$, where $a$, $b$, and $c$ are coefficients and $a \neq 0$. The roots of this equation are the values of $x$ that satisfy it. Finding these roots is a fundamental task in mathematics and engineering, but it requires careful handling of different scenarios based on the discriminant.
Example
Consider the quadratic equation $x^2 - 5x + 6 = 0$. Here, $a=1$, $b=-5$, $c=6$. The roots for this equation are $x=2$ and $x=3$.
Background & Knowledge Prerequisites
To understand and implement the solution, a basic understanding of the following concepts is helpful:
- C++ Fundamentals: Variables, data types, operators, conditional statements (if-else), and input/output operations.
- Object-Oriented Programming (OOP) in C++: Classes, objects, member variables (attributes), member functions (methods), and constructors.
- Basic Algebra: Understanding quadratic equations, the quadratic formula, and the concept of a discriminant ($\Delta = b^2 - 4ac$).
- Mathematical Functions: Using
sqrt()for square root andpow()for power from thelibrary.
Use Cases or Case Studies
Quadratic equations and their root calculations are crucial in various fields:
- Physics: Calculating projectile motion, understanding oscillations, and determining trajectories.
- Engineering: Designing structures, analyzing electrical circuits, and solving optimization problems in mechanical engineering.
- Economics: Modeling supply and demand curves, profit maximization, and other economic forecasting.
- Computer Graphics: Ray tracing and collision detection in simulations and game development often involve solving quadratic equations.
- Data Science: Certain statistical models and curve fitting algorithms rely on finding roots of polynomial equations.
Solution Approaches
We will implement a robust solution using a C++ class to encapsulate the quadratic equation's properties and root-finding logic.
Approach 1: Encapsulating Quadratic Equation Logic in a Class
This approach defines a QuadraticEquation class that stores the coefficients $a, b, c$ and provides a method to calculate and display the roots based on the discriminant.
One-line summary: A C++ class designed to store coefficients of a quadratic equation and compute its real or complex roots.
Code Example:
// Quadratic Equation Roots using Class
#include <iostream> // For input/output operations
#include <cmath> // For sqrt() and pow() functions
#include <iomanip> // For setprecision()
using namespace std;
// Define a class to represent a Quadratic Equation
class QuadraticEquation {
private:
double a, b, c; // Coefficients of the quadratic equation
public:
// Constructor to initialize the coefficients
QuadraticEquation(double coeffA, double coeffB, double coeffC) {
a = coeffA;
b = coeffB;
c = coeffC;
}
// Method to calculate and display the roots
void findRoots() {
if (a == 0) {
cout << "Invalid quadratic equation: 'a' cannot be zero." << endl;
return;
}
double discriminant = b * b - 4 * a * c;
double root1, root2;
cout << fixed << setprecision(2); // Format output to 2 decimal places
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "Roots are real and distinct." << endl;
cout << "Root 1 = " << root1 << endl;
cout << "Root 2 = " << root2 << endl;
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
cout << "Roots are real and same." << endl;
cout << "Root 1 = Root 2 = " << root1 << endl;
} else { // discriminant < 0
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
cout << "Roots are complex and distinct." << endl;
cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl;
cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
}
}
};
int main() {
// Step 1: Declare variables for coefficients
double coeff_a, coeff_b, coeff_c;
// Step 2: Prompt user for input
cout << "Enter coefficient a: ";
cin >> coeff_a;
cout << "Enter coefficient b: ";
cin >> coeff_b;
cout << "Enter coefficient c: ";
cin >> coeff_c;
// Step 3: Create an object of QuadraticEquation class
QuadraticEquation eq(coeff_a, coeff_b, coeff_c);
// Step 4: Call the findRoots method to calculate and display roots
eq.findRoots();
return 0;
}
Sample Output:
- Case 1: Real and Distinct Roots (e.g., $x^2 - 5x + 6 = 0$)
Enter coefficient a: 1 Enter coefficient b: -5 Enter coefficient c: 6 Roots are real and distinct. Root 1 = 3.00 Root 2 = 2.00
- Case 2: Real and Same Roots (e.g., $x^2 + 4x + 4 = 0$)
Enter coefficient a: 1 Enter coefficient b: 4 Enter coefficient c: 4 Roots are real and same. Root 1 = Root 2 = -2.00
- Case 3: Complex and Distinct Roots (e.g., $x^2 + 2x + 5 = 0$)
Enter coefficient a: 1 Enter coefficient b: 2 Enter coefficient c: 5 Roots are complex and distinct. Root 1 = -1.00 + 2.00i Root 2 = -1.00 - 2.00i
- Case 4: Invalid input (a=0)
Enter coefficient a: 0 Enter coefficient b: 5 Enter coefficient c: 6 Invalid quadratic equation: 'a' cannot be zero.
Stepwise Explanation:
- Include Headers: The program starts by including
for input/output,for mathematical functions likesqrt(), andfor output formatting. - Class Definition (
QuadraticEquation):- Private Members:
double a, b, c;are declared as private to store the coefficients. This encapsulates the data, meaning it can only be accessed or modified through the class's public methods.
- Private Members:
QuadraticEquation(double coeffA, double coeffB, double coeffC) is a special method called when an object of the class is created. It initializes the a, b, and c member variables with the provided values.findRoots()): This function performs the core logic.a check: It first checks if a is zero. If so, it's not a quadratic equation, and an error message is printed.double discriminant = b * b - 4 * a * c; calculates the discriminant.discriminant > 0 (Real and Distinct Roots): Calculates two distinct real roots using the quadratic formula: $x = (-b \pm \sqrt{\Delta}) / (2a)$.discriminant == 0 (Real and Same Roots): Calculates two identical real roots: $x = -b / (2a)$.discriminant < 0 (Complex and Distinct Roots): Calculates two complex conjugate roots. The real part is -b / (2a), and the imaginary part is sqrt(-discriminant) / (2a).cout << fixed << setprecision(2); is used to display the roots with two decimal places for better readability.main()Function:- Input: It prompts the user to enter the coefficients $a, b, c$.
QuadraticEquation eq(coeff_a, coeff_b, coeff_c); creates an object named eq of the QuadraticEquation class, passing the user-entered coefficients to its constructor.eq.findRoots(); invokes the findRoots() method on the eq object, which then calculates and prints the roots.Conclusion
By implementing the quadratic equation root-finding logic within a C++ class, we achieve a highly organized, maintainable, and reusable solution. This approach encapsulates the data (coefficients) and behavior (root calculation) together, aligning with object-oriented principles. It effectively handles all three cases of real distinct, real equal, and complex roots based on the discriminant.
Summary
- A
QuadraticEquationclass encapsulates coefficients and root-finding logic. - The constructor initializes
a,b, andc. - The
findRoots()method calculates roots based on the discriminant. - Discriminant (
b^2 - 4ac) determines the nature of the roots: - Positive: Two distinct real roots.
- Zero: Two identical real roots.
- Negative: Two distinct complex conjugate roots.
- Input validation checks if coefficient
ais zero. - Output is formatted for clarity using
setprecision.