In this post I show you how to write a C program that finds the roots(both real and complex) of a quadratic equation.

### Theory:

A quadratic equation looks like this:

We will therefore, ask the user to enter the coefficients().

The discriminant is given as,

If then the equation has real and equal roots, if then the equation has real and unequal roots, and if then the equation has complex roots.

So, in our program, we will first perform a check to find out if the roots are going to be real or complex by using the above conditions.

Then accordingly we will, use the following formulas to find the root:

**Real Roots**():

**Complex Roots**():

That’s all the information you need to be able to write the program.

### Program:

/************************************** ****ROOTS OF A QUADRATIC EQUATION 2017 (c) Manas Sharma - https://bragitoff.com *************************************/ #include<stdio.h> #include<math.h> main() { double a,b,c,root1,root2,d,imag; printf("Enter the coefficients(a,b,c) of the quadratic equation\nax^2+bx+c=0\n"); scanf("%lf%lf%lf",&a,&b,&c); //printf("%f,%f,%f",a,b,c); d=b*b-4*a*c; if(d>=0){ /****REAL ROOTS CALCULATION****/ root1=(-b+sqrt(d))/(2*a); root2=(-b-sqrt(d))/(2*a); printf("The polynomial has real roots:\nx1=%f\nx2=%f\n",root1,root2); } else{ /****COMPLEX ROOTS CALCULATION****/ root1=-b/(2*a); imag=sqrt(fabs(d))/(2*a); printf("The polynomial has complex roots:\nx1=%f+%fi\nx2=%f-%fi\n",root1,imag,root1,imag); } }

### OUTPUT:

Ph.D. researcher at Friedrich-Schiller University Jena, Germany. I’m a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT, and Machine Learning related apps and software from time to time. Can code in most of the popular languages. I like to share my knowledge in Physics and applications using this Blog and a YouTube channel.