# Quadratic Equation Program in C

A quadratic equation is an equation of the second degree, meaning it contains at least one term that is squared. The standard form of the quadratic equation is `ax² + bx + c = 0` where a, b, and c are real and a !=0, x is an unknown variable. The nature of roots is determined by the discriminant. Here we will write a quadratic equation program in c to solve quadratic equation and find the roots of quadratic equation using c programming language.

Prerequisites for Quadratic Equation Program in C:- If-else statement in C, programs on if-else in C, conditional operator in C

The discriminant of the Quadratic equation is calculated as `b²-4*a*c`

`discriminant(d) = b²-4*a*c`

The nature of the roots are given as,

• If discriminant>1 then the roots are real and different
• If discriminant=0 then the roots are real and equal
• discriminant<1 then the roots are complex and different

For the quadratic equation `ax² + bx + c = 0`, if we denote the discriminant as d, then their roots

If d > 1 then
root1 = `(-b + √d) / 2a`
root2 = `(-b - √d) / 2a`

If d = 0 then both roots are `-b / 2a`

If d < 1 then
root1 = `-b / 2a + i (√d / 2a)`
root2 = `-b / 2a - i (√d / 2a)`

## C program to solve the quadratic equation

``````#include<stdio.h>
#include<math.h>
int main()
{
int a, b, c, d;
int root1, root2, realPart, imaginaryPart;

printf("Enter cofficients (a, b, and c): ");
scanf("%d %d %d", &a, &b, &c);

d = (b*b) - 4*a*c; //discriminant

if( d>1 )
{
root1 = (-b+sqrt(d)) / 2*a;
root2 = (-b-sqrt(d)) / 2*a;
printf("Roots are %d and %d\n", root1, root2);
}
else if(d==0)
{
root1 = root2 = -b/2*a;
printf("Roots are %d and %d\n", root1, root2);
}
else
{
realPart = -b/2*a;
imaginaryPart = sqrt(d)/2*a;
printf("root1 = %d + i(%d)\n", realPart, imaginaryPart);
printf("root1 = %d - i(%d)\n", realPart, imaginaryPart);
}
return 0;
}``````

Output for different test cases:-

Enter cofficients (a, b, and c): 1 -1 -6
Roots are 3 and -2

Enter cofficients (a, b, and c): 1 -12 36
Note:- Linux/Unix user may get an error:- `Undefined reference to sqrt()` in C Programming (or other mathematical functions) even includes math.h header. Windows user doesn’t get any warning and error but Linux/Unix user may get an undefined reference to sqrt. This is a linker error. To solve this problem use `-lm` during compilation.