You are here

C program to find roots of a quadratic equation

C program to find roots of a quadratic equation: This program calculates roots of a quadratic equation. Coefficients are assumed to be integers, but roots may not be real. Discriminant (b*b-4*a*c) decides the nature of roots. In the program, j stands for iota.

C programming code

  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int main()
  5. {
  6.    int a, b, c, d;
  7.    double root1, root2;
  8.  
  9.    printf("Enter a, b and c where a*x*x + b*x + c = 0\n");
  10.    scanf("%d%d%d", &a, &b, &c);
  11.  
  12.    d = b*b - 4*a*c;
  13.  
  14.    if (d < 0) { //complex roots
  15.      printf("First root = %.2lf + j%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
  16.      printf("Second root = %.2lf - j%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
  17.    }
  18.    else { //real roots
  19.       root1 = (-b + sqrt(d))/(2*a);
  20.       root2 = (-b - sqrt(d))/(2*a);
  21.  
  22.       printf("First root = %.2lf\n", root1);
  23.       printf("Second root = %.2lf\n", root2);
  24.    }
  25.  
  26.    return 0;
  27. }