[go: up one dir, main page]

0% found this document useful (0 votes)
70 views30 pages

Record Oops

Here are the recursive and non-recursive functions to print the nth Fibonacci number: // Recursive function int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); } // Non-recursive function int fibonacci(int n) { int f[] = new int[n+2]; int i; f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i-1] + f[i-2]; } return f[n

Uploaded by

Dheenadayalan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views30 pages

Record Oops

Here are the recursive and non-recursive functions to print the nth Fibonacci number: // Recursive function int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); } // Non-recursive function int fibonacci(int n) { int f[] = new int[n+2]; int i; f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i-1] + f[i-2]; } return f[n

Uploaded by

Dheenadayalan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Department of Computer Science and Engineering

KPR Institute of Engineering and Technology

B.E. – COMPUTER SCIENCE AND ENGINEERING

LABORATORY RECORD

U19CS405 –
OBJECT ORIENTED PROGRAMMING
AND ADVANCED
DATA STRUCTURES

(Regulation 2019)

APRIL 2022
KPR INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)

COIMBATORE – 641 407

LABORATORY RECORD

Name : ……………………………………………………………….

Roll Number : ……………………………………………………………….

Subject Code & Title: ……………………………………………………………….

Department : ……………………………………………………………….

Year & Semester : ……………………………………………………………….

This is the certified record of work done by………………………………………….

Register Number………………………………………………………

Staff In- Charge Head of the Department

Place:

Date:

He/ She has submitted the record for the End Semester Practical
Examination held on ……………………

Internal Examiner External Examiner


TABLE OF CONTENTS

S.NO DATE NAME OF THE EXPERIMENT PAGE MARKS SIGN


NO.
3
1 Quadratic equation

5
2 The Fibonacci Sequence

8
3 User Interface

12
4 Abstract Class

14
5 String Tokenizer

16
6 AgeOutOfRangeException

17
7 Fibonnacci Heap

The BFS and DFS on a graph 23


8

Total
Vision of the Institution

To become a premier institute of academic excellence by imparting technical,


intellectual and professional skills to students for meeting the diverse needs of the
industry, society, the nation and the world at large.

Mission of the Institution


1. Commitment to offer value-based education and enhancement of
practical skills
2. Continuous assessment of teaching and learning process through
scholarly activities
3. Enriching research and innovative activities in collaboration with
industry and institute of repute
4. Ensuring the academic process to uphold culture, ethics and
social responsibility

Vision of the Department


To foster the students by providing learner centric teaching environment, continuous
learning, research and development to become thriving professionals and
entrepreneurs to excel in the field of computer science and contribute to the society.

Mission of the Department


1. Providing value-based education and contented learning experience to the students
2. Educating the students with the state of art technologies and cultivating their
proficiency in analytical and designing skills
3. Enabling the students to achieve a successful career in Computer Science and
Engineering or related fields to meet the changing needs of various stakeholders
4. Guiding the students in research by nurturing their interest in continuous learning
towards serving the society and the country
List of Exercise

List of Experiments:

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 quadratic formula.If the discriminate b2-4ac is negative ,display a message
stating that there are no real solutions?
2. The Fibonacci sequence is defined by the following rule: The fist two values in the sequence
are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java
program that uses both recursive and non recursive functions to print the nth value in
theFibonacci sequence.
3. Write a program that creates a user interface to perform integer divisions. The user enters
two numbers in the textfields, Num1 and Num2. The division of Num1 and Num2 is displayed
in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the
program would throw a NumberFormatException. If Num2 were Zero, the program would throw
an ArithmeticException Display the exception in a message dialog box.
4. Write a java program to create an abstract class named shape that contains two integers and
an empty method named printArea(). Provide three classes named Rectangle, Triangle and
Circle such that classes contain only the method printArea() that prints the area of the given
shape.
5. Write a Java program that reads a line of integers, and displays each integer,
and the sum of all the integers ( uses StringTokenizer class of java.util).
6. Create an exception class named AgeOutOfRangeException extended from the class
Exception. This class should contain a constructor with no parameter to call the Exception class
constructor with the message "You are older than the requested age (25 years)".
7. Write a java program to create fibonnacci Heap and perform the basic operation.
8. Write a java program to implement and perform the BFS and DFS on a graph.

List of Experiments:

Cycle 1
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 quadratic formula.If the discriminate b2-4ac is negative ,display a message
stating that there are no real solutions?
2. The Fibonacci sequence is defined by the following rule: The fist two values in the sequence
are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java
program that uses both recursive and non recursive functions to print the nth value in
theFibonacci sequence.
3. Write a program that creates a user interface to perform integer divisions. The user enters
two numbers in the textfields, Num1 and Num2. The division of Num1 and Num2 is displayed
in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the
program would throw a NumberFormatException. If Num2 were Zero, the program would
throw an ArithmeticException Display the exception in a message dialog box.

4. Write a java program to create an abstract class named shape that contains two integers and
an empty method named printArea(). Provide three classes named Rectangle, Triangle and
Circle such that classes contain only the method printArea() that prints the area of the given
shape.

Cycle 2

1. Write a Java program that reads a line of integers, and displays each integer, and the
sum of all the integers ( uses StringTokenizer class of java.util).
2. Create an exception class named AgeOutOfRangeException extended from the class
Exception. This class should contain a constructor with no parameter to call the
Exception class constructor with the message "You are older than the requested age
(25 years)".

3. Write a java program to create fibonnacci Heap and perform the basic operation.

4. Write a java program to implement and perform the BFS and DFS on a graph
Ex. No.:1
Quadratic equation
Date:

AIM:
To write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0 and
display a message stating that there are no real solutions if the discriminate b2-4ac is negative.

Algorithm:
Step 1: Start
Step 2: Declare and initialize the required variables
Step 3: Get input value from the user and calculate (b*b)-(4*a*c)
Step 4: Check if (b*b)-(4*a*c) is equal to 0 if yes go to step 5 else go to step 6
Step 5: Display ‘roots are real and equal’ and assign the value of f as 1
Step 6: Check if (b*b)-(4*a*c) is greater than 0 if yes go to step 7 else go to step 8
Step 7: Display ‘roots are real and unequal’ and assign the value of f as 1
Step 8: Display ‘roots are imaginary’
Step 9: Check if f value is equal to 1 if yes then display the roots of the quadratic equation
Step 10: Stop

CODING
import java.util.*;
class Roots
{
public static void main(String args[])
{
int a,b,c,d,f=0;
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter the values of a ,b ,c : ");
a=scr.nextInt();
b=scr.nextInt();
c=scr.nextInt();
d=(b*b)-(4*a*c);
if(d==0)
{
System.out.println("Roots are real and Equal");
f=1;
}
else if(d>0)
{
System.out.println("Roots are real and UnEqual");
f=1;
}
else
System.out.println("Roots are imaginary");
if(f==1)
{
float r1=(float)(-b+Math.sqrt(d))/(2*a);
3|Page
float r2=(float)(-b-Math.sqrt(d))/(2*a);
System.out.println("Roots are : "+r1+" ,"+r2);
}
}
}
OUTPUT SCREEN SHOT

RESULT:

The above program has been compiled and executed successfully.

4|Page
THE FIBONACCI SEQUENCE
Ex. No.:2

Date:

AIM:
To write a Java program that uses both recursive and non-recursive functions to print the nth
value in the Fibonacci sequence.

Algorithm:
Step 1: Start
Step 2: Declare and initialize the required variables
Step 3: Get input value from the user
Step 4: Create an object for the class
Step 5: Call non-recursive function while passing the parameters
Step 6: Use for loop to find the nth value in the series and display it
Step 7: Call recursive function while passing the parameters
Step 8: Check if the given value is greater than 2 if yes go to step 9
Step 9: Find the nth value in the series using recursion and display it
Step 10: Stop

CODING
import java.util.*;
class Function
{
void nrcf(int a,int b,int c,int n)
{
for(int i=1;i<=n-2;i++)
{
c=a+b;
a=b;
b=c;
}
a=b=1;
System.out.println("nth value in the series using non recursive function is : "+c);
}
void rcf(int a,int b,int c,int n)
{
if(n-2>0)
{
c=a+b;
a=b;
b=c;
rcf(a,b,c,n-1);
return;
}
System.out.println("\nnth value in the series using recursive function is : "+c);
}
}
5|Page
class Fibonacci
{
public static void main(String args[])
{
Function f=new Function();
int n,a=1,b=1,c=0;
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter n value: ");
n=scr.nextInt();
f.nrcf(a,b,c,n);
f.rcf(a,b,c,n);
}
}

OUTPUT SCREEN SHOT

6|Page
RESULT:

The above program has been compiled and executed successfully.

7|Page
Ex. No.:3
User Interface
Date:

AIM:
To write a Java program that creates a user interface to perform integer divisions which gets
two numbers as input from the users and display the output of the integer division.

Algorithm:
Step 1: Start
Step 2: Create a class that has the function which holds the design of user interface
Step 3: Get input value from the user
Step 4: Check if the second number is equal to 0 if yes go to step 5 else go to step 6
Step 5: Display ‘division by 0 is undefined’
Step 6: Find the answer for the integer division and display the result
Step 7: Stop

CODING

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="DivApplet" width=350 height=300>
</applet>
*/
public class DivApplet extends JApplet implements ActionListener{
JTextField number1,number2,result;
JButton divide;
public void init(){
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
});
}
catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
8|Page
private void makeGUI(){
setLayout(new FlowLayout());
Label number1p = new Label("Number1: ",Label.RIGHT);
Label number2p = new Label("Number2: ",Label.RIGHT);
number1= new JTextField(20);
number2 = new JTextField(20);
result = new JTextField(20);
divide = new JButton("Divide");
add(number1p);
add(number1);
add(number2p);
add(number2);
add(result);
add(divide);
divide.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String snumber1,snumber2;
snumber1 = number1.getText();
snumber2 = number2.getText();
try{
int number1 = Integer.parseInt(snumber1);
int number2 = Integer.parseInt(snumber2);
if(number2==0)
JOptionPane.showMessageDialog(null, "Division by zero not defined.");
else{
double r = (double)number1/number2;
result.setText(((Double)r).toString());
}
}
catch(NumberFormatException ne)
{
JOptionPane.showMessageDialog(null,"Enter a number");
}
}
}

9|Page
SCREEN SHOT

10 | P a g e
RESULT:

The above program has been compiled and executed successfully

11 | P a g e
Ex. No.:4
Abstract Class
Date:

AIM:
To write a Java program that creates an abstract class named shape that contains two integers and
an empty method named printArea() and prints the area of the given shape.

Algorithm:
Step 1: Start
Step 2: Create an abstract class named shape under which there are subclasses of different shapes
Step 3: Create object for the sub classes
Step 4: Call the function of the class while passing parameters
Step 5: Display the area of that shape subclass
Step 6: Stop

CODING

import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
12 | P a g e
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);

SCREEN SHOT

RESULT:

The above program has been compiled and executed successfully

13 | P a g e
Ex. No.:5
StringTokenizer
Date:

AIM:
To write a Java program that reads a line of integers, and displays each integer, and the sum of
all the integers

Algorithm:
Step 1: Start
Step 2: Declare and initialize the required variables
Step 3: Get input value from the user
Step 4: Read the input line of integers
Step 5: Display each integer
Step 6: Find the sum of all the integers
Step 7: Display the sum of all the integers
Step 8:Stop

CODING

import java.util.*;
class StringTokenizerDemo {
public static void main(String args[]) {
int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("sum of the integers is: " + sum);
sc.close();
}
}

14 | P a g e
SCREEN SHOT

RESULT:

The above program has been compiled and executed successfully

15 | P a g e
Ex. No.:6
AgeOutOfRangeException
Date:

AIM:
To write a Java program that creates an exception class named AgeOutOfRsnge Expectations

Algorithm:
Step 1: Start
Step 2: Create a sub class
Step 3: If the age is out of the range of expectations display ‘you are older than the requested age’
Step 4: Stop

CODING
public class AgeOutOfRangeException extends Exception {
public AgeOutOfRangeException() {
super("You are older than the requested age (25 years)");
}
public AgeOutOfRangeException(String message)
{
super(message);
}
}

OUTPUT

("You are older than the requested age (25 years)

RESULT:

The above program has been compiled and executed successfully

16 | P a g e
Ex. No.:7 Fibonnacci Heap
Date:

AIM:
To write a Java program that creates Fibonacci Heap and performs the basic operation.

Algorithm:
Step 1: Start
Step 2: Create the required classes and member functions

Step 3: Get input value from the user about which operation they want to perform:

1. Insert element
2. Check if heap is empty
3. Clear heap
Step 4: Using switch case, if its case 1 get input of the element to be inserted. If its case to display
if the heap is empty or not. If its case 3 clear the heap and for default case display ‘wrong entry’

Step 5: Ask if the user want to perform the operations if yes go to step 3 else go to step 6

Step 6: Stop

CODING

import java.util.*;
/* Fibonacci Heap Node **/
class FibonacciHeapNode
{
FibonacciHeapNode child, left, right, parent;
int element;
/** Constructor **/
public
FibonacciHeapNode(int element)
{
this.right = this;
this.left = this;
this.element = element;
}
}
/** Class FibonacciHeap **/
class FibonacciHeap
{
private
FibonacciHeapNode root;
privateint count;
17 | P a g e
/** Constructor **/
public
FibonacciHeap()
{
root = null;
count = 0;
}
/** Check if heap is empty **/
publicboolean isEmpty()
{
return root == null;
}
/** Make heap empty **/
publicvoid clear()
{
root = null;
count = 0;
}
/** Function to insert **/
publicvoid insert(int element)
{
FibonacciHeapNode node = new FibonacciHeapNode(element);
node.element = element;
if (root != null)
{
node.left = root;
node.right = root.right;
root.right = node;
node.right.left = node;
if (element < root.element)
root = node;
}
else
root = node;
count++;
}
/** function to display **/
publicvoid display()
{
System.out.print("\nHeap = ");
FibonacciHeapNode ptr = root;
if (ptr == null)
{
System.out.print("Empty\n");
return;
}
do
{
System.out.print(ptr.element + " ");
ptr = ptr.right;
18 | P a g e
} while (ptr != root && ptr.right != null);
System.out.println();
}
}
/** Class FibonacciHeapTest **/
publicclass FibonacciHeapTest
{
publicstaticvoid main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("FibonacciHeap Test\n\n");
FibonacciHeap fh = new FibonacciHeap();
char ch;
/** Perform FibonacciHeap operations **/
do
{
System.out.println("\nFibonacciHeap Operations\n");
System.out.println("1. insert element ");
System.out.println("2. check empty");
System.out.println("3. clear");
int choice = scan.nextInt();
switch (choice)
{
case 1:
System.out.println("Enter element");
fh.insert(scan.nextInt());
break;
case 2:
System.out.println("Empty status = " + fh.isEmpty());
break;
case 3:
fh.clear();
break;
default:
System.out.println("Wrong Entry \n ");
break;
}
fh.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
} while (ch == 'Y' || ch == 'y');
}
}

19 | P a g e
Fibonacci Heap Test

OUTPUT:

FibonacciHeap Operations

1. insert element
2. check empty
3. clear
1
Enter element
24

Heap = 24

Do you want to continue(Type y or n)


y

FibonacciHeap Operations

1. insert element
2. check empty
3. clear
1
Enter element
6

Heap = 6 24

Do you want to continue(Type y or n)


y

FibonacciHeap Operations

1. insert element
2. check empty
3. clear
1
Enter element
28

20 | P a g e
Heap = 6 28 24

Do you want to continue(Type y or n)


y

FibonacciHeap Operations

1. insert element
2. check empty
3. clear
1
Enter element
14

Heap = 6 14 28 24

Do you want to continue(Type y or n)


y

FibonacciHeap Operations

1. insert element
2. check empty
3. clear
1
Enter element
63

Heap = 6 63 14 28 24

Do you want to continue(Type y or n)


y

FibonacciHeap Operations

1. insert element
2. check empty
3. clear
2
Empty status = false

Heap = 6 63 14 28 24

Do you want to continue(Type y or n)


y

FibonacciHeap Operations

21 | P a g e
1. insert element
2. check empty
3. clear
3

Heap = Empty

Do you want to continue(Type y or n) y

FibonacciHeap Operations

1. insert element
2. check empty
3. clear
2
Empty status = true

Heap = Empty

Do you want to continue(Type y or n)

RESULT:

The above program has been compiled and executed successfully.

22 | P a g e
Ex. No.:8 The BFS and DFS on a graph
Date:

AIM:
To write a Java program that implements and performs the BFS and DFS on a graph

Algorithm:
Step 1: Start
Step 2: Create the necessary classes and member functions
Step 3: Set Status=1 (ready state) for each node in G
Step 4: Enqueue the starting node A and set its Status=2 (waiting state)
Step 5: Repeat step 4 and 5 until Queue is empty
Step 6: Dequeue a node N. Process it and set its Status=3 (process
Status)
Step 7: Enqueue all the neighbors of N that are in the ready state
(Whose Status=1) and set.
Step 8: Stop

CODING

// Java program to print BFS traversal from a given source vertex.


// BFS(int s) traverses vertices reachable from s.
import java.io.*;
import java.util.*;
// This class represents a directed graph using adjacency list
// representation
class Graph
{
private
int V; // No. of vertices
private
LinkedList<Integer> adj[]; //Adjacency Lists
// Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// Java program to print DFS
// mtraversal from a given given
// graph
import java.io.*;

23 | P a g e
import java.util.*;
// This class represents a
// directed graph using adjacency
// list representation
class Graph
{
private
int V; // No. of vertices
// Array of lists for
// Adjacency List Representation
private
LinkedList<Integer> adj[];
// Constructor
@SuppressWarnings("unchecked") Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v, int w)
{
adj[v].add(w); // Add w to v's list.
}
// A function used by DFS
void DFSUtil(int v, boolean visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v + " ");
// Recur for all the vertices adjacent to this
// vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}
// The function to do DFS traversal.
// It uses recursive
// DFSUtil()
void DFS(int v)
{
// Mark all the vertices as
// not visited(set as
// false by default in java)
boolean visited[] = new boolean[V];
24 | P a g e
// Call the recursive helper
// function to print DFS
// traversal
DFSUtil(v, visited);
}
// Driver Code
public
static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println(
"Following is Depth First Traversal " + "(starting from vertex 2)");
g.DFS(2);
}
}
// Function to add an edge into the graph
void
addEdge(int v, int w)
{
adj[v].add(w);
}
// prints BFS traversal from a given source s
void BFS(int s)
{
// Mark all the vertices as not visited(By default
// set as false)
boolean visited[] = new boolean[V];
// Create a queue for BFS
LinkedList<Integer> queue = new LinkedList<Integer>();
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.add(s);
while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(s + " ");
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
25 | P a g e
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
// Driver method to
public
static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Breadth First Traversal " +
"(starting from vertex 2)");
g.BFS(2);
}
}

Output:

Following is Breadth First Traversal (starting from vertex 2)


2031

RESULT:

The above program has been compiled and executed successfully.

26 | P a g e

You might also like