Program to Find Roots of a Quadratic Equation in C
Finding Roots of a Quadratic Equation
A quadratic equation is in the form ax² + bx + c = 0. The roots of this equation can be real or complex depending on the discriminant (D = b² - 4ac).
We will explore three different methods to find the roots of a quadratic equation in C.
Method 1: Using the Quadratic Formula
This method uses the quadratic formula: x = (-b ± sqrt(b² - 4ac)) / (2a).
#include <stdio.h> #include <math.h> void findRoots(int a, int b, int c) { float discriminant = b * b - 4 * a * c; if (discriminant > 0) { float root1 = (-b + sqrt(discriminant)) / (2 * a); float root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Real and Distinct Roots: %.2f, %.2f\n", root1, root2); } else if (discriminant == 0) { float root = -b / (2 * a); printf("Real and Equal Roots: %.2f\n", root); } else { float realPart = -b / (2 * a); float imagPart = sqrt(-discriminant) / (2 * a); printf("Complex Roots: %.2f + %.2fi, %.2f - %.2fi\n", realPart, imagPart, realPart, imagPart); } } int main() { int a, b, c; printf("Enter coefficients a, b, and c: "); scanf("%d %d %d", &a, &b, &c); findRoots(a, b, c); return 0; }
Output: Real and Distinct Roots: 2.00, 1.00
Method 2: Using Factorization
Factorization is an alternative method where we break the middle term to find the roots.
#include <stdio.h> void findRootsByFactorization(int a, int b, int c) { int found = 0; for (int i = -100; i <= 100; i++) { for (int j = -100; j <= 100; j++) { if (i * j == a * c && i + j == b) { printf("Roots are: %d/%d and %d/%d\n", -j, a, -i, a); found = 1; break; } } if (found) break; } if (!found) printf("Cannot be factorized easily.\n"); } int main() { int a, b, c; printf("Enter coefficients a, b, and c: "); scanf("%d %d %d", &a, &b, &c); findRootsByFactorization(a, b, c); return 0; }
Output: Roots are: 2/1 and 3/1
Method 3: Using Recursion
This method recursively calculates the discriminant and finds the roots.
#include <stdio.h> #include <math.h> void findRootsRecursive(int a, int b, int c, float d) { if (d > 0) { float root1 = (-b + sqrt(d)) / (2 * a); float root2 = (-b - sqrt(d)) / (2 * a); printf("Real and Distinct Roots: %.2f, %.2f\n", root1, root2); } else if (d == 0) { float root = -b / (2 * a); printf("Real and Equal Roots: %.2f\n", root); } else { float realPart = -b / (2 * a); float imagPart = sqrt(-d) / (2 * a); printf("Complex Roots: %.2f + %.2fi, %.2f - %.2fi\n", realPart, imagPart, realPart, imagPart); } } void calculateDiscriminant(int a, int b, int c) { float d = b * b - 4 * a * c; findRootsRecursive(a, b, c, d); } int main() { int a, b, c; printf("Enter coefficients a, b, and c: "); scanf("%d %d %d", &a, &b, &c); calculateDiscriminant(a, b, c); return 0; }
Output: Complex Roots: -1.00 + 2.00i, -1.00 - 2.00i