Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to find the root of quadratic equation.

Write a program to find the root of quadratic equation.

Given a quadratic equation, we have to find the root of given quadratic equation and print their root.

So what is quadratic equation ?

if the equation is in form of ax2+bx+c then it is quadratic equation.


Input: 1 5 6
Output:-2  -3


STEP 1: if descriminant is greater than 0 ,roots are real and different.
STEP 2:if descriminant is smaller than 0 ,roots are real and equal.
STEP 3:if descriminant is equal than 0 ,roots are complex and diffrent.


using namespace std;
int main()
	double dis;
	double root1;
	double root2;
	double r1, r2, r3;
	double real, imaginary;
	cout<<"enter coefficient"<<endl;
	dis = (r2*r2) - (4*r1*r3);
	if (dis > 0)  //condition 1
		root1 = (-r2 + sqrt(dis)) / (2*r1);
		root2 = (-r2 - sqrt(dis)) / (2*r1);
		cout<<"Roots are real and different"<<endl;
		cout<<root1<<" "<<root2<<endl;
	else if (dis<0) //condition 2
		real = -r2/(2*r1);
		imaginary =sqrt(-dis)/(2*r1);
		cout << "Roots are complex and different."  << endl;
	cout<<real<<" "<<imaginary<<endl;
	else //condition 3
		cout << "Roots are real and same." << endl;
		root1 = (-r2 + sqrt(dis)) / (2*r1);
		cout<<root1<<" "<<root1<<endl;


1 5 6
-2 -3

Time Complexity:O(N)

Space Complexity:O(1)


Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments