w3resource

C Exercises: Calculate the root of a Quadratic Equation

C Conditional Statement: Exercise-11 with Solution

Write a C program to calculate the root of a quadratic equation.

Visual Presentation:

Calculate the root of a Quadratic Equation

Sample Solution:

C Code:

#include <stdio.h>   // Include the standard input/output header file.
#include <math.h>    // Include the math library for mathematical functions.

void main()
{
   int a, b, c, d;   // Declare variables to store coefficients and discriminant.
   float x1, x2;     // Declare variables to store roots.

   printf("Input the value of a, b & c : ");   // Prompt user for input.
   scanf("%d%d%d", &a, &b, &c);   // Read and store coefficients in 'a', 'b', and 'c'.
   d = b*b - 4*a*c;   // Calculate the discriminant.

   if(d == 0)   // Check if discriminant is zero.
   {
     printf("Both roots are equal.\n");
     x1 = -b / (2.0 * a);   // Calculate the single root.
     x2 = x1;
     printf("First  Root Root1 = %f\n", x1);   // Print the roots.
     printf("Second Root Root2 = %f\n", x2);
   }
   else if(d > 0)   // Check if discriminant is positive.
   {
       printf("Both roots are real and different.\n");
       x1 = (-b + sqrt(d)) / (2 * a);   // Calculate the first root.
       x2 = (-b - sqrt(d)) / (2 * a);   // Calculate the second root.
       printf("First  Root Root1 = %f\n", x1);   // Print the roots.
       printf("Second Root Root2 = %f\n", x2);
   }
   else   // If discriminant is negative.
       printf("Roots are imaginary;\nNo Solution. \n");   // Print no solution message.
}

Sample Output:

Input the value of a,b & c : 1 5 7                                                                            
Root are imaginary;                                                                                           
No Solution. 

Flowchart:

Flowchart: Calculate root of Quadratic Equation.

C Programming Code Editor:

Previous: Write a C program to find the eligibility of admission for a professional course based on the specified criteria
Next: Write a C program to read roll no, name and marks of three subjects and calculate the total, percentage and division.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/conditional-statement/c-conditional-statement-exercises-11.php