C Program to Find Roots of a Quadratic Equation

Quadratic equations are the polynomial equation having a degree 2. For a quadratic equation ax2+ bx + c = 0, (a≠0) and the discriminant (D = b2-4ac) decides the nature of roots. There are three possibilities of discriminant and those are:

  1. when d>0, the roots are real and distinct
  2. when d=0, the roots are real and equal
  3. when d<0, the roots are real and imaginary
quardraic equation program

In order to understand the program, you need to have the knowledge of the following in C Programming:


Find the Roots of a Quardratic Equation in C

The program uses sqrt() library function in order to calculate the square root of a number. To use sqrt(), math.h header file is used.

#include <math.h>
#include <stdio.h>

int main()
{
  double a, b, c, d, root1, root2, real, img;
  
  printf("Enter the values for a, b and c:\n");
  scanf("%lf %lf %lf", &a, &b, &c);

  //determinant
  d = b *b - 4 *a * c;

  // real and different roots
  if (d > 0)
  {
    root1 = (-b + sqrt(d)) / (2 *a);
    root2 = (-b - sqrt(d)) / (2 *a);
    printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
  }

  //for real and equal roots
  else if (d == 0)
  {
    root1 = root2 = -b / (2 *a);
    printf("root1 = root2 = %.2lf;", root1);
  }

  // d < 0 both roots are real and imaginary
  else
  {
    real = -b / (2 *a);
    img = sqrt(-d) / (2 *a);
    printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", real, img, real, img);
  }

  return 0;
}

Output:

quadratic equation