C Program To Find Roots of Quadratic Equation

The formula to solve a quadratic equation is
     -b + √(b2 - 4ac)
 r =  ______________
          2a
The term b2 - 4ac is called as discriminant and is of very importance. Depending on the value of discriminant we can tell the nature of the roots of the quadratic equation where a, b and c are the rational numbers.

If value of discriminant (d) is
  • Zero (0) - the equation has real root
  • greater than zero (d > 0) - the equation has real and distinct roots
  • less than zero (d < 0) - the equation has imaginary roots
The discriminant is useful if we want to know the nature of the roots instead of actually calculating them.

C Program Find Roots of Quadratic Equation

/* Aim: To find the roots of 
given quadratic equation */ 

#include <stdio.h>
#include <math.h>
void main()
{
   int a,b,c,D;
   float r1,r2;

   printf("\n Enter the (X,Y) Co-ordinates :- ");
   scanf("%d%d",&a,&b);

   printf("\n Enter the Value of Constant :- ");
   scanf("%d",&c);
 
   D=(b*b)-(4*a*c);

   if (D>0)
   {
     r1=((-b+sqrt(D))/2*a);
     r2=((-b-sqrt(D))/2*a);
     printf("\nThe roots of quadratic equation: %d and %d \n \n",r1,r2); 
   }
   else if(D==0)  
   {
    r1=r2=-b/(2*a);
    printf("\nThe roots of quadratic equation: %d and %d \n \n",r1,r2); 
    }
    else	{
    printf("\nThe roots of given quadratic equation have no real roots \n \n");
    } 
}

Output:

Enter the (X,Y) Co-ordinates :- 4 8

Enter the Value of Constant :- 2

The roots of quadratic equation: 1 and 32 
If you want to find roots of quadratic equation first to verify them with the output of your c program, use this tool Quadratic Equation Solver Online Calculator.