Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to write a C program to find the roots of a quadratic equation?
A quadratic equation is of the form ax² + bx + c = 0, where a, b, and c are coefficients and a ? 0. The roots can be found using the quadratic formula, and the nature of roots depends on the discriminant value.
Syntax
r1 = (-b + sqrt(discriminant)) / (2 * a); r2 = (-b - sqrt(discriminant)) / (2 * a);
Mathematical Formula
The quadratic formula is −
r? = (-b + ?(b² - 4ac)) / (2a)
r? = (-b - ?(b² - 4ac)) / (2a)
Where the discriminant (d) = b² - 4ac determines the nature of roots −
- If d > 0: Two distinct real roots
- If d = 0: Two equal real roots
- If d
Algorithm
- Read coefficients a, b, c from user
- Calculate discriminant d = b² - 4ac
- Check the value of discriminant
- Apply quadratic formula based on discriminant value
- Display the roots
Flowchart
Example
Here's a complete C program that finds the roots of a quadratic equation −
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, discriminant, root1, root2;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
// Calculate discriminant
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
// Two distinct real roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Two distinct real roots: %.2f and %.2f<br>", root1, root2);
}
else if (discriminant == 0) {
// Two equal real roots
root1 = root2 = -b / (2 * a);
printf("Two equal real roots: %.2f and %.2f<br>", root1, root2);
}
else {
// Complex roots
float realPart = -b / (2 * a);
float imagPart = sqrt(-discriminant) / (2 * a);
printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi<br>",
realPart, imagPart, realPart, imagPart);
}
return 0;
}
Output
Case 1: Two distinct real roots Enter coefficients a, b and c: 1 -5 6 Two distinct real roots: 3.00 and 2.00 Case 2: Two equal real roots Enter coefficients a, b and c: 1 -2 1 Two equal real roots: 1.00 and 1.00 Case 3: Complex roots Enter coefficients a, b and c: 1 2 5 Complex roots: -1.00 + 2.00i and -1.00 - 2.00i
Key Points
- Always include
<math.h>header for thesqrt()function - Check if coefficient
ais non-zero to ensure it's a quadratic equation - Use proper operator precedence with parentheses in the quadratic formula
- Handle all three cases based on discriminant value
Conclusion
This program demonstrates how to solve quadratic equations in C by calculating the discriminant and applying the quadratic formula. It handles all possible cases including real, equal, and complex roots effectively.
Advertisements
