Worksheet 1 Java Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Student Name: Aryaman Sharma UID: 20BCS4206

Branch: CSE-CC2 Section/Group: 20CC2/B


Semester: 3 Date of Performance: 31/08/2021
Subject Name: Programming in java lab Subject Code: 21O-20CSP-235

1. Aim/Overview of the practical:

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:

For calculating the roots of quadratic equation

First calculate determinant, D=b2−4 ac

−b ± √ D
And then for calculating roots, x=
2a

5. Output:

Learning outcomes:
1. Learn the concept to import libraries in java.

2. Learn the concept of classes.

3. Learn the concept of methods.

Evaluation Grid (To be created as per the SOP and Assessment guidelines by the faculty):

Sr. No. Parameters Marks Obtained Maximum Marks


1.
2.
3.

You might also like