Introduction
Quadratic equations are a fundamental concept in algebra, typically represented in the form:
ax² + bx + c = 0
Where a, b, and c are constants, and x represents the variable.
Objective
The objective of this program is to solve quadratic equations by calculating the roots using the quadratic formula:
x = (-b ± √(b² - 4ac)) / 2a
Given values for a, b, and c, this C program will determine if the equation has real roots or complex roots, and will then display the appropriate roots.
Code
#include
#include
int main() {
float a, b, c, discriminant, root1, root2;
// Taking input for a, b, and c
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);
// Calculating the discriminant
discriminant = b * b - 4 * a * c;
// Checking if the discriminant is positive, negative, or zero
if (discriminant > 0) {
// Two real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("The roots are real and distinct: %.2f and %.2f\n", root1, root2);
}
else if (discriminant == 0) {
// One real root
root1 = -b / (2 * a);
printf("The root is real and the same: %.2f\n", root1);
}
else {
// Complex roots
float realPart = -b / (2 * a);
float imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("The roots are complex:\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart);
}
return 0;
}
Program Explanation
This C program solves a quadratic equation using the following steps:
- Input: The program asks the user to enter values for the coefficients a, b, and c.
- Discriminant Calculation: The discriminant D = b² – 4ac is calculated. The discriminant helps determine the nature of the roots.
- Root Calculation: Based on the value of the discriminant:
- If D > 0, the equation has two real and distinct roots.
- If D = 0, the equation has one real root.
- If D < 0, the equation has complex (imaginary) roots.
- Output: The program prints the roots of the equation to the screen based on the discriminant’s value.
How to Run the Program
-
- Open a C programming environment or a code editor like Code::Blocks, Dev-C++, or an IDE like Visual Studio.
- Create a new C file and paste the provided code into the file.
- Save the file with a .c extension (e.g., quadratic_solver.c).
- Compile the code using the built-in compiler in your IDE or by using a command line compiler like gcc:
gcc quadratic_solver.c -o quadratic_solver
- Run the program and input values for a, b, and c when prompted.
- The program will output the roots of the quadratic equation.


I like this web site because so much utile material on here : D.