POP Lab Manual

Program 2

Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages based on the discriminant value to determine if roots are real and distinct, real and equal, or complex (imaginary).
Quadratic Equation Formula:
ax² + bx + c = 0
Discriminant (d) = b² - 4ac
Roots: x = (-b ± √d) / 2a

Algorithm

  1. Initialize: Start the program
  2. Input Coefficients: Read coefficients a, b, c from user
  3. Calculate Discriminant: d = b² - 4ac
  4. Check Discriminant: Compare d with 0
  5. If d > 0: Calculate two real and distinct roots
  6. If d = 0: Calculate one real and equal root
  7. If d < 0: Display "Roots are imaginary"
  8. Output: Display appropriate message and roots
  9. Terminate: Stop the program

Flowchart

START
Input a, b, c
d = b²-4ac
Check d
Calculate Roots
Display Results
STOP

Code

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


int main() {
    float a, b, c, d, r1, r2;

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

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

    if (d > 0) {
        r1 = (-b + sqrt(d)) / (2*a);
        r2 = (-b - sqrt(d)) / (2*a);
        printf("Roots are real and distinct: %.2f , %.2f\n", r1, r2);
    }
    else if (d == 0) {
        r1 = r2 = -b / (2*a);
        printf("Roots are real and equal: %.2f , %.2f\n", r1, r2);
    }
    else {
        printf("Roots are imaginary (complex).\n");
    }

    return 0;
}

Output


// Output 1 - Real and Distinct Roots
Enter coefficients a, b, c: 1 -5 6
Roots are real and distinct: 3.00 , 2.00

// Output 2 - Real and Equal Roots  
Enter coefficients a, b, c: 1 -4 4
Roots are real and equal: 2.00 , 2.00

// Output 3 - Complex/Imaginary Roots
Enter coefficients a, b, c: 1 2 5
Roots are imaginary (complex).

// Output 4 - Another Real and Distinct Example
Enter coefficients a, b, c: 2 -7 3
Roots are real and distinct: 3.00 , 0.50
          
Comments

Replay !

0 Comments

Share Your Thoughts

Please enter your name
Please enter a valid email
Password must be at least 6 characters
Please enter your comment
Email Verification Required
We've sent a 6-digit verification code to . Please enter the code below to verify your email address.
Email Verified Successfully!
Your email has been verified. Would you like to proceed with posting your comment?

Type "YES" to confirm and post your comment, or click Cancel to skip posting.