Friday, August 7, 2026

Quadratic Equation Root Finder || C Lab Programs

 Program 04: Quadratic Equation Root Finder

Problem Statement:: A math app needs to determine the type and values of roots for a quadratic equation ($ax^2+bx+c=0$) based on user-provided coefficients. 

Problem Description:

  • Input: Three floating-point numbers for coefficients a, b, and c.

  • Output: The roots and their nature (Real/Distinct, Real/Equal, or Complex).

  • Constraints: Must handle linear cases (a=0) and invalid inputs (a=0, b=0).

  • Method: Calculate the discriminant $\Delta = b^2 - 4ac$ to determine the root type. 

Pgm Logic:

  1. Start.

  2. Input coefficients a, b, and c.

  3. If a=0 and b=0, print "Invalid Coefficients".

  4. Else if a=0, solve as a linear equation: root = -c/b.

  5. Else, calculate discriminant disc = b*b - 4*a*c:

    • If disc > 0: Compute two real distinct roots.

    • Else if disc = 0: Compute one repeated real root.

    • Else: Compute complex roots in real ± imag i format.

  6. Stop. 

Program Code:

// Purpose: To calculate and display the nature and values of roots for a quadratic equation.

#include <stdio.h>

#include <math.h>


int main()

{

    float a, b, c, root1, root2, disc, real, imag;

    printf("Enter coefficients of quadratic equation (a, b, c): ");

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

    if (a == 0 && b == 0) printf("Invalid Coefficients!\n");

    else if (a == 0) {

        root1 = -c / b;

        printf("Linear Equation with root: %.2f\n", root1);

    } else {

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

        printf("Discriminant = %.2f\n", disc);

        if (disc > 0) {

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

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

            printf("Two distinct real roots: %.2f and %.2f\n", root1, root2);

        } else if (disc == 0) {

            root1 = -b / (2 * a);

            printf("One real root: %.2f\n", root1);

        } else {

            real = -b / (2 * a);

            imag = sqrt(-disc) / (2 * a);

            printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi\n", real, imag, real, imag);

        }

    }

    return 0;

}


Output: 

Enter coefficients (a, b, c): 1 -3 2 

Discriminant = 1.00 

Two distinct real roots: 2.00 and 1.00 

RESULT: Thus the program has been executed and the output was verified. 

Remarks: This program was tested in onlineGDB. It demonstrates advanced use of nested if-else structures and mathematical functions from <math.h>

Program Explanation: The logic first screens for non-quadratic scenarios (like linear equations). For true quadratics, it uses the discriminant to select the appropriate mathematical formula for real or complex results.



For all 2026 published C Lab Program posts Index page: click here

For all 2026 published articles list:click here

…till the next post, bye-bye & take care

No comments:

Post a Comment