0% found this document useful (0 votes)
32 views

OOPs & DS LAB Manual

The document contains a laboratory record for a course on Object Oriented Programming and Data Structures. It includes details like the student name, branch, batch, year and semester. It also contains a list of experiments conducted with details like date, name of exercise and signature.

Uploaded by

M. Pon Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

OOPs & DS LAB Manual

The document contains a laboratory record for a course on Object Oriented Programming and Data Structures. It includes details like the student name, branch, batch, year and semester. It also contains a list of experiments conducted with details like date, name of exercise and signature.

Uploaded by

M. Pon Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

FRANCIS XAVIER ENGINEERING

COLLEGE (AUTONOMOUS),
TIRUNELVELI

DEPARTMENT OF ELECTRONICS AND


COMMUNICATION ENGINEERING

LABORATORY RECORD

21EC3511 - Object Oriented


Programming
2022 - 2023 and Data
/ODD SEMESTER
Structures

REGISTER NUMBER:

STUDENT NAME :

BRANCH :ELECTRONICS AND


COMMUNICATION ENGINEERING

BATCH :2021 – 2025 BATCH

YEAR/SEMESTER : II YEAR / III SEMESTER


FRANCIS XAVIER ENGINEERING
COLLEGE (AUTONOMOUS),
TIRUNELVELI-627003

REG NO ………………………………

BONAFIDE CERTIFICATE

Certified that this is a bonafide record of work done by Selvan /Selvi

………………………………………………………………………….. with Reg.No

……………………………..… of I Year / II Semester in ELECTRONICS AND

COMMUNICATION ENGINEERING Branch of this institution in the 21EC511-

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

LABORATORY during 2022-2023.

Staff-in Charge HOD

Submitted for the Practical Examination held on …………………

External Examiner Internal Examiner


LIST OF EXPERIMENTS

S.No Date Name of the Exercise Pg.No Marks Signatur


e
1 Basic Programs for Java Concepts

2 Program to define inheritance and


show method overriding.

3 Program to demonstrate Exception Handling.

4 Program to demonstrate Multithreading.

5 Array implementation of List Abstract


Data Type (ADT)
6 Linked list implementation of List ADT

7 Stack ADT – Array and linked list


implementations
8 Evaluation of a postfix expression
using Stack.
9 Queue ADT – Array and linked
list implementations.
10 Implementation of Binary Tree Traversals.

11 Implementation of Graph Traversals.


EX:01(a) Basics of JAVA
SIMPLE CLASS PROGRAM
DATE:

AIM:
To write a JAVA program to display the name and age of the person using Class.

ALGORITHM

1. Include the header files.


2. Get name and age.
3. Using the next line function returns the String from the current position to the end of the line
4. Using the next int function reads in a string of digits (characters) and converts them into an int type
5. Print the values
6. Compile and run the program

PROGRAM:
import java.util.*;
class prg
{
public static void main()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter your name :");
String st=s.nextLine();
System.out.println("Enter your age :");
int age=s.nextInt();
System.out.println("Enter your year of birth :");
String yr=s.nextLine(); System.out.println("Name :"+st);
System.out.println("Age :"+age);
System.out.println("Year of birth :"+yr);
}
}

OUTPUT:

RESULT:
EX:01(b) Basics of JAVA
SWAPPING OF TWO NUMBERS

DATE:

AIM:
To write a Java program for swapping of two numbers.

ALGORITHM:
1.Include the header files.
2.Declare a function named ‘swap’.
3.Read two numbers a and b.
4. Call that function in the main program
5. For Call by value, pass the value when we call that function
6.For Call by reference, assign the address to the pointer
7.Print the swapped values
8.Compile and run the program

PROGRAM

//call by value

public class Tester


{
public static void main(String[] args)

{ int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
//Call by reference

public class JavaTester {


public static void main(String[] args) {
IntWrapper a = new IntWrapper(30);
IntWrapper b = new IntWrapper(45);
System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be different here**:");
System.out.println("After swapping, a = " + a.a + " and b is " + b.a);
}
public static void swapFunction(IntWrapper a, IntWrapper b) {
System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);
// Swap n1 with n2
IntWrapper c = new IntWrapper(a.a);
a.a = b.a;
b.a = c.a;
System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);
}
}
class IntWrapper {
public int a;
public IntWrapper(int a){ this.a = a;}
}
OUTPUT:

RESULT:
EX:01(c) Basics of JAVA
STATIC CLASS MEMBER
DATE:

AIM:
To write a Java program to demonstrate static class member.

ALGORITHM:

1.Create a inner class called reptile


2.Create a static class called mammal
3. Create a object creation of the outer class
4. Create a object of the static nested class
5. Display the information
8.Compile and run the program

PROGRAM:

/ inner class
class Reptile {
public void displayInfo() {
System.out.println("I am a reptile.");
}
}

// static class
static class Mammal {
public void displayInfo() {
System.out.println("I am a mammal.");
}
}
}

class Main {
public static void main(String[] args) {
// object creation of the outer class
Animal animal = new Animal();

// object creation of the non-static class


Animal.Reptile reptile = animal.new Reptile();
reptile.displayInfo();
// object creation of the static nested class
Animal.Mammal mammal = new Animal.Mammal();
mammal.displayInfo();

}
}

OUTPUT:

RESULT:
EX:02 Program to Define Inheritance and Show Method
Overriding.
DATE:

AIM
To develop java program using abstract class

ALGORITHM:

Step 1: Start the program


Step 2: Create the abstract class Shape that contains two integers and an empty method named print Area().
Step 3: Create three classes named Rectangle, Triangle, Circle. These three classes are inherited from abstract
class Shape.
Step 4: Each one of the classes contains only the method print Area () that prints the area of the given shape.
Step 5: Execute the main class AbstractAreas . In this class the input values are given. Then calculate the Print
Area.
Step 6: Stop the program.

PROGRAM

abstract class Shape


{
double dim1;
double dim2;
abstract void printarea();
}
class Rectangle extends Shape
{
Rectangle(double a,double b)
{
dim1=a;
dim2=b;
}
void printarea()
{
System.out.println("Area of Rectangle:"+dim1*dim2);
}}
class Triangle extends Shape
{
Triangle(double a,double b)
{
dim1=a;
dim2=b;
}
void printarea()
{
System.out.println("Area of Triangle:"+(dim1*dim2)/2);
}}
class Circle extends Shape
{
Circle(double a)
{
dim1=a;
}
void printarea()
{
System.out.println("Area of Circle:"+3.14*dim1*dim1);
}}
class AbstractAreas
{
public static void main(String args[])
{
Rectangle r=new Rectangle(7,5);
Triangle t=new Triangle(5,3);
Circle c=new Circle(7);
Shape s;
s=r;
s.printarea();
s=t;
s.printarea();
s=c;
s.printarea();
}}

OUTPUT:

RESULT:
EX:03 Programs to Demonstrate Exception Handling
DATE:

AIM

To write a Java program to implement user defined exception handling

ALGORITHM

Step 1: Start the program


Step 2: create the class InvalidAgeException that is inherited from Exception class
Step 3: Create validate function using throws keyword.
Step 4: Based on Exception handling customer or user defined exception handling is to be done.
Step 5: if the age is less than 18, throws not Eligible to vote.
Step 6: if the age is greater than 18, Welcome to vote is printed.
Step 6: Stop the program.

PROGRAM

class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}}
class CustomException
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not Eligible to vote");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try
{
validate(20);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}}}
OUTPUT:

RESULT:
EX:4 Programs to Demonstrate Multithreading
DATE:

AIM
To develop java program to perform multi threading

ALGORITHM:

Step 1: Start the program


Step 2: Create three threads First thread generates a random integer every 1 second and if the value is even,
second thread computes the square of the number and prints.
Step 3: If the value is odd, the third thread will print the value of cube of the number.
Step 4: Stop the program.

PROGRAM

import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x);
}}
class odd implements Runnable
{
public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);
}}
class A extends Thread
{
public void run()
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
} else {
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("-------------------------------------");
}}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}}}
public class Multithread
{
public static void main(String[] args)
{
A a = new A();
a.start();
}}

OUTPUT:
RESULT:
EX:5 Array implementation of List ADT
DATE:

AIM:
To write a JAVA program to display the name and age of the person using Class.

ALGORITHM

1. Include the header files.


2. Create a list
3. Perform the create,Display ,insert , Delete and Make Empty operations
4. Print the values
5. Compile and run the program

PROGRAM:

import java.util.*; class


JavaDemo {
public static void main (String[] args) { int[]
priceOfPen= new int[5];
Scanner in=new Scanner(System.in); for(int
i=0;i<priceOfPen.length;i++)
priceOfPen[i]=in.nextInt();
for(int i=0;i<priceOfPen.length;i++)
System.out.print(priceOfPen[i]+" ");
}
}
RESULT:
EX:6 Linked List Implementation of List ADT
DATE:

AIM:
To write a program to implement singly linked list.

ALGORITHM:

1. For insert operation, allocate memory for the new node, add the number given as
input bythe user and add the node at the end of the list.
2. For the delete operation, delete the node with the value given as input by the user.
3. Display all the values present in the list.
4. Display the size which denotes the total number of elements in the list.

PROGRAM:

import java.util.*;
class LLNode{ int
data;
LLNode next;
LLNode(int data)
{
this.data=data;
this.next=null;
}
}
class Demo{
LLNode head;
LLNode insertInBeg(int key,LLNode head)
{
LLNode ttmp=new LLNode(key); if(head==null)
head=ttmp; else
{
ttmp.next=head;
head=ttmp;
}
return head;
}
LLNode insertInEnd(int key,LLNode head)
{
LLNode ttmp=new LLNode(key); LLNode
ttmp1=head; if(ttmp1==null)
head=ttmp; else
{
while(ttmp1.next!=null) ttmp1=ttmp1.next;
ttmp1.next=ttmp;
}
return head;
}
LLNode insertAtPos(int key,int pos,LLNode head)
{
LLNode ttmp=new LLNode(key); if(pos==1)
{
ttmp.next=head;
head=ttmp;
}
else
{
LLNode ttmp1=head;
for(int i=1;ttmp1!=null && i<pos;i++)
ttmp1=ttmp1.next; ttmp.next=ttmp1.next;
ttmp1.next=ttmp;
}
return head;
}
LLNode delete(int pos,LLNode head)
{
LLNode ttmp=head;
if(pos==1)
head=ttmp.next; else
{
for(int i=1;ttmp!=null && i<pos-1;i++)
ttmp=ttmp.next;
ttmp.next=ttmp.next.next;
}
return head;
}
int length(LLNode head)
{
LLNode ttmp=head; int
c=0; if(ttmp==null)
return 0;
else

{
while(ttmp!=null)
{ ttmp=ttmp.next; c+
+;
}
}
return c;
}
LLNode reverse(LLNode head)
{
LLNode prevLNode=null,curLNode=head,nextLNode=null;
while(curLNode!=null)
{
nextLNode=curLNode.next;
curLNode.next=prevLNode;
prevLNode=curLNode;
curLNode=nextLNode;
}
head=prevLNode;
return head;
}
void display(LLNode head)
{
LLNode ttmp=head;
while(ttmp!=null)
{System.out.print(ttmp.data+" "); ttmp=ttmp.next;
}
}
public static void main(String[] args)
{
LinkedListDemo l=new LinkedListDemo(); l.head=null;
Scanner in=new Scanner(System.in); do
{

System.out.println("\n********* MENU *********");


System.out.println("\n1.Insert In End"); System.out.println("\
n2.Insert In Beg"); System.out.println("\n3.Insert At A Particular
Pos"); System.out.println("\n4.Delete At a Pos");
System.out.println("\n5.Length"); System.out.println("\
n6.Reverse"); System.out.println("\n7.Display");
System.out.println("\n8.EXIT"); System.out.println("\nenter ur
choice : ");
int n=in.nextInt();
switch(n)
{case 1: System.out.println("\nenter the value "); l.head=l.insertInEnd(in.nextInt(),l.head);
break;
case 2: System.out.println("\nenter the value"); l.head=l.insertInBeg(in.nextInt(),l.head);
break;
case 3:
System.out.println("\nenter the value"); l.head=l.insertAtPos(in.nextInt(),in.nextInt(),l.head);
break; case 4:
l.head=l.delete(in.nextInt(),l.head); break;
case 5: System.out.println(l.length(l.head)); break;
case 6: l.head=l.reverse(l.head); break;
case 7:
l.display(l.head); break;
case 8: System.exit(0); break;
default: System.out.println("\n Wrong Choice!"); break;
}
System.out.println("\n do u want to cont... ");
}while(in.nextInt()==1);
}
}
else
{
printf("Element(s) in the list are : ");
}
display(n);
break;
case 3:
printf("Size of the list is %d\n",count());
break;
case 4:
if(head==NULL)
printf("List is Empty\n");
else{
printf("Enterthenumbertodelete:");
scanf("%d",&num);
if(delete(num))
printf("%d deleted successfully\n",num);
else
printf("%d not found in the list\n",num);
}
break;
case 5:
return 0;
default:
printf("Invalid option\n");
}
}
}
return 0;

OUTPUT:
RESULT:
EX:7(a) Stack ADT- Array Implementation of Stack
DATE:

AIM:
To write a program to perform array implementation of stack.

ALGORITHM:
1. Initialize the top pointer to be -1.
2. To perform push operation, get the input from the user and add the value to
the stack byincrementing the value of top.
3. To perform the pop operation, the value is deleted by decrementing the top pointer.
4. Display the values in the stack.

PROGRAM
import java.util.*;
class Stack
{
int[] a;
int top;
Stack()
{
a=new int[100];
top=-1;
}
void push(int x)
{
if(top==a.length-1)
System.out.println("overflow");
else
a[++top]=x;
}
int pop()
{
if(top==-1)
{System.out.println("underflow");
return -1;
}
else
return(a[top--]);
}
void display()
{
for(int i=0;i<=top;i++)
System.out.print(a[i]+" ");
System.out.println();
}
boolean isEmpty()
{
if(top==-1)
return true;
else
return false;
}
int peek()
{
if(top==-1)
return -1;
return (a[top]);
}
}
public class Demo
{
public static void main(String args[])
{
Stack s=new Stack();
Scanner in= new Scanner(System.in); do
{System.out.println("\n******** MENU *******");
System.out.println("\n1.PUSH");
System.out.println("\n2.POP");
System.out.println("\n3.PEEK");
System.out.println("\n4 IS EMPTY"); System.out.println("\
n5.EXIT");
System.out.println("\n enter ur choice : ");
switch(in.nextInt())
{
case 1:
System.out.println("\nenter the value ");
s.push(in.nextInt());
break;
case 2:
System.out.println("\n popped element : "+ s.pop());
break;
case 3:
System.out.println("\n top element : "+ s.peek());
break;
case 4:
System.out.println("\n is empty : "+ s.isEmpty());
break;
case 5:
System.exit(0);
break;
default:
System.out.println("\n Wrong Choice!");
break;
}
System.out.println("\n do u want to cont... ");
}while(in.nextInt()==1);
}
}
OUTPUT:
RESULT:
EX:7(b) Stack ADT- Linked List Implementation of Stack
DATE:

AIM:
To write a program to implement stack using linked list.

ALGORITHM:
1. Initially create the header node and assign its next pointer to null.
2. For push operation, allocate memory for creating a temporary node and add the
nodetothe next of header node.
3. For pop operation, delete the node next to the header and free the memory space.
4. Display the values present in the stack

PROGRAM:

import java.util.*;
class LNode
{
int data;
LNode next;
LNode(int d)
{
data=d;
}
}
class Stack
{
LNode push(int d,LNode head)
{
LNode tmp1 = new LNode(d);
if(head==null)
head=tmp1;
else
{
tmp1.next=head;
head=tmp1;
}
return head;
}
LNode pop(LNode head)
{
if(head==null)
System.out.println("underflow");
else
head=head.next;
return head;
}
void display(LNode head)
{
System.out.println("\n list is : ");
if(head==null){
System.out.println("no LNodes");
return;
}
LNode tmp=head;
while(tmp!=null){
System.out.print(tmp.data+" ");
tmp=tmp.next;
}
}
boolean isEmpty(LNode head)
{
if(head==null)
return true;
else
return false;
}
int peek(LNode head)
{
if(head==null)
return -1;
return head.data;
}
}
public class Demo{
public static void main(String[] args)
{
Stack s=new Stack();
LNode head=null;
Scanner in=new Scanner(System.in); do
{
System.out.println("\n******** MENU *******");
System.out.println("\n1.PUSH");
System.out.println("\n2.POP");
System.out.println("\n3.PEEK");
System.out.println("\n4 IS EMPTY");
System.out.println("\n5 DISPLAY");
System.out.println("\n6.EXIT");
System.out.println("\n enter ur choice : ");
switch(in.nextInt())
{
case 1:
System.out.println("\nenter the value ");
head=s.push(in.nextInt(),head);
break;
case 2:
head=s.pop(head);
break;
case 3:
System.out.println("\n top element : "+ s.peek(head));
break;
case 4:
System.out.println("\n is empty : "+ s.isEmpty(head));
break;
case 5:
s.display(head);
break;
case 6:
System.exit(0);
break;
default:
System.out.println("\n Wrong Choice!");
break;
}
System.out.println("\n do u want to cont... ");
}while(in.nextInt()==1);
}
}
OUTPUT:

RESULT:
EX:8 Evaluation of a Postfix Expression Using a Stack
DATE:

AIM:

To write a C program for evaluating postfix expression using stack.

ALGORITHM:

1. Get the postfix expression as input from the user.


2. Create a stack to store operands.
3. Scan the expression and do the following
a. If the element is a number, push it into the stack.
b. If the element is an operator, pop the operands for the operator from
the stack.Evaluate the operator and push the result back to the stack.
4. When the expression is ended, the number in thestack is the final answer.

PROGRAM:

#include <stdio.h> #include


<ctype.h> #define
MAXSTACK100
#define POSTFIXSIZE 100
int stack[MAXSTACK];int
top = -1;
void push(int item)
{
if (top >= MAXSTACK - 1) {
printf("stack over flow");
return;
} else {
top = top + 1;
stack[top]=item;
}}
int pop()
{
int item;
if (top < 0) {
printf("stack under flow");
} else {
item = stack[top];
top = top - 1;
}
return item;
}
void EvalPostfix(char postfix[])
{
int i;char ch;int val;intA,B;
for (i = 0; postfix[i] != ')'; i+
+)
{
ch = postfix[i];
if (isdigit(ch)) {
push(ch - '0');
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
A = pop();
B = pop();
switch (ch) /* ch is an operator */
{
case '*':
val = B * A;break;
case '/':
val = B /
A;break; case '+':
val = B +
A;break; case '-':
val = B - A;break;
} push(val);
} }
printf(" \n Result of expression evaluation : %d \n",
pop());}
int main()
{
int i;
char postfix[POSTFIXSIZE];
printf("ASSUMPTION: There are only four operators(*, /, +, -) in an expression and operand issingle
digit only.\n");
printf(" \nEnter postfix expression,\n press right parenthesis ')' for end expression : ");
for (i = 0; i <= POSTFIXSIZE - 1; i++)
{
scanf("%c", &postfix[i]);
if (postfix[i] == ')') /* is there any way to eliminate this if */
{
break;
} /* and break statement */
}
EvalPostfix(postfix);
getch();
return 0;
}
OUTPUT:

RESULT:
EX:9(a) Queue ADT- Array implementation of Queue
DATE:

Aim:
To write a C program for array implementation of queue.

Algorithm:

1. Initialize the values of rear and front to be -1.


2. Insert operation is done by incrementing the value of rear and placing the value in
the corresponding position.
3. Delete operation is done by incrementing the front pointer and deleting the value
atthat position.
4. Display the values present in the queue.

Program:

#include <stdio.h>
#include <conio.h>
#define max 5
static int
queue[max];int front = -
1;
int rear=-1; void
insert(intx)
{
queue[++rear] = x;
if (front == -1)
front = 0;
}
int rem()
{
int val;
val = queue[front];
if (front==rear && rear==max-
1) front = rear = -1;
else front+
+; return
(val);
}
void view()
{
int i;
if (front == -1)
printf("\n Queue Empty \
n"); else
{ printf("\n Front-->");
for(i=front; i<=rear; i++)
printf("%4d", queue[i]);
printf("<--Rear\n");
}
}
void main()
{
int d,ch= 0,val;clrscr();while(ch != 4)
{
printf("\n QUEUE OPERATION \
n"); printf("1.INSERT");
printf("2.DELETE");
printf("3.VIEW");
printf("4.QUIT\n");
printf("Enter Choice :
"); scanf("%d", &ch);
switch(ch)
{
case 1:
if(rear < max-1)
{
printf("\n Enter element to be inserted : ");
scanf("%d", &val);
insert(val);
}
else
printf("\n Queue Full \
n"); break;
case 2:
if(front == -1)
printf("\n Queue Empty \
n"); else
{
d=rem();
printf("\n Element deleted : %d \n",d);
}
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\n Invalid Choice \n");

}}}
OUTPUT:

RESULT:
EX:9(b) Queue ADT- Linked List Implementation of Queue
DATE:
AIM:

To write a program for implementing queue using linked list.

ALGORITHM:

1. Initially create the header node and assign its next pointer to null.
2. For insert operation, allocate memory for the new node and insert the node next to
the header.
3. For delete operation, delete the last node in the list and free the memory space.\
4. Display the values available in the queue.

PROGRAM:

#include <stdio.h>
#include<conio.h>
#include <process.h>
#include <alloc.h> struct
node
{
int label;
struct node *next;
};
main()
{
int ch=0;int k;
struct node *h, *temp, *head;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct
node)); head->next = NULL;
while(1)
{
printf("\n Queue using Linked List \n");
printf("1->Insert ");
printf("2->Delete ");printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice :
"); scanf("%d", &ch);
switch(ch)
{
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
/* Reorganize the links */
h = head;
while (h->next !=
NULL); h = h->next;
h->next = temp;
temp->next =
NULL; break;

case 2:
/* Delink the first node */h = head-
>next;
head->next = h->next;
printf("Node deleted \n");
free(h); break;

case 3: printf("\n\
nHEAD -> "); h=head;
while (h->next!=NULL)
{
h = h->next;
printf("%d -> ",h->label);
}

case 4:
printf("NULL \n");break;
exit(0);
}
}
}

OUTPUT:
RESULT:
EX:10 Implementation of Binary Trees and Traversals
DATE:

AIM:
To write a program to implement binary trees and traversals.

ALGORITHM:

1. Get the input from the user and create a binary tree such that the root is greater
thantheleft child and less than the right child.
2. For inorder traversal
a) Traverse the left subtree, i.e., call Inorder(left-subtree)
b) Visit the root.
c) Traverse the right subtree, i.e., call Inorder(right-subtree)
3. For preorder traversal
a) Visit the root.
b) Traverse the left subtree, i.e., call Preorder(left-subtree)
c) Traverse the right subtree, i.e., call Preorder(right-subtree)
4. For postorder traversal
a) Traverse the left subtree, i.e., call Postorder(left-subtree)
b) Traverse the right subtree, i.e., call Postorder(right-subtree)
c) Visit the root.
5. Display the results

PROGRAM:

#include<stdio.h>
#include<conio.h> struct
node
{
int data;
struct node *right,*left;
}
*root,*p,*q;
struct node *make(int y)
{
struct node *newnode;
newnode=(struct node *)malloc(sizeof(struct
node)); newnode->data=y;
newnode->right=newnode->left=NULL;return(newnode);
}
void left(struct node *r,int x)
{
if(r->left!=NULL)printf("\n invalid!");else
r->left=make(x);
}
void right(struct node *r,int x)
{
if(r->right!=NULL)printf("\n invalid!");else
r->right=make(x);
}
void inorder(struct node *r)
{if(r!=NULL)
{
inorder(r->left);printf("\t %d",r->data);
inorder(r->right);
}}
void preorder(struct node *r)
{ if(r!=NULL)
{
printf("\t%d",r->data);
preorder(r->left);
preorder(r->right);
}
}
void postorder(struct node *r)
{if(r!=NULL)
{
postorder(r->left);postorder(r->right);
printf("\t%d",r->data);
}
}
void main()
{
int no;
int choice;char ch;clrscr(); printf("\n
enter the root");
scanf("%d",&no);root=make(no);
p=root;do
{
printf("Do you want to
continue(y/n)"); scanf("%s",&ch);
printf("\n enter another
number:"); scanf("%d",&no);
if(no==-1)
break; p=root;
q=root;
while(no!=p->data && q!=NULL)
{
p=q;
if(no<p->data)q=p-
>left;
else
q=p->right;
}
if(no<p->data)
{
printf("\n leftbranch of %d is%d",p->data,no);
left(p,no);
}
else
{
right(p,no);
printf("\n rightbranch of %d is %d",p->data,no);
}
}while(ch=='y'||ch=='Y');do
{
printf("\n 1.inorder traversal \n 2.preorder traversal \n3.postorder \n 4.exit");
printf("\n enter the choice");
scanf("%d",&choice);switch(choice)
{
case 1:inorder(root);
break;
case 2:preorder(root);
break;
case 3:postorder(root);
break;
case 4:exit(0);
default: printf("error!invalid
choice"); break;
}
getch();
}
while(choice<=3);

OUTPUT:
RESULT:
EX:11 Implementation of Graph Traversals - BFS and DFS
DATE:

AIM:
To write a program to implement DFS and BFS graph traversal.

ALGORITHM:

DFS
1. Define a Stack of size total number of vertices in the graph.
2. Select any vertex as starting point for traversal. Visit that vertex and push it on to the Stack.
3. Visit any one of the adjacent vertex of the vertex which is at top of the stack which is not visited
and push it on to the stack.
4. Repeat step 3 until there are no new vertex to be visit from the vertex on top of the stack.
5. When there is no new vertex to be visit then use back tracking and pop one vertex from the stack.
6. Repeat steps 3, 4 and 5 until stack becomes Empty.
7. When stack becomes Empty, then produce final spanning tree by removing unused edges from
the graph

BFS
1. Define a Queue of size total number of vertices in the graph.
2. Select any vertex as starting point for traversal. Visit that vertex and insert it into the Queue.
3. Visit all the adjacent vertices of the verex which is at front of the Queue which is not visited and
insert them into the Queue.
4. When there is no new vertex to be visit from the vertex at front of the Queue then delete that
vertex from the Queue.
5. Repeat step 3 and 4 until queue becomes empty.
6. When queue becomes Empty, then produce final spanning tree by removing unused edges from
the graph

PROGRAM:

#include<stdio.h>
int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();

void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}

do
{
for(i=1;i<=n;i++)
vis[i]=0; printf("\
nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S"); printf("\
nENTER YOUR CHOICE");
scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);

switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}

//*****BFS(breadth-first search) code*****//


void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++) if((a[p][i]!
=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}

void add(int item)


{
if(rear==19)
printf("QUEUE FULL");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else q[+
+rear]=item;
}
}
int delete()
{
int k; if((front>rear)||
(front==-1)) return(0);
else
{
k=q[front++];
return(k);
}
}

//******DFS(depth-first search) code*******//


void dfs(int s,int n)
{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++) if((a[k][i]!
=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack
overflow ");else
stack[++top]=item;
}
int pop()
{
int k;
if(top
==-1)
return
(0);
else
{
k=stack[top-
-];
return(k);
}
}

OUTPUT:

70
RESULT:

70

You might also like