Yash Ds
Yash Ds
210840131022
PRACTICAL 1
Aim: Program: for Call by Value & Call by Reference using pointers.
Tool: C
Background Theory:
Pointer: -A pointer is a variable which holds a memory address which is the location of some
other variable in memory. So,we can say that pointer is a special type of variable which store
the address of another variable as its value.
Syntax for pointer Declaration:
data-type *varname;
e.g:- int *ptr;
This Declaration says that ptr variable can store the address of any integer variable.
Call by Value
Whenever we call a function and pass an argument, an object or a variable to the function, then
by the default rule of C and C++, it is call by value.
It means that the original data remains at its place and a temporary copy of it is, sends and
passed to the function. Whatever the function does with this copy, the value in the calling
function remains intact. This is call by value.
PROGRAM:
#include<stdio.h>
void swap(int,int);
int main()
{
int a,b;
printf("\nEnter a Value of A=");
scanf("%d",&a);
printf("\nEnter a Value of B=");
scanf("%d",&b);
swap(a,b);
printf("\nOld Values:");
printf("A=%d B=%d \n",a,b);
}
void swap(int p,int q)
1
PEN NO. 210840131022
{
int tmp;
tmp=p;
p=q;
q=tmp;
printf("New Values After Swap:");
printf("A=%d B=%d",p,q);
}
OUTPUT:
Call by Reference
If we want a function to change something in the original object variable or whatever,
that variable or object by reference would be passed. To do this, we don't make temporary
copy of that object or variable. Rather, the address of the variable is sent. When the function
manipulates it, the original object will be manipulated, effecting change in its values. The use
of call by reference is also important for the sake of efficiency.
If we have a large object, sending of its copy will be something insufficient. It will occupy a
large space on the stack. Here, we can use call by reference instead of call by value only for
efficiency while we need not to change the original object. For this we use a keyword const
that means that a const (constant) reference is being passed. The function can use its values but
cannot change it.
PROGRAM:
#include<stdio.h>
void swap(int*,int*);
int main()
{
int a,b;
printf("\nEnter a Value of A=");
scanf("%d",&a);
printf("\nEnter a Value of B=");
2
PEN NO. 210840131022
scanf("%d",&b);
swap(&a,&b);
printf("\nOld Values:");
printf("A=%d B=%d \n",a,b);
}
void swap(int *p , int *q)
{
int tmp;
tmp=*p;
*p=*q;
*q=tmp;
printf("New Values After Swap:");
printf("A=%d B=%d",*p,*q);
}
OUTPUT:
3
PEN NO. 210840131022
PRACTICAL 2
Aim: Introduction to Dynamic Memory Allocation. DMA functions
malloc(), calloc(), free() etc.
Tool: C
Calloc: –Allocate multiple blocks of memory while malloc function reseves single block of
memory of specified size. Allocates space for an array of elements, initializes them to zero
and then returns a pointer to the memory.
Free: -Frees previously allocated space. Deallocate the memory referred to by the pointer so
it can be reused.
free(ptr)
Realloc: –Modifies the size of previously allocated space. If we want to change the size of
already allocated block, this function is used
Malloc: -
#include<stdio.h>
#include<stdlib.h>
4
PEN NO. 210840131022
int main(){
int *ptr;
int n,i,sum=0;
printf("Enter Number of Elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
printf("Enter Elements of Array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
OUTPUT: -
Calloc: -
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter Number of Elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
5
PEN NO. 210840131022
6
PEN NO. 210840131022
PRACTICAL 3
7
PEN NO. 210840131022
PROGRAM:
#include<stdio.h>
#define size 4
struct stack{
int a[size],top;
int temp[size], tos;
}s;
void push(int item){
s.a[++s.top] = item;
}
int pop(){
return s.a[s.top--];
}
void display(){
int i;
printf("\nThe stack contains: ");
for(i = s.top; i>=0; i--){
printf("\n\t%d", s.a[i]);
}
}
void peep(){
printf("\n\tTop : %d", s.top);
printf("\n\tValue: %d",s.a[s.top]);
}
void change(int row, int new_element){
int i;
int j = -1;
printf("\n\tTop: %d", s.top);
for(i=s.top; i>row; i--){
s.temp[++j] = s.a[s.top--];
}
s.a[s.top] = new_element;
for(i = j; i>-1; i--){
s.a[++s.top] = s.temp[j--];
}
}
int main(){
s.top = -1;
int item, choice, row, new_element;
printf("\n 1. Push\n 2. Pop\n 3. Display\n 4. Peep\n 5. Change\n 6. Exit\n");
char ans;
do{
printf("\n Enter your choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
if(s.top >= size-1){
8
PEN NO. 210840131022
printf("\nStack overflow\n");
break;
}
printf("Enter item to be pushed: ");
scanf("%d", &item);
push(item);
break;
case 2:
if(s.top == -1){
printf("Stack underflow\n");
break;
}
pop();
break;
case 3:
display();
break;
case 4:
peep();
break;
case 5:
printf("Enter row no : ");
scanf("%d",&row);
printf("\nEnter new element: ");
scanf("%d", &new_element);
change(row, new_element );
break;
case 6:
return 0;
}
}while(choice != 6);
return 0;
}
9
PEN NO. 210840131022
OUTPUT:
10
PEN NO. 210840131022
PRACTICAL 4
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define SIZE 100
char stack[SIZE];
int top = -1;
void push(char item)
{
if(top >= SIZE-1)
{
printf("\nStack Overflow.");
}
else
{
top = top+1;
stack[top] = item;
}
}
char pop()
{
11
PEN NO. 210840131022
char item ;
if(top <0)
{
printf("stack under flow: invalid infix expression");
getchar();
exit(1);
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}
int is_operator(char symbol)
{
if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')
{
return 1;
}
else
{
return 0;
}
}
int precedence(char symbol)
{
if(symbol == '^')
{
return(3);
}
else if(symbol == '*' || symbol == '/')
{
return(2);
}
else if(symbol == '+' || symbol == '-')
{
return(1);
}
else
{
return(0);
}
}
void InfixToPostfix(char infix_exp[], char postfix_exp[])
{
int i, j;
char item;
char x;
push('(');
12
PEN NO. 210840131022
strcat(infix_exp,")");
i=0;
j=0;
item=infix_exp[i];
while(item != '\0')
{
if(item == '(')
{
push(item);
}
else if( isdigit(item) || isalpha(item))
{
postfix_exp[j] = item;
j++;
}
else if(is_operator(item) == 1)
{
x=pop();
while(is_operator(x) == 1 && precedence(x)>= precedence(item))
{
postfix_exp[j] = x;
j++;
x = pop();
}
push(x);
push(item);
}
else if(item == ')')
{
x = pop();
while(x != '(')
{
postfix_exp[j] = x;
j++;
x = pop();
}
}
else
{
printf("\nInvalid infix Expression.\n");
getchar();
exit(1);
}
i++;
item = infix_exp[i];
}
if(top>0)
{
printf("\nInvalid infix Expression.\n");
getchar();
13
PEN NO. 210840131022
exit(1);
}
if(top>0)
{
printf("\nInvalid infix Expression.\n");
getchar();
exit(1);
}
postfix_exp[j] = '\0';
}
int main()
{
char infix[SIZE], postfix[SIZE];
printf("\nEnter Infix expression : ");
gets(infix);
InfixToPostfix(infix,postfix);
printf("Postfix Expression: ");
puts(postfix);
return 0;
}
OUTPUT:
14
PEN NO. 210840131022
PRACTICAL 5
Step-1 [Overflow?]
if R>=N
then Write (‘ OVERFLOW ‘)
return
Step-2 [Increment rear Pointer]
R = R+1
Step-3 [Insert Element]
Q[R] = Y
Step-4 [Is front pointer properly set?]
if F = 0
then F = 1
return
Step-1 [Underflow?]
if F = 0
then Write (‘ UNDERFLOW ‘)
return(0)
Step-2 [Delete Element]
Y = Q[F]
Step-3 [ Queue Empty?]
if F = R
then F = R = 0
else F = F + 1
Step-4 [Return Element]
return(Y)
15
PEN NO. 210840131022
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define n 4
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
16
PEN NO. 210840131022
break;
case 3:
printf("\n Queue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case 4:
exit(0);
default:
printf("Wrong Choice");
}
}
}
}
OUTPUT
17
PEN NO. 210840131022
PRACTICAL 6
Aim: Write a Program: to implement Circular Queue using array that
performs following Operations :
(a) INSERT(b) DELETE (C) DISPLAY
Background Theory:
Here, F=0 and R=0,
Q = vector array.
N = size of array .
18
PEN NO. 210840131022
else F = F + 1
return(y)
PROGRAM:
#include<stdlib.h>
#include<stdio.h>
#define max 4
int front=-1,rear=-1;
int CQueue[max];
void insert();
int delete();
void display();
int main()
{
int w,no;
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Display");
printf("\n4. EXIT");
for(;;)
{
printf("\nEnter the Choice :");
scanf("%d",&w);
switch(w)
{
case 1:
insert();
break;
case 2:
no=delete();
break;
case 3:
display();
break;
19
PEN NO. 210840131022
case 4:
exit(1);
default:
printf("\nWrong Choice\n");
}}}
void insert()
{
int no;
if((front ==0 && rear == max-1) || front == rear+1)
{printf("\nCircular Queue Is Full !\n");
return;
}
printf("\nEnter a number to Insert :");
scanf("%d",&no);
if(front==-1)
front=front+1;
if(rear==max-1)
rear=0;
else rear=rear+1;
CQueue[rear]=no;
}
int delete()
{
int e;
if(front==-1)
{
printf("\nThe Circular Queue is Empty !!\n");
}
e=CQueue[front];
if(front==max-1)
front=0;
else if(front==rear)
{
front=-1;
20
PEN NO. 210840131022
rear=-1;
}
else front=front+1;
printf("\n%d was deleted !\n",e);
return e;}
void display()
{int i;
if(front==-1)
{
printf("\nThe Circular Queue is Empty ! Nothing To Display !!\n");
return;
}
i=front;
if(front<=rear)
{printf("\n\n");
while(i<=rear)
printf("%d ",CQueue[i++]);
printf("\n");
}
else
{
printf("\n\n");
while(i<=max-1)
printf("%d ",CQueue[i++]) ;
i=0;
while(i<=rear)
printf("%d ",CQueue[i++]);
printf("\n");
}}
21
PEN NO. 210840131022
OUTPUT:
22
PEN NO. 210840131022
PRACTICAL 7
Aim: Write a Program: to implement following operations on the singly
linked list.
Tool : C
Background Theory:
Here, X= New Element.
AVAIL = Available memory pointer.
NEW = Temporary pointer variable.
INFO = Actual Element of list.
LINK = Address of next-node in the list.
FIRST = Pointer of First Element.
C=Current node pointer variable
SAVE=Temporary pointer variable for Insert Operation.
TEMP,TEMP2=Temporary pointer variable for Delete Operation.
23
PEN NO. 210840131022
24
PEN NO. 210840131022
TEMP<− FIRST
3. [Assign address to next node]
FIRST<− LINK ( TEMP )
4. [free the first Node]
free(TEMP)
5. [Finished]
Return
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *link;
}node;
node *create(node *st)
{
int n;
node *nav,*tmp;
printf("\nenter -1 at end");
25
PEN NO. 210840131022
printf("\nenter number:");
scanf("%d",&n);
while(n!=-1)
{
nav = (struct node*)malloc(sizeof(struct node));
nav->info=n;
if(st==NULL)
{
nav->link=NULL;
st=nav;
}
else
{
tmp=st;
while(tmp->link!=NULL)
tmp=tmp->link;
tmp->link=nav;
nav->link=NULL;
}
printf("\nenter number:");
scanf("%d",&n);
}
return st;
}
node* insert_at_f(int x,node* first1)
{
node *n;
n=(struct node*)malloc(sizeof (struct node));
n->info=x;
n->link=first1;
first1=n;
return first1;
}
node* insert_at_r(int x,node *f)
26
PEN NO. 210840131022
{
node *n,*save;
n=(node *)malloc(sizeof(struct node));
n->info=x;
n->link=NULL;
save=f;
if(f==NULL)
{
f=n;
}
else
{
while(save->link!=NULL)
{
save=save->link;
}
save->link=n;
}
return f;
}
node* display(node *first)
{
node *temp;
temp=first;
while(temp!=NULL)
{
printf("%d,",temp->info);
temp=temp->link;
}
return first;
}
node* delet_at_f(node *first)
{
node *save;
27
PEN NO. 210840131022
if(first==NULL)
printf("\nno element.");
else
{
save=first;
printf("deleted element: %d",save->info);
first=save->link;
free(save);
}
return first;
}
node* delet_at_r(node *first)
{
node *temp,*s;
temp=first;
if(temp==NULL)
{
printf("\nno element.");
}
else
{
while(temp->link!=NULL)
{
temp=temp->link;
}
s=first;
while(s->link!=temp)
{
s=s->link;
}
s->link=NULL;
printf("\ndeleted element: %d",temp->info);
free(temp);
}
28
PEN NO. 210840131022
return first;
}
node* insert_at_ith(int x ,node* first)
{
node *n,*save,*temp;
int i,a=1;
n=(struct node*)malloc(sizeof(struct node));
n->info=x;
printf("\nenter the before ith location of enter element : ");
scanf("%d",&i);
temp=first;
while(a!=(i+1))
{
temp=temp->link;
a++;
}
n->link=temp;
a=1;
save=first;
while(a!=(i))
{
save=save->link;
a++;
}
save->link=n;
return first;
}
node* delet_at_ith(node *first)
{
node *save,*temp,*last;
int a=0,b=0,c=0,i;
if(first==NULL)
printf("\nno elements.");
else
29
PEN NO. 210840131022
{
printf("\nenter the ith location for deleted location: ");
scanf("%d",&i);
last=first;
while(a!=i)
{
last=last->link;
a++;
}
temp=first;
while(b!=(i-1))
{
temp=temp->link;
b++;
}
save=first;
while(c!=(i-2))
{
save=save->link;
c++;
}
printf("\ndeleted element: %d",temp->info);
free(temp);
}
save->link=last;
return first;
}
int main()
{
node *first;
int n,i,x,choice;
first=NULL;
printf("\n1.create node");
printf("\n2.insert at front\n3.insert at last\n4.delete at front\n5.delete at rear\n6.insert
30
PEN NO. 210840131022
break;
case 8:
first=display(first);
break;
case 9:
exit(0);
break;
}
}
while(choice!=9);
return 0;
}
OUTPUT:
32
PEN NO. 210840131022
PRACTICAL 8
Aim: Write a Program: to implement following operation on the Doubly
linked list.
a) Insert a node at the front
b) Insert a node at the end
c) Delete a last node
d) Delete a node before specified position
Tool: C
Background Theory:
Here, X=New element.
NODE = Pointer of the TOP element of available memory.
NEW = Temporary pointer variable.
INFO = Actual Element of list.
RPTR = Address of next-node in the list.
LPTR = Address of previous-node in the list.
L=Pointer of left-most node.
R=Pointer of Right-most node.
OLD, OLD2 = Temporary pointer variable for Delete Operation .
SAVE= Temporary pointer variable for Insert Operation.
N= Node location.
33
PEN NO. 210840131022
INFO(NEW) <− X
3.[Assign a valaue NULL to next part of node]
LPTR(NEW) <− NULL
4.[Assign address to new node]
IF L = NULL
then RPTR(NEW) <− NULL
R <− NEW
else RPTR(NEW) <− L
LPTR(L) <− NEW
5.[Initialize New node]
L <− NEW
6.[finished]
Return
R <− OLD
5.[Delete last node]
free(OLD2)
6.[Finished]
Return
Algorithm for Delete node before specified position
1.[Empty list or Underflow?]
IF R = NULL
then Write (“LIST IS EMPTY”):
Return
2.[Read Location]
Read N
3.[Initialization for delete N node]
OLD <− L
4.[if node equal to first]
IF N = 1
then write(“Give correct position of N”);
Return
5.[if node equal to second]
IF N=2
then L <− RPTR(OLD)
LPTR(L) <− NULL
free(OLD)
Return
6.[if the deleted node is not 1 than traverse the list till specific location is reached]
a) initialize i=1
b) Repeat while i ≠ N-2
OLD <− RPTR(OLD)
IF OLD = NULL
than write(‘Node is not in the list’);
Return
i++
7.[set the link field]
OLD2 <− RPTR(OLD)
RPTR(OLD) <− RPTR(OLD2)
LPTR(RPTR(OLD2)) <− OLD
8.[Delete node]
free(OLD2)
9.[finished]
Return
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct node
35
PEN NO. 210840131022
{
struct node *next;
int data;
struct node *prev;
};
int n;
struct node *st=NULL;
struct node *tmp,*nav,*tmp1;
struct node *create(struct node *st)
{
printf("\nenter -1 to end");
printf("\nenter number:");
scanf("%d",&n);
while(n!=-1)
{
if(st==NULL)
{
nav=(struct node*)malloc(sizeof(struct node));
nav->prev=NULL;
nav->data=n;
nav->next=NULL;
st=nav;
}
else
{
tmp=st;
nav=(struct node*)malloc(sizeof(struct node));
nav->data=n;
while(tmp->next!=NULL)
tmp=tmp->next;
tmp->next = nav;
nav->prev = tmp;
nav->next = NULL;
}
36
PEN NO. 210840131022
printf("\nenter data:");
scanf("%d",&n);
}
return st;
}
struct node *inst_front(struct node *st)
{
printf("\nenter number:");
scanf("%d",&n);
nav=(struct node*)malloc(sizeof(struct node));
nav->data=n;
st->prev=nav;
nav->next=st;
nav->prev=NULL;
st=nav;
return st;
}
struct node *inst_last(struct node *st)
{
printf("\nenter number:");
scanf("%d",&n);
nav=(struct node*)malloc(sizeof(struct node));
nav->data=n;
tmp=st;
while(tmp->next!=NULL)
tmp=tmp->next;
tmp->next=nav;
nav->prev=tmp;
nav->next=NULL;
return st;
}
struct node *del_last(struct node *st)
{ struct node *save=NULL;
tmp=st;
37
PEN NO. 210840131022
while(tmp->next!=NULL)
{ save=tmp;
tmp=tmp->next;
}
save->next=NULL;
free(tmp);
return st;
}
struct node *del_before(struct node *st)
{
int val;
printf("\nenter value before which node has to delete:");
scanf("%d",&val);
tmp=st;
while(tmp->data!=val)
tmp=tmp->next;
tmp1=tmp->prev;
if(tmp1==st)
{
tmp=st;
st=st->next;
st->prev=NULL;
}
else
{
tmp->prev=tmp1->prev;
tmp1->prev->next=tmp;
}
free(tmp1);
return st;
}
struct node *display(struct node *st)
{
tmp=st;
38
PEN NO. 210840131022
while(tmp!=NULL)
{
printf("%d-->",tmp->data);
tmp=tmp->next;
}
return st;
}
int main()
{
int ch;
printf("\n 1.create list\n 2.insert at front\n 3.insert at last\n 4.delete at last\n 5.delete
before node\n 6.display\n 7.exit");
do
{
printf("\nenter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
st=create(st);
printf("\ndoubly linked list create");
}
break;
case 2:
st=inst_front(st);
break;
case 3:
st=inst_last(st);
break;
case 4:
st=del_last(st);
break;
case 5:
39
PEN NO. 210840131022
st=del_before(st);
break;
case 6:
st=display(st);
break;
case 7:
exit(0);
}
}
while(ch!=8);
return 0;
}
OUTPUT:
40
PEN NO. 210840131022
PRACTICAL 9
Aim: Write a Program: to implement following operation on the circular
link list.
a) Create Node of the Circular Linked List.
b) Insert the node at the End of linked list.
c) Insert the node before specific position.
d) Delete First node of linked list.
e) Delete node after specific position.
f) Display.
41
PEN NO. 210840131022
1.[UNDERFLOW?]
if AVAIL = NULL
then write (‘underflow occur’)
Return
2.[Obtain address of next free node]
NEW <− AVAIL
3.[Remove free node from the availability of stack]
AVAIL <− LINK ( AVAIL )
4. [Initialize field of new node and its link to the list]
INFO ( NEW ) <− X
LINK ( NEW ) <− FIRST
5.[Is the list is empty?]
if FIRST=NULL
then LINK(FIRST) <−NEW
LAST<−NEW
FIRST<−NEW
else LINK(LAST) <−NEW
LINK(NEW) <−FIRST
LAST<−NEW
6.[Finished]
Return
42
PEN NO. 210840131022
43
PEN NO. 210840131022
44
PEN NO. 210840131022
n->link=NULL;
head=n;
last=n;
}
else
{
n->link=head;
head=n;
last->link=head;
}}
void insert_end(int x)
{
node *n;
n=(struct node*)malloc(sizeof(struct node));
n->info=x;
if(head==NULL)
{
n->link=NULL;
head=n;
last=n;
}
else
{
last->link=n;
n->link=head;
last=n;
}}
void insert_mid(int x,int y)
{
node *n,*temp=head,*temp1=NULL;
n=(struct node*)malloc(sizeof(struct node));
n->info=x;
if(head==NULL)
printf("no element.\n");
45
PEN NO. 210840131022
else
{
while(temp->info!=y && temp->link!=head)
{
temp1=temp;
temp=temp->link;
}
temp1->link=n;
n->link=temp;
}}
void delet_first()
{
node *temp=head;
if(head==NULL)
printf("no element.\n");
else
{
printf("deleted elment: %d\n",temp->info);
head=temp->link;
free(temp);
last->link=head;
}}
void delet_end()
{
node *temp,*temp1=last;
if(head==NULL)
printf("no element.\n");
else
{
temp=head;
while(temp->link!=last)
temp=temp->link;
last=temp;
temp->link=head;
46
PEN NO. 210840131022
temp=temp->link;
}
printf("%d\n",temp->info);
}
}
int main()
{
int ch,a,b,c,d,e;
printf(" 1.Insert at first\n 2.Insert at last\n 3.Insert at before of specific element\n
4.Delete at first\n 5.Delete at last\n 6.Delete at specific element\n 7.Display\n
8.Exit\n");
do
{
printf(" Enter The Choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter the element: ");
scanf("%d",&a);
insert_first(a);
break;
case 2:printf("enter the element: ");
scanf("%d",&b);
insert_end(b);
break;
case 3:printf("Enter The Element : ");
scanf("%d",&c);
printf("Enter The Specific Element : ");
scanf("%d",&d);
insert_mid(c,d);
break;
case 4:delet_first();
break;
case 5:delet_end();
48
PEN NO. 210840131022
break;
case 6:
printf("Enter The Specified Element: ");
scanf("%d",&e);
delet_mid(e);
break;
case 7:display();
break;
case 8:exit(0);
break;
}
}while(ch!=8);
return 0;
}
OUTPUT:
49
PEN NO. 210840131022
PRACTICAL 10
Aim: Write a Program: which create binary search tree.
Tool: C
Binary Search Tree is a node-based binary tree data structure which has the following
properties:
1. The left subtree of a node contains only nodes with keys lesser than the node’s key.
2. The right subtree of a node contains only nodes with keys greater than the node’s key.
3. The left and right subtree each must also be a binary search tree.
Algorithm:
i) If root == NULL,
return the new node to the calling function.
ii) if root=>data < key
call the insert function with root=>right and assign the return value in root=>right.
root->right = insert(root=>right,key)
iii) if root=>data > key
call the insert function with root->left and assign the return value in root=>left.
root=>left = insert(root=>left,key)
PROGRAM:
#include<stdio.h>
typedef struct node
{
int num; struct
node *left; struct
node *right;
}node; struct node
*r=NULL;
struct node *insert(node *r,int v)
{
if(r==NULL)
{
50
PEN NO. 210840131022
51
PEN NO. 210840131022
OUTPUT:
52
PEN NO. 210840131022
PRACTICAL 11
AIM: Implement recursive and non-recursive tree traversing methods in
order, pre order and post-order traversal.
Tool: C
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one
logical way to traverse them, trees can be traversed in different ways. The following are the
generally used methods for traversing trees:
Inorder Traversal:
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left->subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right->subtree)
Preorder Traversal:
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left->subtree)
3. Traverse the right subtree, i.e., call Preorder(right->subtree)
Postorder Traversal (Practice):
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left->subtree)
2. Traverse the right subtree, i.e., call Postorder(right->subtree)
3. Visit the root
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node {
int element;
struct node* left;
struct node* right;
};
struct node* createNode(int val)
53
PEN NO. 210840131022
{
struct node* Node = (struct node*)malloc(sizeof(struct node));
Node->element = val;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
void traversePreorder(struct node* root)
{
if (root == NULL)
return;
printf(" %d ", root->element);
traversePreorder(root->left);
traversePreorder(root->right);
}
void traverseInorder(struct node* root)
{
if (root == NULL)
return;
traverseInorder(root->left);
printf(" %d ", root->element);
traverseInorder(root->right);
}
void traversePostorder(struct node* root)
{
if (root == NULL)
return;
traversePostorder(root->left);
traversePostorder(root->right);
54
PEN NO. 210840131022
55
PEN NO. 210840131022
PRACTICAL 12
AIM: Implement following types of sort:
(a)Quick Sort (b) Merge Sort (c) Bubble Sort
Tool:- C
Quick Sort:- Quick Sort is a Divide and Conquer algorithm. It picks an element as a pivot and
partitions the given array around the picked pivot. There are many different versions of
quickSort that pick pivot in different ways.
● Always pick the first element as a pivot.
● Always pick the last element as a pivot (implemented below)
● Pick a random element as a pivot.
● Pick median as the pivot.
quickSort(arr, low, pi – 1)
quickSort(arr, pi + 1, high)
end
partition (arr[], low, high):
pivot = arr[high]
i = (low – 1)
Merge Sort:- Merge Sort algorithm is a sorting algorithm that is based on the Divide and
Conquer paradigm. In this algorithm, the array is initially divided into two equal halves and
then they are combined in a sorted manner.
56
PEN NO. 210840131022
Bubble Sort :- Bubble sort algorithm is straight forward. It is easy to understand & simple
sorting technique. But this sorting technique is not efficient in comparison to other sorting
technique.
57
PEN NO. 210840131022
return (i + 1);
}
void quick(int a[], int start, int end)
{
if (start < end)
{
int p = partition(a, start, end);
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}
void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 24, 9, 29, 14, 19, 27 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
quick(a, 0, n - 1);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
OUTPUT:
58
PEN NO. 210840131022
59
PEN NO. 210840131022
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
60
PEN NO. 210840131022
printf("\n");
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}
OUTPUT:
61
PEN NO. 210840131022
OUTPUT:
62
PEN NO. 210840131022
PRACTICAL 13
AIM: Write a Program: to implement Binary search.
Tool:- C
Background Theory:
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the
search interval in half. The idea of binary search is to use the information that the array is
sorted and reduce the time complexity to O(Log n).
Algorithm:
binarySearch(arr, x, low, high)
repeat till low = high
mid = (low + high)/2
if (x == arr[mid])
return mid
PROGRAM:
#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
if(a[mid] == val)
{
return mid+1;
}
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
int main() {
63
PEN NO. 210840131022
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70};
int val = 40;
int n = sizeof(a) / sizeof(a[0]);
int res = binarySearch(a, 0, n-1, val);
printf("The elements of the array are - ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}
OUTPUT:
64