Write a C program to Find roots of quadratic equation

Topics

  1. Includes two header files: “stdio.h” and “math.h” to use their respective functions.
  2. Defines a main function with no arguments that returns an integer.
  3. Declares several variables of type double: a, b, c, discriminant, root1, root2, realPart, imaginaryPart.
  4. Prints a message asking the user to enter the coefficients of a quadratic equation.
  5. Uses the scanf function to read in the values entered by the user for coefficients a, b, and c.
  6. Computes the value of the discriminant of the quadratic equation using the formula discriminant = b^2 – 4ac.
  7. Checks the value of the discriminant using an if-else statement to determine what type of roots the equation has:
    • If the discriminant is greater than 0, the program computes and displays two real and different roots.
    • If the discriminant is equal to 0, the program computes and displays two real and same roots.
    • If the discriminant is less than 0, the program computes and displays two complex and different roots.
  8. Uses printf statements to display the results of the calculations to the user.
  9. Returns 0 to indicate successful execution of the program.
#include <stdio.h>
#include <math.h>

int main() {
    double a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);

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

    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("Roots are real and different. Root1 = %.2lf and Root2 = %.2lf", root1, root2);
    }
    else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        printf("Roots are real and same. Root1 = Root2 = %.2lf", root1);
    }
    else {
        realPart = -b / (2 * a);
        imaginaryPart = sqrt(-discriminant) / (2 * a);
        printf("Roots are complex and different. Root1 = %.2lf + %.2lfi and Root2 = %.2lf - %.2lfi", realPart, imaginaryPart, realPart, imaginaryPart);
    }

    return 0;
}

OUTPUT

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


Enter coefficients a, b and c: 1 -6 10
Roots are complex and different. Root1 = 3.00 + 1.00i and Root2 = 3.00 - 1.00i

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *