Techtopz

(@techtopz)

Techtopz is a blog on programming and tech stuff.
Techtopz is now on UpHub.
Follow us for more updates.

    


Java Programming | Solving Quadratic Equations

This is a tutorial for solving quadratic equations in java. The program is given below that solves the QE. The program is not extendable. Go enjoy the program. Lets begin…

Program for solving quadratic equation in java.

//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class QuadraticEq {
//void main
public static void main (String[] args)
{
//declare int
int a,b,c,x,y,z,t;

//Declare input as scanner
Scanner input = new Scanner(System.in);

//Take inputs
System.out.println("Enter value of a,b,c of QE:");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();

System.out.println("----------------------------");
System.out.println("QE : "+a+"x(square)+"+b+"x+"+c);
System.out.println("----------------------------");

//calculate
x=(b*b)-(4*a*c);
System.out.println("b*b-4*a*c is "+x);

if(x<0)
System.out.println("Roots are imaginary");
else
{
//calculate roots
t=(int) Math.sqrt(x);
y=(-b+t)/(2*a);
z=(-b-t)/(2*a);
System.out.println("Roots are "+y+" & "+z);
}
}
}


Output

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

How it works
1. The program prints the message to enter values of a,b,c of QE.
2. The user enters values.
3. The QE is solved and printed.

Extending it.
The program is not extendable. There is no direction to extend it.

Explanation.
1. Import the Scanner.
2. Declare the class as public
3. Add the void main function
4. Add system.out.println() function with the message to enter values of QE.
5. Declare input as Scanner.
6. Take the inputs and save it in variables.
7. Sovle Qe and save it in variable.
8. Add system.out.println() function to print the roots.

At the end.
You learnt creating the Java program for Solving Quadratic Equation. So now enjoy the program.


Login to like the post