Like Us On Facebook & Follow Us On Twitter

Tuesday, 19 November 2013

Calculate Roots Of a Quadratic Equation Using C Program

Hi everyone
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:


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:

/* Double-Click To Select Code */


void main()
float a,b,c,root1,root2,x,real,im;

printf("-> Quadratic Equation Form: ax2+bx+c");
printf("\n\nEnter the value of a: ");
printf("\nEnter the value of b: ");
printf("\nEnter the value of c: ");

x = (b*b)-(4*a*c);

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);

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);


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, 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 = sqrt(-x)/(2*a) -> Since determinant is negative here, we make it positive by multiplying an extra '-'.

Program Output:

C Program To Calculate Roots Of a Quadratic Equation

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:

1 comment:

  1. I like your approach on the topic. Your article is as interesting as your previous writings. Keep up the good work, thanks a lot.