Loading...
C Program to Find the Roots of a Quadratic Equation

C Program to Find the Roots of a Quadratic Equation

In this example, we will learn to find the roots of a quadratic equation in C programming.

Remainder :

To understand this example, we should have the knowledge of the following C programming topics:


Quadratic Equation

The standard form of a quadratic equation is:

ax2 + bx + c = 0 

Here, a, b and c are real numbers and a != 0

The term b2-4ac is known as the discriminant of a quadratic equation which tells the nature of the roots.

  • If discriminant > 0, the roots are real and different.
  • If discriminant = 0, the roots are real and equal.
  • If discriminant < 0, the roots are complex and different.

Program to Find Roots of a Quadratic Equation

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

int main() {
  int a, b, c, dis;
  double root1, root2;
  printf("Enter coefficients a, b and c: ");
  scanf("%d %d %d", &a, &b, &c);
  dis = b * b - 4 * a * c;
  if (dis < 0) {
    printf("First root = %.2lf + i%.2lf\n", -b/(double)(2*a), sqrt(-dis)/(2*a));
    printf("Second root = %.2lf - i%.2lf\n", -b/(double)(2*a), sqrt(-dis)/(2*a));
  }
  else {
    root1 = (-b + sqrt(dis)) / (2 * a);
    root2 = (-b - sqrt(dis)) / (2 * a);
    printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
  }
  return 0;
}

Output

Enter coefficients a, b and c: 2 3 4
First root = -0.75 + i1.20
Second root = -0.75 - i1.20

In this program, we use sqrt() library function to find the square root of a number. To learn more, visit: sqrt() function.

- Related Topics