C PROGRAMMING PROGRAM • DECISION MAKING
Find the Roots of a Quadratic Equation
Learn how to find the roots of a quadratic equation using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
1 -5 6
Sample output
Roots = 3.00 and 2.00
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <math.h>
int main(void)
{
double a, b, c, discriminant, firstRoot, secondRoot;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
if (a == 0) {
printf("The equation is not quadratic.\n");
return 0;
}
discriminant = b * b - 4.0 * a * c;
if (discriminant > 0) {
firstRoot = (-b + sqrt(discriminant)) / (2.0 * a);
secondRoot = (-b - sqrt(discriminant)) / (2.0 * a);
printf("Roots = %.2f and %.2f\n", firstRoot, secondRoot);
} else if (discriminant == 0) {
printf("Repeated root = %.2f\n", -b / (2.0 * a));
} else {
printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi\n",
-b / (2.0 * a), sqrt(-discriminant) / (2.0 * a),
-b / (2.0 * a), sqrt(-discriminant) / (2.0 * a));
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Roots = 3.00 and 2.00
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use the discriminant b²−4ac to select two real, one repeated or two complex roots.
- Display the computed result.
Use the discriminant b²−4ac to select two real, one repeated or two complex roots.
EFFICIENCY
Time and space complexity
Time complexity
O(1)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
