C Examples

C Program - Find Roots of a Quadratic Equation

A standard form of a quadratic equation is:

ax2 + bx + c = 0


a, b and c are real numbers and a ≠ 0.

Roots of the equation are:

Roots of quadratic equation

For Example:

The roots of equation x2 + 5x + 4 = 0 is

Roots of quadratic equation

The roots of the equation will be imaginary if D = b2 - 4ac < 0. For example - the roots of equation x2 + 4x + 5 = 0 will be

Roots of quadratic equation

Example: Calculate roots of a Quadratic equation

In the example below, a function called roots is created which takes a, b and c as arguments to calculate the roots of the equation ax2 + bx + c = 0.

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

static void roots(double, double, double);

static void roots(double a, double b, double c) {
  double D = b*b - 4*a*c;
  if (D >= 0) {
    double x1 = (-b + sqrt(D))/(2*a);
    double x2 = (-b - sqrt(D))/(2*a);
    printf("Roots are: %.f, %.f\n", x1, x2);   
  } else {
    double x1 = -b/(2*a);
    double x2 = sqrt(-D)/(2*a);
    printf("Roots are: %.f±%.fi\n", x1, x2); 

int main() {
  printf("Equation is x*x+5x+4=0\n"); 
  printf("\nEquation is x*x+4x+5=0\n"); 

The above code will give the following output:

Equation is x*x+5x+4=0
Roots are: -1, -4

Equation is x*x+4x+5=0
Roots are: -2±1i