Write Ac Program To Calculate Quadratic Equation Using Switch Case
Quadratic equations are fundamental in mathematics, appearing in various scientific and engineering disciplines. Solving them involves finding the values of the variable that satisfy the equation. This process can lead to different types of solutions, depending on a specific part of the equation known as the discriminant. In this article, you will learn how to calculate the roots of a quadratic equation using a switch case structure in C.
Problem Statement
A quadratic equation is expressed in the form $ax^2 + bx + c = 0$, where $a$, $b$, and $c$ are coefficients, and $a \neq 0$. The roots of this equation (the values of $x$ that satisfy it) depend on the value of the discriminant, $\Delta = b^2 - 4ac$. Based on the discriminant's value, there are three main scenarios for the roots:
- $\Delta > 0$: Two distinct and real roots.
- $\Delta = 0$: Two real and equal roots.
- $\Delta < 0$: Two complex conjugate roots.
The challenge is to implement a C program that takes coefficients $a$, $b$, and $c$ as input and calculates the appropriate roots based on these conditions using a switch statement.
Example
Consider the equation $x^2 - 5x + 6 = 0$. Here, $a=1$, $b=-5$, $c=6$. The discriminant $\Delta = (-5)^2 - 4(1)(6) = 25 - 24 = 1$. Since $\Delta > 0$, there are two distinct real roots. The program should output something similar to:
Enter coefficients a, b and c: 1 -5 6
Discriminant = 1.00
Root 1 = 3.00
Root 2 = 2.00
Background & Knowledge Prerequisites
To effectively understand and implement the solution, readers should be familiar with:
- C Programming Basics: Variables, data types (especially
floatordouble), input/output operations (scanf,printf). - Conditional Statements: Basic understanding of
if-elseconstructs, which are conceptually related to how we'll categorize the discriminant for theswitchstatement. - Mathematical Functions: Knowledge of
sqrt()for square roots, which is part of themath.hlibrary. - Quadratic Equation Formula: The general formulas for calculating roots based on the discriminant.
To set up your environment, ensure you have a C compiler (like GCC) installed. You will need to link the math library using the -lm flag during compilation if using sqrt():
gcc your_program.c -o your_program -lm
Use Cases or Case Studies
Quadratic equations have a wide range of applications across different fields:
- Physics: Calculating projectile motion trajectories, determining equilibrium points in mechanical systems, or analyzing oscillatory motion.
- Engineering: Designing parabolic antennas, optimizing structural components, or solving problems in electrical circuits.
- Economics: Modeling supply and demand curves, profit maximization problems, or economic growth models where relationships are non-linear.
- Computer Graphics: Used in ray tracing to find intersections between rays and spheres or other quadratic surfaces.
- Optimization Problems: Finding maximum or minimum values in scenarios that can be modeled by quadratic functions, such as maximizing the area of a field with a fixed perimeter.
Solution Approaches
The most common approach to solving quadratic equations involves calculating the discriminant and then applying the appropriate formula for roots. To incorporate a switch statement, we'll categorize the discriminant's nature into distinct integer values.
Solving Quadratic Equations with switch Case
This approach calculates the discriminant and categorizes its value (positive, zero, or negative) into an integer status. A switch statement then uses this status to compute and print the corresponding roots.
// Calculate Quadratic Equation Roots
#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;
double realPart, imagPart;
int status_indicator;
// Step 2: Get input from the user for coefficients
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
// Step 3: Check if 'a' is zero, as it's not a quadratic equation then
if (a == 0) {
printf("Error: 'a' cannot be zero for a quadratic equation.\\n");
// For a=0, it becomes a linear equation bx + c = 0, x = -c/b
if (b != 0) {
printf("It's a linear equation. Root = %.2lf\\n", -c / b);
} else {
printf("Invalid coefficients (a=0, b=0).\\n");
}
return 1; // Indicate an error
}
// Step 4: Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Step 5: Determine the status based on discriminant value
if (discriminant > 0) {
status_indicator = 1; // Real and distinct roots
} else if (discriminant == 0) {
status_indicator = 0; // Real and equal roots
} else {
status_indicator = -1; // Complex roots
}
// Step 6: Use switch case to handle different root types
switch (status_indicator) {
case 1: // Case for real and distinct roots (discriminant > 0)
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Discriminant = %.2lf\\n", discriminant);
printf("Root 1 = %.2lf\\n", root1);
printf("Root 2 = %.2lf\\n", root2);
break;
case 0: // Case for real and equal roots (discriminant == 0)
root1 = -b / (2 * a);
printf("Discriminant = %.2lf\\n", discriminant);
printf("Root 1 = Root 2 = %.2lf\\n", root1);
break;
case -1: // Case for complex roots (discriminant < 0)
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Discriminant = %.2lf\\n", discriminant);
printf("Root 1 = %.2lf + %.2lfi\\n", realPart, imagPart);
printf("Root 2 = %.2lf - %.2lfi\\n", realPart, imagPart);
break;
}
return 0;
}
Sample Output
Scenario 1: Real and Distinct Roots (e.g., $x^2 - 5x + 6 = 0$)
Enter coefficients a, b and c: 1 -5 6
Discriminant = 1.00
Root 1 = 3.00
Root 2 = 2.00
Scenario 2: Real and Equal Roots (e.g., $x^2 + 4x + 4 = 0$)
Enter coefficients a, b and c: 1 4 4
Discriminant = 0.00
Root 1 = Root 2 = -2.00
Scenario 3: Complex Roots (e.g., $x^2 + 2x + 5 = 0$)
Enter coefficients a, b and c: 1 2 5
Discriminant = -16.00
Root 1 = -1.00 + 2.00i
Root 2 = -1.00 - 2.00i
Scenario 4: Invalid Input (a=0)
Enter coefficients a, b and c: 0 2 4
Error: 'a' cannot be zero for a quadratic equation.
It's a linear equation. Root = -2.00
Stepwise Explanation
- Include Headers: The program starts by including
stdio.hfor input/output functions andmath.hfor thesqrt()function. - Declare Variables:
doubletype variables are declared for coefficients (a,b,c), thediscriminant, theroots(root1,root2), and parts of complex roots (realPart,imagPart). Anintvariablestatus_indicatoris used to categorize the discriminant. - Get Input: The program prompts the user to enter the coefficients $a$, $b$, and $c$, which are read using
scanf(). - Handle
a = 0: A quadratic equation requiresato be non-zero. The program checks this condition and provides an appropriate message and handles it as a linear equation if possible. - Calculate Discriminant: The discriminant ($\Delta = b^2 - 4ac$) is calculated and stored in the
discriminantvariable. - Determine Status: An
if-else if-elsestructure evaluates thediscriminant:
- If
discriminant > 0,status_indicatoris set to1. - If
discriminant == 0,status_indicatoris set to0. - If
discriminant < 0,status_indicatoris set to-1.
switch statement.- Use
switch: The program then uses aswitchstatement based onstatus_indicatorto execute the correct block of code for calculating the roots:
-
case 1(Real and Distinct): Calculatesroot1androot2using the formula $x = \frac{-b \pm \sqrt{\Delta}}{2a}$ and prints them. -
case 0(Real and Equal): Calculatesroot1(which is equal toroot2) using $x = \frac{-b}{2a}$ and prints the single root. -
case -1(Complex Roots): Calculates therealPart($ \frac{-b}{2a}$) andimagPart($ \frac{\sqrt{-\Delta}}{2a}$) and prints the roots in the formatrealPart ± imagParti. Note thatsqrt()expects a non-negative argument, sosqrt(-discriminant)is used whendiscriminantis negative.
- Return: The
mainfunction returns0on successful execution.
Conclusion
Calculating the roots of a quadratic equation is a common task in programming that effectively demonstrates conditional logic. By categorizing the discriminant into distinct states, a switch statement provides a clear and organized way to handle the three different scenarios for the roots: real and distinct, real and equal, or complex conjugate pairs. This approach highlights how switch can be used even for conditions that are initially continuous by first mapping them to discrete values.
Summary
- A quadratic equation is $ax^2 + bx + c = 0$, where $a \neq 0$.
- The discriminant $\Delta = b^2 - 4ac$ determines the nature of the roots.
- $\Delta > 0$: Two distinct real roots.
- $\Delta = 0$: Two real and equal roots.
- $\Delta < 0$: Two complex conjugate roots.
- A
switchstatement can be used by first categorizing the discriminant's nature into an integer status. - The
math.hlibrary (specificallysqrt()) is essential for root calculation. Remember to link with-lmduring compilation.