Mycnis.weebly.com



DATA STRUCTURES AND ALGORITHMS LAB

PROGRAMS ON DATA STRUCTURES:

(1) 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 discriminant b2 -4ac is negative, display a message stating that there are no real solutions.

import java.io.*;

class QuadraticEquationPgm1

{

public static void main(String args[]) throws IOException

{

double a, b, c, sq, r1, r2;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the value of a");

a = Float.parseFloat(br.readLine());

System.out.println("enter the value of b");

b = Float.parseFloat(br.readLine());

System.out.println("enter the value of c");

c = Float.parseFloat(br.readLine());

sq = Math.sqrt(b * b - 4 * a * c);

if (sq == 0)

{

r1 = -b / (2 * a);

r2 = r1;

System.out.println("The roots are real and equal");

System.out.println("The roots are:" + r1 + "," + r2);

}

else if (sq > 0)

{

r1 = (-b + sq) / (2 * a);

r2 = (-b - sq) / (2 * a);

System.out.println("The roots are real but not equal");

System.out.println("The roots are:" + r1 + "," + r2);

}

else

{

System.out.println("There are no real solutions");

}

}

}

(2) The Fibonacci sequence is defined by the following rule. The first two values in the sequence are 1 and 1. Every subsequent value is the run of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence.

import java.io.*;

class Fibonacci

{

int a1,a2,a3,num,i;

int fibRec(int x)

{

if(x==0)

return 0;

else if(x==1)

return 1;

else

return (fibRec(x-1)+fibRec(x-2));

}

int fibNonRec(int y)

{

a1=1;

a2=1;

num=y;

for(i=3;i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download