C Online Compiler
Example: Find Roots of Quadratic Equation using Switch Statement in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Roots of Quadratic Equation using Switch Statement #include <stdio.h> #include <math.h> // Required for sqrt() function int main() { // Step 1: Declare variables for coefficients and roots double a, b, c; double discriminant, root1, root2, realPart, imagPart; int choice; // To control the switch statement // Step 2: Prompt user for coefficients printf("Enter coefficients a, b and c: "); scanf("%lf %lf %lf", &a, &b, &c); // Step 3: Handle the case where 'a' is zero (not a quadratic equation) if (a == 0) { if (b == 0) { if (c == 0) { printf("Infinite solutions (0=0).\n"); } else { printf("No solution (c=0, where c!=0).\n"); } } else { // Linear equation: bx + c = 0 => x = -c/b root1 = -c / b; printf("This is a linear equation.\n"); printf("Root = %.2lf\n", root1); } return 0; // Exit if not a quadratic equation } // Step 4: Calculate the discriminant discriminant = b * b - 4 * a * c; // Step 5: Determine the 'choice' value for the switch statement if (discriminant > 0) { choice = 1; // Distinct real roots } else if (discriminant == 0) { choice = 0; // Equal real roots } else { choice = -1; // Complex roots } // Step 6: Use switch statement to find roots based on 'choice' switch (choice) { case 1: // Discriminant > 0 (Distinct Real Roots) root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Roots are real and distinct.\n"); printf("Root1 = %.2lf\n", root1); printf("Root2 = %.2lf\n", root2); break; case 0: // Discriminant = 0 (Equal Real Roots) root1 = root2 = -b / (2 * a); printf("Roots are real and equal.\n"); printf("Root1 = Root2 = %.2lf\n", root1); break; case -1: // Discriminant < 0 (Complex Roots) realPart = -b / (2 * a); imagPart = sqrt(-discriminant) / (2 * a); printf("Roots are complex and distinct.\n"); printf("Root1 = %.2lf + %.2lfi\n", realPart, imagPart); printf("Root2 = %.2lf - %.2lfi\n", realPart, imagPart); break; } return 0; }
Output
Clear
ADVERTISEMENTS