C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Decision Making Programs in C

Find roots of quadratic equation

Introduction

A quadratic equation is in the form:

ax2+bx+c=0

where

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

The roots of the equation are given by the quadratic formula:

x = (−b±sqrt(b2−4ac))/2a 

The discriminant DDD helps determine the nature of the roots:

D=b2−4ac

  • If D>0 → Two distinct real roots
  • If D=0 → Two equal real roots
  • If D<0 → Complex conjugate roots

 

C Program: Find Roots of Quadratic Equation

C

#include <stdio.h>

#include <math.h>

 

int main() {

    float a, b, c, discriminant, root1, root2, realPart, imagPart;

 

    // Input coefficients

    printf("Enter coefficients a, b and c: ");

    scanf("%f %f %f", &a, &b, &c);

 

    // Calculate discriminant

    discriminant = b * b - 4 * a * c;

 

    // Check the nature of roots

    if (discriminant > 0) {

        // Real and distinct roots

        root1 = (-b + sqrt(discriminant)) / (2 * a);

        root2 = (-b - sqrt(discriminant)) / (2 * a);

        printf("Roots are real and different.\n");

        printf("Root 1 = %.2f\n", root1);

        printf("Root 2 = %.2f\n", root2);

    }

    else if (discriminant == 0) {

        // Real and equal roots

        root1 = root2 = -b / (2 * a);

        printf("Roots are real and equal.\n");

        printf("Root 1 = Root 2 = %.2f\n", root1);

    }

    else {

        // Complex roots

        realPart = -b / (2 * a);

        imagPart = sqrt(-discriminant) / (2 * a);

        printf("Roots are complex and conjugate.\n");

        printf("Root 1 = %.2f + %.2fi\n", realPart, imagPart);

        printf("Root 2 = %.2f - %.2fi\n", realPart, imagPart);

    }

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter coefficients a, b and c: 1 5 6
Roots are real and different.
Root 1 = -2.00
Root 2 = -3.00

OUTPUT 2 :
Enter coefficients a, b and c: 1 4 4
Roots are real and equal.
Root 1 = Root 2 = -2.00

OUTPUT 3 :
Enter coefficients a, b and c: 1 2 5
Roots are complex and conjugate.
Root 1 = -1.00 + 2.00i
Root 2 = -1.00 - 2.00i

Explanation

  1. User inputs a, b, and c.
  2. The discriminant D = b² - 4ac is calculated.
  3. Depending on the value of D:
    • If positive → two distinct real roots.
    • If zero → two equal real roots.
    • If negative → complex conjugate roots.
  4. The roots are printed accordingly.