Calculate Roots Of a Quadratic Equation Using C Program | Coding Bot

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:

 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:

/* 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, 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.

    ReplyDelete