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

CPDS LAB (1) - Merged

Uploaded by

hod.eee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

CPDS LAB (1) - Merged

Uploaded by

hod.eee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

CS3362/ C PROGRAMMING & DATA

STRUCTURES
LAB MANNUAL
EX_NO: 1a

DATE: Swap Numbers Using Temporary Variable

AIM:
To write an algorithm and program to Swap Numbers Using Temporary Variable.

Algorithm:
Step1: Start.
Step2: Take two inputs in variable num1and num2.
Step3: Assign value of num1to temp.
Step4: Then,assignthe value ofnum2tonum1.
Step5: Finally,assign the value of temp to num2. Note that temp variable stores the initial
value of the num1 variable.
Step 5: End.

Program:

#include<stdio.h>
main()
{
double first, second, temp;
printf("Enter first number: ");
scanf("%lf", &first);
printf("Enter second number: ");
scanf("%lf", &second);

temp = first;

first = second;

second=temp;

printf("\nAfter swapping,first number=%.2lf\n",first);

printf("After swapping, second number = %.2lf",second);


return 0;
}
Output:

Enter first number: 1.20


Enter second number:2.45

After swapping, first number = 2.45


After swapping,second number=1.20
EX_NO: 1b
Algorithm to find the factorial of a number
DATE:

AIM:
To write an algorithm and program to find the factorial of a number.

Algorithm:
Step1: Start.
Step2: Take an integer number as input in variable num and initialize i=1.
Step3: Check if the num is less than 0.If yes,
Display“Factorial of a negative number doesnot exist.” And go to step 6
Step4: Repeat until I is lessthan or equals to num, fact= fact* i i=i+1
Step5: Display factorial of the given number.
Step 6:End

Program:
#include<stdio.h>
main()
{
int num,
fact, i=1;
printf("Enter an integer: ");
scanf("%d",&num);
if (num< 0)
printf("Factorial of negative number doesn't exist.");
else
{
while(i<=num)
{
fact = fact
* i; i++;
}
printf("Factorialof%d=%lu",num, fact);
}
return 0;
}
Output

Enter an integer: 6 Factorial of 6=720

Enter an integer: 0 Factorial of 0=1

Enter an integer: 1 Factorial of 1=1


EX-NO: 1c
Program to find reverse a number using basic method
DATE:

Aim:

To write an algorithm and program to reverse a number using basic method or without using
loops

Algorithm:
Step1: Start.
Step2: Take a number as input in num.
Step3: Make a copy of num for future reference.
Step 4: digit_1= num% 10;
Step 5: num = num / 10;
Step 6: digit_2 = num % 10;
Step 7: num = num / 10;
Step 8: digit_3 = num % 10;
Step 9: num= num/10;
Step 10: digit_4 = num%10;
Step11: rev=digit_1*1000+digit_2*100+digit_3*10+digit_4;
Step 12: Display original number and reversed number.
Step 13: End.

Program:

#include<stdio.h>
Void main()
{
int num,digit_1,digit_2,digit_3,digit_4,rev,copy;
printf("Enter a4digited number:");
scanf("%d",&num);
copy=num;
numberdigit_1= num% 10;
num = num / 10;
digit_2=num%10;
num = num / 10;
digit_3=num%10;
num = num / 10;
digit_4=num%10;
rev =digit_1*1000 +digit_2 *100 +digit_3 *10+digit_4;
printf("\nOriginalnumber=%d", copy);
printf("\nReversenumber=%d",rev);
}

Output:

Enter a 4 digited

number: 4321 Original

number = 4321

Reverse number =1234


EX-NO: 1d

DATE: Program to find the average of N numbers using for loop

AIM:
To write an algorithm and program to find the average of N numbers using for loop.

Algorithm:
Step1: Start.
Step2: Take the number of elements as input in n.
Step3: Initializei=0.
Step4: Repeat step 4 to step 7 until i< n.
Step5: Take elements as input in num
Step 6:Calculate,sum= sum+ num
Step7: i= i+ 1
Step8: avg=sum/n
Step9: End.

Program:
#include<stdio.h>
main()
{
intn,i;
float sum = 0, avg, num;
printf("Enter number of elements: ");
scanf("%d",&n);
printf("\nEnter %d elements\n", n);
for(i=0; i< n;i++)
{
scanf("%f", &num);
sum= sum+ num;
}
avg =sum/n;
printf("\nAverageofnumbersis%f",avg);
return 0;
}
Output:
Enter number of elements : 5

Enter 5 elements
10
12
15
5
8

Average of numbers is10.000000


EX-NO: 2a
C program to check even or odd using functions
DATE:

Aim:

To write C program to check even or odd using functions


Algorithm:
Step1: Start the program.
Step2: Read/ input the number.
Step3: if n%2==0 then number is even.
Step4: else number is odd.
Step5: displays the output.
Step6:Stop the program

PROGRAM:

#include<stdio.h>
int is Even(int num)
{
return !(num& 1);
}
Int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
if(isEven(num))
{
printf("The number is even.");
}
else
{
printf("The number is odd.");
}
return 0;
}
Output
Enter any number: 22

The number is Even


EX-NO: 2b

DATE: Sum of Natural Numbers Using Recursion

Aim:
Write a C program to Sum of Natural Numbers Using Recursion

Algorithm:
• Start
• Declare and initialize variable, i, num, sum=0.
• Enter the value of num i.e. number upto which sum is to be calculated
• Use Loop to add number. Any of while, do-while or forloop can be used.
• Print the sum
• Stop

PROGRAM:

#include<stdio.h>
int add Numbers(int n);
int main()
{

int num;
printf("Enter a positive integer: ");
scanf("%d",&num);
printf("Sum=%d",addNumbers(num));
return 0;
}

Int add Numbers(int n)


{
if (n != 0)
return n + addNumbers(n - 1);
else
return n;
}
Output
Enter a positive integer: 20
Sum= 210
EX-NO:2c

DATE: Factorial of a Number Using Recursion

Aim:
To write a C program for Factorial of a Number Using Recursion

Algorithm:
Step1: Start
Step2: Read number n
Step3: Callfactorial(n)
Step4: Print factorial f
Step5: Stop

factorial(n)
Step1: If n==1 then return1
Step2: Elsef=n*factorial(n-1)
Step3: Return f

PROGRAM:

//Factorial of a Number Using Recursion

#include<stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorialof%d=%ld",n,multiplyNumbers(n));
return 0;
}

long int multiplyNumbers(int n)


{
if (n>=1)
return n*multiplyNumbers(n-1);
else

return 1;
}
Output
Enter a positive integer: 6
Factorial of 6 =720
EX-NO: 2d

DATE: C Programming for Matrix Multiplication

Aim:
To write a C program for Matrix Multiplication

Algorithm:

• Start.
• Enter the value of m and n(or)order of the firstmatrix.
• Enter the value of p and q(or)order of the second matrix.
• Create a matrix of size a[m][n] and b[p][q].
• Enter the element of matrices row-wise using loops.
• If the number of columns of the first matrix is not equal to the number of rows of the
second matrix, print matrix multiplication is not possible and exit. If not, proceed to
the next step.
• Create a third matrix, c of size m x q, to store the product.
• Set a loop from i=0 to i=m.
• Set an inner loop for the above loop from j=0 to j=q.
• Initialise the value of the element(i,j) of then ew matrix to 0.
• Set an inner loop inside the above loop from k=0 to k=p.
• Using the add and assign operator(+=) store the value of a[i][k]*b[k][j] in the third
matrix, c[i][j].
• Print the third matrix.
• Stop.

PROGRAM:
#include<stdio.h>
int main()
{
int a[10][10],
b[10][10],
c[10][10],n, i, j,k;
printf("EnterthevalueofN(N<=10):");
scanf("%d",&n);
printf("EntertheelementsofMatrix-A:\n");
for (i = 0; i< n;
i++)
{
for(j=0;j<n;j++)
{
scanf("%d",& a[i][j]);
}
}
printf("EntertheelementsofMatrix-B:\n");
for(i =0; i< n;i++)
{
for (j = 0; j < n; j++)
{
scanf("%d",&b[i][j]);
}
}
for (i = 0; i< n;
i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
for (k = 0; k < n; k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("Theproductofthetwomatricesis:\n");
for(i =0; i< n;i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
return 0;
}
output
Enter the value of N (N <= 10): 2
Enter the elements of Matrix - A:2 2
22
Enter the elements of Matrix-B:2 2
22

Product of the two matrices is :8 8


8 8
EX-NO:3

DATE: C Programming for Working of Pointers

Aim:
To write a C program for Working of Pointers

Algorithm:
1.int* pc,
c;2.c=22;
• printf("Addressofc: %p\n",&c);
• printf("Valueofc:%d\n\n",c);//22
• pc=&c;
• printf("Addressofpointerpc:%p\n",pc);
• printf("Contentofpointer pc:%d\n\n",*pc);//22
• return 0;

WorkingofPointers

#include <stdio.h>
intmain()
{
int*pc,
c;c=22;
printf("Address of c: %p\n", &c);
printf("Valueofc:%d\n\n",c);
//22pc=&c;
printf("Address of pointer pc: %p\n", pc);
printf("Contentofpointer pc:%d\n\n",*pc);
//22c =11;
printf("Address of pointer pc: %p\n", pc);
printf("Contentofpointerpc:%d\n\n",*pc);
//11
*pc=2;
printf("Address of c: %p\n",&c);
printf("Valueofc:%d\n\n",c);
//2return 0;
}
Output
Address of c: 2686784
Value of c:22

Address of pointer pc: 2686784


Content of pointer pc:22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c:2
EX-NO: 3a
Dynamic memory allocation of structs
DATE:

Aim:
To write a C program for Dynamic memory allocation of structs

Algorithm:
Struct person*ptr;
printf("Enter the number of persons:");
scanf("%d",&n);
ptr=(struct person*)malloc(n*sizeof(struct person));
for(i=0; i< n;++i)
printf("Enter first name and age respectively:");
scanf("%s%d",(ptr+i)->name,&(ptr+i)->age);
printf("Displaying Information:\n");
for(i=0; i< n;++i)
printf("Name:%s\tAge:%d\n",(ptr+i)->name,(ptr+i)->age);

Dynamic memory allocation of structs


#include <stdio.h>
#include <stdlib.h>
struct person
{
Int age;
float weight;
charname[30];
};
intmain()
{
structperson*ptr;
int i, n;
printf("Enter the number of persons: ");
scanf("%d",&n);
ptr=(struct person*)malloc(n*sizeof(structperson));
for(i=0; i< n;++i)
{
printf("Enterfirstnameandagerespectively:");
scanf("%s%d",(ptr+i)->name,&(ptr+i)->age);
}
printf("DisplayingInformation:\n");
for(i=0; i< n;++i)
printf("Name:%s\tAge:%d\n",(ptr+i)->name,(ptr+i)->age);
return 0;
}
OUTPUT

When you run the program, the output will be:


Enter the number of persons:2
Enter first name and age respectively: Harry24
Enter first name and age respectively:Gary
32Displaying Information:
Name: HarryAge 24
Name:Gary
Age:32
EX-NO: 3b

DATE: Store Information in Structure and Displayit

Aim:
To write a C program for Store Information in Structure and Displayit

Algorithm:

struct student
{
charfirstName[50];
introll;
floatmarks;
}
s[5];
for(i =0;i< 5;++i)
• s[i].roll = i+ 1;
• printf("\nForrollnumber%d,\n",s[i].roll);
• printf("Enterfirstname:");
• scanf("%s",s[i].firstName);
• printf("Entermarks:");
• scanf("%f",&s[i].marks);
• printf("DisplayingInformation:\n\n");
• printf("\nRollnumber:%d\n",i +1);
• printf("Firstname:");
• puts(s[i].firstName);
• printf("Marks:%.1f",s[i].marks);

Store Information in Structure and Displayit

#include <stdio.h>
struct student
{
Char first Name[50];
Int roll;
Float marks;
}
s[5];
int main()
{
Int i;
printf("Enter information of students:\n");
for(i =0; i< 5;++i)
{
s[i].roll = i+ 1;
printf("\nFor roll number%d,\n",s[i].roll);
printf("Enter first name:");
scanf("%s",s[i].first Name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
}
printf("Displaying Information:\n\n");
for(i =0; i< 5;++i)
{
printf("\nRoll number:%d\n",i+1);
printf("First name:");
puts(s[i].first Name);
printf("Marks:%.1f",s[i].marks);
printf("\n");
}
return 0;
}
Output
Enter information of students:
For roll number 1,
Enter name: Tom
Enter marks: 98
For roll number2,
Enter name: Jerry
Enter marks: 89
Displaying Information:
Roll number: 1
Name: Tom
Marks:98
.
EX-NO:4
Read name and marks of n number of student sand store
DATE: the main file

Aim:
To write a C program for read name and marks of n number of student sand store
themina file

Algorithm:

Char name[50];
Int marks,i, num;
printf("Enter number of students:");
scanf("%d",&num);
FILE *f ptr;
fptr=(f open("C:\\student.txt","w"));
if(fptr==NULL)
printf("Error!");
exit(1);
for(i=0; i< num;++i)
printf("For student%d\nEnter name:",i+1);
scanf("%s",name);
printf("Enter marks:");
scanf("%d",&marks);
fprintf(fptr,"\nName:%s\nMarks=%d\n",name,marks);
fclose(fptr);

Program:

#include <stdio.h>
Int main()
{
char name[50];
int marks,
i,num;
printf("Enter number of students: ");
scanf("%d",&num);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i=0; i< num;++i)
{
printf("For student%d\nEnter name:",i+1);
scanf("%s",name);
printf("Enter marks:");
scanf("%d",&marks);
fprintf(fptr,"\nName:%s\nMarks=%d\n",name,marks);
}
fclose(fptr);
return 0;
}
Output

Enter number of students:2

Enter name: AAA


Enter marks: 60
Enter marks:70
Enter marks:80

Enter name: BBB


Enter marks: 45
Enter marks:15
Enter marks:10
EX-NO:5

Simple Calculator using switch Statement


DATE:

Aim:

To write a C program for Simple Calculator using switch Statement

Procedure:
Step1-Displaymessageslike“press1foraddition,2forsubtraction,3formultiplication,4for division”
Step2-accept the choice from theuser and store it in a variable (saychoice)
Step3-put choice int heswit chass witch(choice)
Step4-put the case accordingly like case1foraddition,case2for subtraction and soon and store and
print the result.Also give a default case for wrong choice

Program:
#include <stdio.h>
Int main()
{
char op;
double first,second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf%lf",&first,&second);
switch (op)
{
case'+':
printf("%.1lf+%.1lf=%.1lf",first,second,first+second);
break;
case'-':
printf("%.1lf-%.1lf =%.1lf", first,second,first-second);
break;
case'*':
printf("%.1lf*%.1lf =%.1lf", first,second,first*second);
break;
case'/':
printf("%.1lf/%.1lf=%.1lf",first,second,first/second);
break;
default:
printf("Error!operator is not correct");
}

return 0;
}
Output
Enter an operator (+, -, *,):
*Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8
EX-NO: 6

DATE: Array implementation of Stack and Queue ADTs

Aim:
Write a program to Array implementation of Stackand Queue ADTs

Algoritham

Step1:push()to insert an element into the stack


Step2:op() to remove an element from the stack
Step3:top()Returns the top element of the stack.
Step4: isEmpty() returns true if stack is empty else false.
Step5:size()returns the size of stack.

Program:
//C program for array implementation of stack
#include<limits.h>
#include <stdio.h>
#include<stdlib.h>
StructStack
{
Int top;
unsigned capacity;
int*array;
};
structStack*createStack(unsignedcapacity)
{
struct Stack* stack = (structStack*)malloc(sizeof(structStack));
stack->capacity=capacity;
stack->top=-1;
stack->array = (int*)malloc(stack->capacity *sizeof(int));
return
stack;
}
intisFull(structStack*stack)
{
returnstack->top==stack->capacity-1;
}
Int is Empty(structStack*stack)
{
return
stack->top==-1;
}
Void push(struct Stack*stack,int item)
{
if (isFull(stack))return;
stack->array[++stack->top] = item;
printf("%dpushed to stack\n",item);
}
Top by1
int pop(struct Stack*stack)
{
if (isEmpty(stack))return INT_MIN;
return stack->array[stack->top--];
}
Int peek(struct Stack*stack)
{
if (isEmpty(stack))
return
INT_MIN;
Return stack->array[stack->top];
}

//Driver program to test above functions int main()


Output

structStack*stack=createStack(100);

push(stack,10);
push(stack,20);

10 pushed into stack20


pushed into stack30
pushed into stack30
Popped from stack
Top element is:20
Elements present in stack:2010
EX-NO: 7
Implementation of the queue using linked list
DATE:

Aim:
Write a program to Implementation of the queue using linked list
Algoritham:

Step 1 We will maintain two node pointer "front" and "back", which always points to the head
and tailnode of linked list respectively .This will ensure that we will add node at rear of linked
list and remove node from front of linked list.
Step2We will start with an empty linkedlist,where both front and backpointer is set toNULL.
Step 3 Enqueue Operation : We will dynamically allocate memory for a struct node
variable(let'ssay temp). Then we will attach new node at the end of linked list by setting back-
>next = temp.Finally setback pointer to temp.(back=temp;)
Step 4 Dequeue Operation : Remove head node(pointed by front pointer) of the linked list.
Storethe front pointer in a temp variable. Now, move front pointer to next node(front = front-
>next;).Deallocatememoryoftempnodeusing free.
Step5getFront Element Operation Returns the value of head node of linked list without
removing it.(returnfront->data;)
Step6isEmpty Check: If both front and back pointers are NULL,then Queue is empty other
wise non-empty.

Program:

*Program:Queue using linked list Language:C*/


#include<stdio.h>
#include<stdlib.h>
structnode
{
Int data;
struct node*next;
};
Struct node*front=NULL,*rear=NULL;
Void enqueue(intval)
{
Struct node*new Node=malloc(sizeof(struct node));new Node->data=val;

New Node->next=NULL;
if(front==NULL&&rear==NULL)front=rear=newNode;
else
{
rear->next=newNode;
rear=newNode;
}
}
Void dequeue()
{
struct node *temp;
if(front==NULL)
printf("Queue is Empty.Unable to performd equeue\n");
else
{
temp=front;

front = front-
>next;if(front=
=NULL)
rear=NULL;

//free the first node free(temp);


}
}
Void print List()
{
Struct node*temp=front;
while(temp)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("NULL\n");
}
Int main()
{
enqueue(10);
enqueue(20);
enqueue(30);
printf("Queue :");
print List();
dequeue();
printf("After dequeue the new Queue:");
printList();
dequeue();
printf("After dequeue the new Queue:");
printList();
return0;
}
Output
Queue:10->20->30->NULL
After dequeue the new Queue:20->30->NULL
After dequeue the new Queue:30->NULL
EX-NO: 8

Let's print each node data in a linked list


DATE:

Aim:
Write a program to Implementation to print each node's data;
Traverse the linked list till the end.

Algoritham:
Step1.Create at emporary node(temp)and assign the head node's address.
Step2.Print the data which present in the temp node.
Step3.After printing the data,move the temp pointer to the next node.
Step4.Do the above process until wereach the end.

Program:
#include<stdio.h>
#include<stdlib.h>
Int main()
{
structnode
{
intdata;
struct node*next;
};
struct node *head,*middle,*last;
head= malloc(sizeof(struct node));
middle=malloc(sizeof(struct node));
last= malloc(sizeof(struct node));
head->data=10;
middle->data=20;
last->data=30;
head->next=middle;
middle->next = last;
last->next=NULL;
struct node*temp=head;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("NULL");

return0;}
Output

10->20->30->NULL
EX-NO: 9
Implementation of Binary Trees and operations
of Binary Trees
DATE:

Aim:
Write a program to Implementation of Binary Trees and operations of Binary Trees

Algorithm

Step1First,declared a function"create"

Step2It takes a value as aninputand create sand returns a node that will have the data variable
equal to the value,and the left and right pointer variables will point to NULL.

Step3To insert the left child,use theinser tLeft function,

Step4which takes the pointer to the parent node and the value.

Step5Then in ternally it calls the create function and then odere turned by it is attached to the
left pointer of the parent node.

Step6Similarly,the insert Right function works.

Program:
//Tree traversal in C
#include <stdio.h>
#include <stdlib.h>
structnode
{
Int item;
struct node* left;struct node*right;
};
Void in order Traversal (structnode*root)
{
if (root == NULL)
return;
in order Traversal(root->left);
printf("%d ", root->item);
inorder Traversal (root->right);
}
Void preorder Traversal(structnode*root)
{
if (root == NULL) return;
printf("%d ", root->item);
preorder Traversal(root->left);
preorderTraversal(root->right);
}
Void postorder Traversal(structnode*root)
{
if (root == NULL)
return;
post order Traversal(root->left);
postorder Traversal(root->right);
printf("%d",root->item);
}
Struct node*create(int value)
{
Struct node*new Node=malloc(sizeof(structnode));
New Node->item=value;
new Node->left = NULL;
new Node->right=NULL;
return new Node;
}
Struct node*insert Left(struct node*root,int value)
{
root->left = create(value);
return root->left;
}
Struct node*insert Right(struct node*root,int value)
{
root->right = create(value);
returnroot->right;
}
Int main()
{
Struct node*root=create(1;
insert Left(root,4);
insert Right(root,6);
insert Left(root->left,42);
insert Right(root->left,3);
insert Left(root->right,2);
insert Right(root->right,33);
printf("Traversal of the inserted binary tree\n");
printf("Inorder traversal \n");
inorder Traversal(root);
printf("\nPreorder traversal\n");
preorder Traversal(root);
printf("\nPostorder traversal\n");
postorder Traversal(root);
}
Output:

Traversal of the inserted binary tree

Inorder traversal 424312633

Preorder traversal 144236233

Postorder traversal 423423361


EX-NO: 10

Implementation of Binary Search Trees


DATE:

Aim:
Write a program to Implementation of Binary Trees and operations of Binary Trees
Algorithm

Step1Define Node class which has three attributes namely :data,left and right. Here, left
represents the left child of the node and right represents the right child of the node.

Step2When a node is created, data will pass to the data attribute of the node and both left and
right will be set to null.

Step3 Define another class which has an attribute root.


Root represents the root node of the tree and initializes it to null.
Step4 insert() will insert the new value intoa binary search tree:
It checks whether root is null, which means tree is empty. New node will
become root node of tree.
If tree is not empty, it will compare value of new node with root node. If value
of new node is greater than root, new node will be inserted to right subtree.
Else, it will be inserted in left subtree.
Step5 deleteNode()will delete a particular nodefrom the tree:
If value of node to be deleted is lessthan root node, search node in leftsubtree
.Else,search in right subtree.
If node is found andit has no children, then set the node to
null.If node has one child then, child node will take position
of node. If node has two children then, find a minimum value
node from its right subtree. This minimum value node will
replace the current node.

Program:

#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
struct
node
{
Int data;
struct node *left;
structnode*right;
};
Struct node*root=NULL;
Struct node*create Node(intdata){
Struct node*new Node=(struct node*)malloc(sizeof(struct node));
New Node->data= data;
New Node->left = NULL;
New Node->right=NULL;
return new Node;
}
Void insert(intdata)
{
Struct node*new Node=create Node(data);
if(root == NULL)
{
root=newNode;
return;
}
else{
struct node*current=root,*parent=NULL;
while(true){
parent=current;
if(data<current->data)
{
current = current->left;
if(current==NULL)
{
parent->left=new Node;
return;
}
}
//If data is greater than current's data, node will be inserted to the right of tree
else
{
current=current->right;
if(current==NULL)
{
parent->right=newNode;
return;
}
}
}
}
}
Struct node*min Node(struct node*root)
{
if(root->left!=NULL)
return minNode(root->left);
else
return root;
}
Struct node*delete Node(structnode*node,intvalue)
{
if(node==NULL)
{
returnNULL;
}
Else
{
if(value<node->data)
node->left=delete Node (node->left,value);
else
if
(value>node->data)
node->right=delete Node(node->right,value);
else
{
if(node->left==NULL&&node->right==NULL)node= NULL;
else
if
(node->left==NULL){node=node->right;
}
Else
If
(node->right==NULL){node=node->left;
}
Else
{
Struct node*temp=min Node(node->right);
node->data =temp->data;
node->right=delete Node(node->right,temp->data);
}
}
return node;
}
}
Void inorder Traversal(struct node*node)
{
if(root == NULL)
{
printf("Treeisempty\n");
return;
}
else
{
if(node->left!= NULL)inorder Traversal(node->left);
printf("%d ", node->data);
if(node->right!= NULL)inorderTraversal(node->right);
}
}
Int main()
{
insert(50);
insert(30);
insert(70);
insert(60);
insert(10);
insert(90);
printf("Binary search tree after insertion:\n");
inorder Traversal(root);
struct node *deletedNode = NULL;
deletedNode=deleteNode(root,90);
printf("\nBinary search tree after deleting node90:\n");
inorder Traversal(root);
deleted Node=deleteNode(root,30);
printf("\nBinary search tree after deleting node30:\n");
inorderTraversal(root);
deletedNode=deleteNode(root,50);
printf("\nBinary search tree after deleting node50:\n");
inorderTraversal(root);
return0;
}
Output:

Binary search tree after insertion:103050607090


Binary search tree after deleting node90:1030506070
Binary search tree after deleting node30:10506070
Binary search tree after deleting node50:106070
EX-NO: 11

Implementation of searching techniques


DATE:

Aim:
Write a program to Implementation of searching techniques

Algorithm

Step1 :Searching for the key element is done in a linear fashion.


Step2 :It is the simplest searching technique.
Step3 :It does not expect the list to be sorted.
Step4 :Limitation−It consumes more time and reduce the power of system.

Program:

#include<stdio.h>
int main()
{
int a[50], n, i, key, flag = 0;
printf("enter the no:of elements");
scanf("%d",&n);
printf("enter the elements:");
for(i=0;i<n;i++)
scanf( "%d", &a[i]);
printf("enter a key element:");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
flag=1;
break;
}
}
if(flag==1)
printf("search is successful:");
else
printf("search is unsuccessfull:");
return0;
}
Output

Enter the no:of elements 5


Enter the elements:12
45
13
67
78
Enter a key element:67
Search is successful
EX-NO: 12

Merge Sort Algorithm


DATE:

Aim:
To Write a program to implement merge sort in C language.

Algorithm:

Step1. Declare Array, left, right and mid variables


Step 2. Find mid by formula mid = (left+right)/2
Step3.CallMerge Sort for the left to mid
Step4.CallMerge Sort for mid+1to right
Step5.Continue step2,3,and 4 while the left is lessthan the right
Step6.Then Call the Merge function
Step7.End

Program:

#include<stdio.h>
Void merge(int a[],int beg,int mid,int end)
{
inti,j,k;
int n1=mid-beg+1;
int n2=end-mid;
int Left Array[n1],Right Array[n2];
//temporary arrays for(inti=0;i<n1;i++)
Left Array[i]=a[beg+i];
for(intj=0;j <n2; j++)
Right Array[j]=a[mid+1+j];
i=0;/*initial index of first sub-array*/
j=0;/*initial index of second sub-array*/
k=beg;/*initial index of merged sub-array*/

while(i<n1&& j<n2)
{
if(Left Array[i]<=Right Array[j])
{
a[k]=LeftArray[i];
i++;
}
else
{
a[k]=Right Array[j];
j++;
}
k++;
}
while(i<n1)
{
a[k]=Left Array[i];
i++;
k++;
}
while(j<n2)
{
a[k]=RightArray[j];
j++;
k++;
}
}
Void merge Sort(int a[],int beg,int end)
{
if(beg<end)
{
int mid = (beg + end) / 2;
merge Sort(a, beg, mid);
merge Sort(a,mid+1,end);
merge(a,beg,mid,end);
}
}
Void print Array(int a[],int n)
{
inti;
for (i = 0; i< n; i++)
printf("%d",a[i]);
printf("\n");
}
int main()
{
int a[]={12,31,25,8,32,17,40,42};
intn=size of(a)/size of(a[0]);
printf("Before sort ing array elements are-\n");
print Array(a,n);
mergeSort(a,0,n-1);
printf("After sort ing array elements are-\n");
printArray(a,n);
return0;
}
Output:
Before sorting array elements are –123125832174042
After sorting array elements are–812172531324042
EX-NO: 13
Write a program to implement insertion
sort in C language.
DATE:

Aim:
To write a program to implement insertion sort in C language.

Algorithm

Step1-If the element is the first element, assume that it is already sorted.Return1.
Step2-Pick the next element,and store it separately in a key.
Step3-Now,compare the key with all elements in the sorted array.
Step4If the element in the sorted array is smaller than
The current element, then move to then ext element. Else, shift greater elements in the array
towards the right.
Step5-Insert the value.
Step6-Repeat until the array is sorted.

Program:
#include<stdio.h>
Void insert(int a[],int n)
/*function to sortanaay with insertion sort*/
{
inti,j,temp;
for(i=1;i<n;i++)
{
temp =a[i];
j =i - 1;
while
(j>=0&&temp<=a[j])
{
a[j+1]= a[j];
j =j-1;
}
a[j+1]=temp;
}
}
Void print Arr(inta[],intn)
{
inti;
for (i = 0; i< n; i++)
printf("%d",a[i]);
}
int main()
{
int a[]={12,31,25,8,32,17};
int n=size of(a)/size of(a[0]);
printf("Before sorting array elements are-\n");
print Arr(a,n);
insert(a,n);
printf("\nAfter sorting array elements are-\n");
printArr(a,n);
return0;
}
Output:

Before sorting array elements are–123125832174042

After sorting array elements are–812172531324042


EX-NO: 14

Write a program to Implementation of Hashing–any two


DATE: collision techniques

Aim:
To write a program Implementation of Hashing–any two collision techniquesin C

Algorithm:

Step1Hashing is an efficient method to store and retrieve elements.

Step2It’s exactly same as index page of a book. In index page ,every topic is associated with a
page number.

Step3If we want to look some topic,we can directly get the page number from the index.

Step4Like wise,in hashing every value will be associated with a key.

Step5Using this key,we can point out the elementd irectly.

Program:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 20struct Data Item
{
int data;
int key;
};
Struct Data Item*has h Array[SIZE];
struct Data Item* dummy Item;
struct Data Item*item;
int has h Code(int key)
{
Return key%SIZE;
}
Struct Data Item*search(int key)
{
Int has h Index=has h Code(key);
While (has h Array[has h Index]!=NULL)
{
if(has h Array[has h Index]->key==key)return has h Array[has h Index];
++hashIndex;
has h Index%=SIZE;
}
return NULL;
}
Void insert(int key,int data)
{
Struct Data Item*item=(struct Data Item*)malloc(sizeof(struct Data Item));
item->data=data;
item->key=key;
int has h Index=has h Code(key);
while(has h Array[has h Index]!=NULL&&has h Array[has h Index]->key!=-1)
{
++hashIndex;
has h Index%=SIZE;
}
has h Array[has h Index]=item;
}
struct Data Item*delete(struct Data Item*item)
{
intkey=item->key;
get the has h
int has h Index = has h Code(key);
while(has h Array[has h Index]!=NULL)
{
if(has h Array[has h Index]->key==key)
{
Struct Data Item*temp=has h Array[has h Index];has h Array[has h Index]=dummy Item;
return temp;
}
++hashIndex;
has h Index%=SIZE;
}
return NULL;
}
Void display()
{
Int i=0;
for(i = 0; i<SIZE; i++)
{
if(has h Array[i]!=NULL)
printf("(%d,%d)",hashArray[i]->key,has h Array[i]->data);
else
printf("~~");
}
printf("\n");
}
int main()
{
dummy Item=(struct Data Item*)malloc(sizeof(struct Data Item));
dummy Item->data=-1;
dummy Item->key=-1;
insert(1,20);
insert(2,70);
insert(42,80);
insert(4,25);
insert(12,44);
insert(14,32);
insert(17,11);
insert(13,78);
insert(37, 97);
display();
item = search(37);
if(item!=NULL)
{
printf("Elementfound:%d\n",item->data);
}
Else
{
printf("Elementnotfound\n");
}
delete(item);
item = search(37);
if(item!=NULL)
{
printf("Elementfound:%d\n",item->data);
}
Else
{
printf("Elementnotfound\n");
}
}
Output:

~~
(1,20) (2,70) (42,80) (4,25)
~~~~~~~~~~~~~~(12,44)(13,78)(14,32)
~ ~ ~ ~(17,11)(37,97)
~~

Element found:97Element not found

You might also like