C Program To Find Roots Of Quadratic Equation Using Switch Statement
Finding the roots of a quadratic equation is a fundamental mathematical problem with diverse applications. In this article, you will learn how to write a C program that calculates these roots by systematically handling different scenarios using a switch statement.
Problem Statement
A quadratic equation is expressed in the form ax^2 + bx + c = 0, where a, b, and c are coefficients and a ≠ 0. The challenge lies in computing the values of x (the roots) that satisfy this equation, considering that these roots can be real and distinct, real and equal, or complex, depending on the discriminant. Accurately determining and displaying these root types is crucial in many computational tasks.
Example
Consider the quadratic equation 2x^2 + 5x + 2 = 0.
The program calculates the discriminant D = b^2 - 4ac.
For a=2, b=5, c=2, D = 5^2 - 4 * 2 * 2 = 25 - 16 = 9.
Since D > 0, there are two distinct real roots.
The roots are calculated as x1 = (-b + sqrt(D)) / (2a) and x2 = (-b - sqrt(D)) / (2a).
x1 = (-5 + sqrt(9)) / (2 * 2) = (-5 + 3) / 4 = -2 / 4 = -0.5
x2 = (-5 - sqrt(9)) / (2 * 2) = (-5 - 3) / 4 = -8 / 4 = -2.0
The program output for this equation would be:
Enter coefficients a, b and c: 2 5 2
Root1 = -0.50
Root2 = -2.00
Background & Knowledge Prerequisites
To understand and implement this solution, readers should have a basic grasp of:
- C Programming Basics: Understanding variables, data types (especially
floatordouble), input/output operations (printf,scanf). - Conditional Statements: Familiarity with
if-elsestatements, which are conceptually similar to how we determine theswitchcase. - Switch Statement: Knowledge of how to use the
switchstatement for multi-way branching based on an integer expression. - Mathematical Concepts:
- Quadratic Equation: The formula
ax^2 + bx + c = 0. - Discriminant: The value
D = b^2 - 4ac, which determines the nature of the roots. - Square Root Function: Using
sqrt()frommath.hfor calculating square roots. - Complex Numbers: Basic understanding of the
i(iota) notation for imaginary parts.
Required Imports: The program will require the following header files:
-
stdio.h: For standard input/output functions likeprintfandscanf. -
math.h: For mathematical functions likesqrt()andpow().
Use Cases or Case Studies
Quadratic equations and their roots appear in various real-world scenarios:
- Physics (Projectile Motion): Calculating the time it takes for a projectile launched at a certain angle and velocity to reach a specific height. The path is often parabolic, described by a quadratic equation.
- Engineering Design: Determining the dimensions of structures or components to meet certain criteria, such as finding the optimal cross-sectional area for a beam under load or designing antennas.
- Economics and Finance: Modeling cost functions, profit maximization, or break-even analysis, where relationships between variables can be quadratic. For instance, calculating the production quantity that yields maximum profit.
- Computer Graphics and Game Development: Calculating collision points between objects (e.g., a bullet's trajectory intersecting a target's path) or determining the trajectory for throwing objects in a game.
- Signal Processing: Analyzing filters or oscillations in electrical circuits (e.g., RLC circuits), where the characteristic equations are often quadratic.
Solution Approach: Using the Switch Statement
This approach calculates the discriminant of the quadratic equation and uses a derived integer value to control a switch statement, allowing for distinct handling of cases involving distinct real, equal real, and complex roots.
Approach Title: Determining Roots with a Switch Statement
One-line Summary: We calculate the discriminant, convert its nature (positive, zero, negative) into an integer case identifier, and then use a switch statement to compute and display the roots accordingly.
Code Example:
// Find Roots of Quadratic Equation using Switch Statement
#include <stdio.h>
#include <math.h> // Required for sqrt() function
int main() {
// Step 1: Declare variables for coefficients and roots
double a, b, c;
double discriminant, root1, root2, realPart, imagPart;
int choice; // To control the switch statement
// Step 2: Prompt user for coefficients
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
// Step 3: Handle the case where 'a' is zero (not a quadratic equation)
if (a == 0) {
if (b == 0) {
if (c == 0) {
printf("Infinite solutions (0=0).\\n");
} else {
printf("No solution (c=0, where c!=0).\\n");
}
} else {
// Linear equation: bx + c = 0 => x = -c/b
root1 = -c / b;
printf("This is a linear equation.\\n");
printf("Root = %.2lf\\n", root1);
}
return 0; // Exit if not a quadratic equation
}
// Step 4: Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Step 5: Determine the 'choice' value for the switch statement
if (discriminant > 0) {
choice = 1; // Distinct real roots
} else if (discriminant == 0) {
choice = 0; // Equal real roots
} else {
choice = -1; // Complex roots
}
// Step 6: Use switch statement to find roots based on 'choice'
switch (choice) {
case 1: // Discriminant > 0 (Distinct Real Roots)
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct.\\n");
printf("Root1 = %.2lf\\n", root1);
printf("Root2 = %.2lf\\n", root2);
break;
case 0: // Discriminant = 0 (Equal Real Roots)
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal.\\n");
printf("Root1 = Root2 = %.2lf\\n", root1);
break;
case -1: // Discriminant < 0 (Complex Roots)
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and distinct.\\n");
printf("Root1 = %.2lf + %.2lfi\\n", realPart, imagPart);
printf("Root2 = %.2lf - %.2lfi\\n", realPart, imagPart);
break;
}
return 0;
}
Sample Output:
- Distinct Real Roots (Discriminant > 0):
Enter coefficients a, b and c: 1 -5 6
Roots are real and distinct.
Root1 = 3.00
Root2 = 2.00
(Equation: x^2 - 5x + 6 = 0, Roots: x=3, x=2)
- Equal Real Roots (Discriminant = 0):
Enter coefficients a, b and c: 1 -4 4
Roots are real and equal.
Root1 = Root2 = 2.00
(Equation: x^2 - 4x + 4 = 0, Root: x=2)
- Complex Roots (Discriminant < 0):
Enter coefficients a, b and c: 1 2 5
Roots are complex and distinct.
Root1 = -1.00 + 2.00i
Root2 = -1.00 - 2.00i
(Equation: x^2 + 2x + 5 = 0, Roots: x = -1 ± 2i)
- Linear Equation (a = 0):
Enter coefficients a, b and c: 0 2 4
This is a linear equation.
Root = -2.00
(Equation: 2x + 4 = 0, Root: x=-2)
Stepwise Explanation:
- Include Headers: The program starts by including
stdio.hfor input/output andmath.hfor thesqrt()function. - Declare Variables:
doubletype variablesa, b, care declared for the coefficients,discriminant,root1, root2,realPart,imagPartfor calculations and results. Anintvariablechoiceis crucial for theswitchstatement. - Get Input: The program prompts the user to enter the coefficients
a,b, andcusingscanf(). - Handle Non-Quadratic Case: An initial
if (a == 0)check determines if the equation is truly quadratic. Ifais 0, it might be a linear equation (bx + c = 0) or have no solution/infinite solutions, which is handled separately. The program exits ifais 0 after processing the linear case. - Calculate Discriminant: The discriminant
D = b^2 - 4acis calculated and stored in thediscriminantvariable. - Set Switch
choice: Anif-else if-elseblock is used to assign an integer value tochoicebased on the discriminant's sign:
-
choice = 1ifdiscriminant > 0(distinct real roots). -
choice = 0ifdiscriminant == 0(equal real roots). -
choice = -1ifdiscriminant < 0(complex roots).
- Execute
switchStatement: Theswitch (choice)statement then directs program flow to the appropriatecase:
-
case 1(Distinct Real Roots): -
root1 = (-b + sqrt(discriminant)) / (2 * a) -
root2 = (-b - sqrt(discriminant)) / (2 * a) - The two distinct real roots are calculated using the quadratic formula and printed.
-
case 0(Equal Real Roots): -
root1 = root2 = -b / (2 * a) - Since
sqrt(0)is 0, both roots are identical and calculated as-b / (2a). -
case -1(Complex Roots): -
realPart = -b / (2 * a) -
imagPart = sqrt(-discriminant) / (2 * a) - The real and imaginary parts are calculated. Note that
sqrt()is applied to-discriminantbecausediscriminantis negative in this case, making-discriminantpositive. The roots are then printed in the formatrealPart ± imagPart i.
breakStatements: Eachcaseends with abreakstatement to exit theswitchblock.- Return 0: The
mainfunction returns0, indicating successful execution.
Conclusion
Successfully finding the roots of a quadratic equation involves understanding the role of the discriminant. By employing a switch statement, we can elegantly manage the three distinct scenarios for the roots—real and distinct, real and equal, or complex—leading to a clear and maintainable C program. This method provides a structured way to handle conditional logic, which is a fundamental skill in programming.
Summary
- A quadratic equation
ax^2 + bx + c = 0has roots determined by its discriminantD = b^2 - 4ac. - A C program can use
if-elsestatements to categorize the discriminant's value, which then drives aswitchstatement. -
D > 0: Two distinct real roots. -
D = 0: Two equal real roots. -
D < 0: Two complex conjugate roots. - The
switchstatement provides a clean way to implement multi-way branching for each root type.