 # Techtopz

(@techtopz)

Techtopz is a blog on programming and tech stuff.

# C++ | Solving a Quadratic Equation

You may have learnt solving quadratic equations in school. Now let us try the logic here in c++. The first program just displays the type of root. The last one displays the root of the given quadratic equation. you cannot extend the program as there are no ways in which you can. Go enjoy the program. Lets begin...

Program for display type of root.

``````#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
int a,b,c,x;
//Input a,b,c save them in variables
cout<<"Enter the value of a,b and c of QE"<<endl;
cin>>a>>b>>c;
//draw a line for neatness
cout<<"-------------------------------------"<<endl;
cout<<a<<"x(square)+"<<b<<"x+"<<c<<endl;
//calculate and save it in x
x=(b*b)-(4*a*c);
cout<<"-------------------------------------"<<endl;
//if else condition.
if(x<0)
cout<<"Roots are imaginary"<<endl;
else
{
if(x==0)
cout<<"Roots are equal"<<endl;
else
cout<<"Roots are unequal"<<endl;
}
//show the output x
cout<<"b*b-4ac is "<<x;
//get character
getch();
}
``````

Output

Enter the value of a,b and c of QE
1 4 5
————————————-
1x(square)+4x+5
————————————-
Roots are imaginary.
b*b-4ac is -4

Program to calculate the root

``````#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
int a,b,c,x,y,z,t;
//Input a,b,c save them in variables
cout<<"Enter the value of a,b and c of QE"<<endl;
cin>>a>>b>>c;
//draw a line for neatness
cout<<"-------------------------------------"<<endl;
cout<<a<<"x(square)+"<<b<<"x+"<<c<<endl;
//calculate and save it in x
x=(b*b)-(4*a*c);
cout<<"-------------------------------------"<<endl;
//show the output x
cout<<"b*b-4ac is "<<x<<endl;
//if else condition.
if(x<0)
cout<<"Roots are imaginary"<<endl;
else
{
//calculate roots
t=sqrt(x);
y=(-b+t)/(2*a);
z=(-b-t)/(2*a);
cout<<"Roots are "<<y<<" & "<<z<<endl;
}
//get character
getch();
}
``````

Output

Enter the value of a,b and c of QE
1 4 3
————————————-
1x(square)+4x+5
————————————-
b*b-4ac is 4
Roots are -1 & -3

How does it work
1. You enter the a,b,c in and is saved in variables.
3. Calculates x.
4. Decides the type of roots and prints it.
5. Calculates the roots if not imaginary and prints them

Extending it
The program cannot be extended as no directions to extend it.

Explanation.
1. Include ‘iostream.h’ and ‘conio.h’ files.