C Program To Solve Quadratic Equation Using Function
A quadratic equation is a fundamental concept in mathematics, typically represented as $ax^2 + bx + c = 0$, where $a$, $b$, and $c$ are coefficients and $a \neq 0$. In this article, you will learn how to write a C program to solve quadratic equations using functions, making the code modular and reusable.
Problem Statement
Solving a quadratic equation involves determining the values of $x$ (roots) that satisfy the equation. The nature and values of these roots depend on the discriminant, $\Delta = b^2 - 4ac$. Implementing this logic in a C program requires handling different cases for the discriminant (positive, zero, or negative) and calculating roots accordingly, which can be elegantly managed using functions.
Example
For the quadratic equation $2x^2 - 8x + 6 = 0$:
Enter coefficient a: 2
Enter coefficient b: -8
Enter coefficient c: 6
Roots are real and distinct.
Root 1 = 3.00
Root 2 = 1.00
Background & Knowledge Prerequisites
To effectively understand this article, readers should have a basic understanding of:
- C Programming Basics: Variables, data types (especially
floatordouble), input/output operations (scanf,printf). - Conditional Statements:
if-else if-elseconstructs for decision-making. - Functions in C: Defining and calling functions, passing arguments.
- Mathematical Functions: Using the
sqrt()function from thelibrary for square root calculations.
Relevant imports needed for the solution include for standard I/O and for mathematical operations.
Use Cases or Case Studies
Quadratic equations appear in various scientific and engineering disciplines. Here are a few practical applications:
- Physics - Projectile Motion: Calculating the time it takes for a projectile launched at an angle to hit a certain height or return to the ground.
- Engineering - Structural Analysis: Determining stress distribution or optimal dimensions in beams and structures.
- Economics - Optimization Problems: Finding profit maximization points where cost and revenue functions are quadratic.
- Electrical Engineering - Circuit Analysis: Solving for current or voltage in certain AC circuits that can be modeled with quadratic relationships.
- Computer Graphics - Ray Tracing: Intersecting a ray with a sphere or other quadratic surfaces to determine visibility.
Solution Approaches
We will implement a single, robust approach that uses a dedicated function to compute and display the roots of a quadratic equation. This function will encapsulate the logic for handling different discriminant values.
Solving Quadratic Equations with Functions
This approach involves creating a void function that takes the coefficients a, b, and c as input. Inside this function, the discriminant is calculated, and based on its value, the appropriate root-finding formula is applied, and the roots are printed.
// Solve Quadratic Equation Using Function
#include <stdio.h>
#include <math.h> // Required for sqrt() function
// Function to calculate and print roots of a quadratic equation
void findRoots(double a, double b, double c) {
double discriminant, root1, root2, realPart, imagPart;
// Step 1: Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Step 2: Check the value of the discriminant and calculate roots accordingly
if (discriminant > 0) {
// Case 1: Discriminant is positive (two distinct real roots)
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct.\\n");
printf("Root 1 = %.2lf\\n", root1);
printf("Root 2 = %.2lf\\n", root2);
} else if (discriminant == 0) {
// Case 2: Discriminant is zero (two identical real roots)
root1 = root2 = -b / (2 * a);
printf("Roots are real and identical.\\n");
printf("Root 1 = Root 2 = %.2lf\\n", root1);
} else {
// Case 3: Discriminant is negative (two complex conjugate roots)
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and conjugate.\\n");
printf("Root 1 = %.2lf + %.2lfi\\n", realPart, imagPart);
printf("Root 2 = %.2lf - %.2lfi\\n", realPart, imagPart);
}
}
int main() {
double a, b, c;
// Step 1: Get coefficients from the user
printf("Enter coefficient a: ");
scanf("%lf", &a);
printf("Enter coefficient b: ");
scanf("%lf", &b);
printf("Enter coefficient c: ");
scanf("%lf", &c);
// Step 2: Handle the case where 'a' is zero (not a quadratic equation)
if (a == 0) {
printf("Coefficient 'a' cannot be zero for a quadratic equation.\\n");
// If a=0, it's a linear equation: bx + c = 0 => x = -c/b
if (b != 0) {
printf("It's a linear equation. Root x = %.2lf\\n", -c / b);
} else if (c == 0) {
printf("Infinite solutions (0 = 0).\\n");
} else {
printf("No solution (0 = -c, where c is non-zero).\\n");
}
} else {
// Step 3: Call the function to find and print the roots
findRoots(a, b, c);
}
return 0;
}
Sample Output
For the input $a=1, b=-5, c=6$:
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
For the input $a=1, b=4, c=4$:
Enter coefficient a: 1
Enter coefficient b: 4
Enter coefficient c: 4
Roots are real and identical.
Root 1 = Root 2 = -2.00
For the input $a=1, b=2, c=5$:
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
Roots are complex and conjugate.
Root 1 = -1.00 + 2.00i
Root 2 = -1.00 - 2.00i
Stepwise Explanation
- Include Headers: The program starts by including
stdio.hfor standard input/output functions andmath.hfor thesqrt()function. findRootsFunction Definition:
- It takes three
doubleparameters:a,b, andc, representing the coefficients. - It declares variables
discriminant,root1,root2,realPart, andimagPartof typedouble. - Discriminant Calculation:
discriminant = b * b - 4 * a * c;calculates the discriminant. - Conditional Logic: An
if-else if-elsestructure checks the value of the discriminant: - If
discriminant > 0: Two distinct real roots are calculated using the formula $(-b \pm \sqrt{\Delta}) / (2a)$ and printed. - If
discriminant == 0: Two identical real roots are calculated using $-b / (2a)$ and printed. - If
discriminant < 0: Two complex conjugate roots are calculated. The real part is $-b / (2a)$, and the imaginary part is $\sqrt{-\Delta} / (2a)$. These are then printed in the formatrealPart ± imagPart i.
mainFunction:
- Declares
a,b, andcvariables to store user input. - User Input: Prompts the user to enter the coefficients
a,b, andcusingprintfand reads them usingscanf. -
a == 0Check: Includes a crucial check to ensureais not zero. Ifais zero, the equation is linear, not quadratic, and the program provides appropriate handling or an error message. - Function Call: If
ais not zero, thefindRoots()function is called witha,b, andcas arguments. - Returns
0to indicate successful execution.
Conclusion
Using functions to solve quadratic equations in C provides a clean, modular, and maintainable approach. It abstracts the complex logic of root calculation into a single block, improving code readability and making it easier to reuse this functionality in larger programs. This method clearly demonstrates how C functions can simplify the development of mathematical computations.
Summary
- Quadratic equations are of the form $ax^2 + bx + c = 0$.
- The discriminant ($\Delta = b^2 - 4ac$) determines the nature of the roots.
- $\Delta > 0$: Two distinct real roots.
- $\Delta = 0$: Two identical real roots.
- $\Delta < 0$: Two complex conjugate roots.
- The C program uses a
voidfunction (findRoots) to encapsulate the logic for calculating and printing roots. - The
mainfunction handles user input and callsfindRootsafter validating the coefficienta. - The
library is essential for thesqrt()function.