Hi everyone

##

##

The program is self explanatory in itself. First we take the coefficients of the quadratic equation as input from the user. Then on the basis of its determinant,i.e,

##

##

In this post, we're going how to write a C program to calculate the roots of a quadratic equation. As we know that a quadratic equation is of a form like:

**ax^2+bx+c=0**

So we won't go into much details. Also you guys must be knowing to calculate the roots of a quadratic equation directly, having formula:

Roots = ( -b + (b^2 - 4ac) ) / 2a & ( -b - (b^2 - 4ac) ) / 2a

So we are just going to use the same formula in our C code. So Let's begin...

##
__C Program To Calculate Roots Of a Quadratic Equation:__

__C Program To Calculate Roots Of a Quadratic Equation:__

/* Double-Click To Select Code */ #include<stdio.h> #include<conio.h> #include<math.h> void main() { float a,b,c,root1,root2,x,real,im; clrscr(); printf("-> Quadratic Equation Form: ax2+bx+c"); printf("\n\nEnter the value of a: "); scanf("%f",&a); printf("\nEnter the value of b: "); scanf("%f",&b); printf("\nEnter the value of c: "); scanf("%f",&c); x = (b*b)-(4*a*c); if(x>0) { root1 = (-b+sqrt(x))/(2*a); root2 = (-b-sqrt(x))/(2*a); //ROOTS ARE UNIQUE printf("\nThe roots of the equation are: %.2f and %.2f",root1,root2); } else if(x==0) { root1 = -b/(2*a); root2 = root1; //ROOTS ARE SAME printf("\nThe roots of the equation are: %.2f and %.2f",root1,root2); } else { real = -b/(2*a); im = sqrt(-x)/(2*a); // ROOTS ARE COMPLEX printf("\nThe roots of the equation are: %.2f+j%.2f and %.2f-j%.2f",real,im,real,im); } getch(); }

##
__Program Explanation:__

The program is self explanatory in itself. First we take the coefficients of the quadratic equation as input from the user. Then on the basis of its determinant,i.e, __Program Explanation:__

__b^2 - 4*a*c__, if its greater than 0 or equal to 0 or less than 0. In each of the case, we can get different types of roots, Unique, Equal or Complex respectively. Using the formula as I described in the beginning of this post, we calculate roots, with an exception in case of complex roots, whereby, we have to find real and imaginary parts of the roots individually, using the formula:

Real Part =

__-b/(2*a)__
Imaginary Part =

**-> Since determinant is negative here, we make it positive by multiplying an extra '-'.**__sqrt(-x)/(2*a)__

##
__Program Output:__

__Program Output:__

Please Comment If You Liked The Post.

Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: