Select Page

# C program to find the roots of a quadratic equation

by | Jan 12, 2023 | C, C Programs

Home » C » C Programs » C program to find the roots of a quadratic equation

## Introduction

In this program, we shall learn the basic mathematics concept of finding the square roots of a quadratic equation.

First of all, let’s understand the standard form of a Quadratic equation.

x(a*a) +y(a) +z=0, where x, y, and z are the coefficients and are real numbers. ‘a’ is any variable.

x!=0

roots are nothing else but the two values of ‘a’.

Discriminant=(y*y)-(4*x*z)

If the Discriminant is greater than 0, then the roots are real and distinct.

If the Discriminant is less than 0, then the roots are imaginary(complex) and distinct.

If the Discriminant is equal to 0, then the roots are real and equal.

To understand this program, you should know about

1. C programming operators

2. C nested if…else statement

3. Predefined sqrt() function

## Program

```#include<stdio.h>

#include<math.h>

int main()

{

float x,y,z;

printf("Enter the cofficients x,y,z:");

scanf("%f %f %f",&x,&y,&z);

float D=y*y-4*x*z; // 'D' is a discriminant

int R1, R2; //R1, R2 represents the root values

if(D>0) // when roots are real and unique

{

R1=(-y+ sqrt(D))/(2*x);

R2=(-y- sqrt(D))/(2*x);

printf("Root1=%.2f\nRoot2=%.2f",R1,R2);

}

else if(D==0) // when roots are real and equal

{

R1=R2=(-y)/(2*x);

printf("Root1=%.2f\nRoot2=%.2f",R1,R2);

}

else //when roots are imaginary

{

float real_part= -y/(2*x);

float img_part= sqrt(-D)/(2*x);

printf("Root 1=%.2f+%.2fi\n”, real_part,img_part);

printf("Root 2=%.2f-%.2fi”, real_part,img_part);

}

}```

## Output ## Explanation

The user is asked to enter 3 float values as the coefficients of the quadratic equation.

float D=y*y-4*x*z; here we compute the value of Discriminant (D), which is the first step to proceed.

After that, we use if, else, and else if statements, and they will be executed depending upon the value of D.

if(D>0) if the statement is true then values of R1 and R2 will get calculated.

R1=(-y+ sqrt(D))/(2*x);

The above statement is the direct formula, and the square root of D is calculated using the sqrt() function. The final value is assigned in R1.

Similarly, R2 is calculated. Both come out to be different and real.

else if(D==0) if the value of D is 0 then R1 and R2 are equal in values and calculated as below

R1=R2=(-y)/(2*x);

If the value of D is less than 0, then the else part of the code gets executed, and R1 and R2 come out to be complex values containing both real and imaginary parts.

float real_part= -y/(2*x); this statement calculates the real part of the root value R1 and R2.

float img_part= sqrt(-D)/(2*x); this statement calculates the imaginary part of the root value R1 and R2.

## Author

• A Full Stack Developer with 10+ years of experience in technical content creation.

• 