Worksheet 1 Java Lab
Worksheet 1 Java Lab
Worksheet 1 Java Lab
Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c = 0. Read in a,
b, c and use the quadratic formula. If the discriminate b2-4ac is negative, display a message stating
that there are no real solutions.
2. Algorithm/Flowchart:
START
Import library for scan the input from user import java.util.Scanner;
Take the inputs of a,b,c from the user.
Calculate Discriminant by D=b^2-4ac.
Calculate the roots by x= (-b ± √D)/2a.
Use if else statement for different condition.
Print the roots of quadratic equation by System.out.println.
STOP
3. Code:
import java.util.Scanner;
public class quadraticequation {
public static void main(String args[])
{
Scanner scanvalue = new Scanner(System.in);
double x1,x2,det,a,b,c;
System.out.println("Enter the value of a ");
a= scanvalue.nextDouble();
System.out.println("Enter the value of b ");
b= scanvalue.nextDouble();
System.out.println("Enter the value of c ");
c= scanvalue.nextDouble();
det = (b*b) - (4*a*c);
if(det == 0)
{
System.out.println("Roots are real and equal ");
x1 = x2 = -b/(2*a);
System.out.println("Roots for quadritic equation " + a + "x^2 + " + b + "x + " + c +
" is ");
System.out.println( x1 + " and " + x2 + "\n");
}
else if(det > 0)
{
System.out.println("Roots are real and unequal");
x1 = (-b + Math.sqrt(det))/(2*a);
x2 = (-b - Math.sqrt(det))/(2*a);
System.out.println("Roots for quadritic equation " + a + "x^2 + " + b + "x + " + c +
" is ");
System.out.println( x1 + " and " + x2 + "\n");
}
else
{
System.out.println("roots are imaginary");
}
}
}
4. Formulas used:
−b ± √ D
And then for calculating roots, x=
2a
5. Output:
Learning outcomes:
1. Learn the concept to import libraries in java.
Evaluation Grid (To be created as per the SOP and Assessment guidelines by the faculty):