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

c rec

Uploaded by

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

c rec

Uploaded by

M.C. JOHN BRITTO
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 99

ST.

JOSEPH COLLEGE OF ENGINEERING


SRIPERUMBUDUR

CS3362-C PROGRAMMING AND DATA


STRUCTURES LABORATORY

NAME OF THE STUDENT :

DEPARTMENT :

REGISTER NO :

YEAR / SEM : II/ III

1
2
INDEX

Ex.No Date Content Pg.No Remarks


1. Practice of C programming using 4
statements, expressions, decision making
and iterative statements

2. Practice of C programming using 6


Functions and Arrays

3. Implement C programs using Pointers and 7


Structures

4. Implement C programs using Files 8

5. Development of real time C applications 11

6. Array implementation of List ADT 18

7. Array implementation of Stack and Queue 22


ADTS

8. Linked list implementation of List. Stack 29


and Queue ADTS

9. Applications of List, Stack and 39


Queue ADTS

10. Implementation of Binary Trees and 46


operations of Binary Trees

11. Implementation of Binary Search Trees 49

12. Implementation of searching techniques 53

13. Implementation of Sorting algorithms: 58


Insertion Sort, Quick Sort, Merge Sort

14. Implementation of Hashing - any two 66


collision techniques

3
Ex.No: 1 I/O STATEMENTS, EXPRESSIONS,DECISION MAKING AND IT
Date:
AIM:
To write a program for I/O statements, operators, expressions using C.

ALGORITHM:
STEP1:Start the program.
STEP2:Declare the variables
totamt,amount,subtot,distant,taxamt,quantity,value,discount,tax.
STEP3:Read the values for the variables.
STEP4:Perform addition, subtraction and multiplication.
STEP5:Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
Void main()
{
float totamt,amount,subtot,distant,taxamt,quantity,value,discount,tax;
printf("\nenter the quantity of item sold:");
scanf("%f",&quantity);
printf("\n enter the value of item:");
scanf("%f",&value);
printf("\n enter the discount
percentage:"); scanf("%f",&discount);
printf("\n enter the tax:");
scanf("%f",&tax);
amount=quantity*value;
distant=(amount*discount)/100.0;
subtot=amount-distant;
taxamt=(subtot*tax)/100.0;
totamt=subtot+taxamt; printf("\n\n\
n******bill******"); printf("\n
quantity sold:%f",quantity); printf("\n
priceperitem:%f",value); printf("\n
amount %f",amount); printf("\n
discount:%f",distant); printf("\n
discounted total: %f",subtot); printf("\
n tax:+ %f",taxamt);
printf("\n total amount %f",totamt); getch();
}

4
OUTPUT:
Enter the quantity of item sold:10
Enter the value of item:50
Enter the discount percentage:10
Enter the tax:10
Quantity sold:10.00
Price per item:50.00
Amount:500.00
Discount:50.00
Discounted total:450.00
Tax:+45
Total amount:495.00

RESULT:
Thus the program for I/O statements, operators and expressions are
executed successfully.

5
Ex.No: 2 FUNCTIONS AND ARRAY
Date:

AIM:
Write a program in C using one dimensional array.

ALGORITHM:

STEP1:Start the program.


STEP2:Declare the array.
STEP3:Read the values in the array.
STEP4:Compare first two numbers in array.
STEP5:If first number is greater than second number, swap the values.
STEP6:Continue until all the numbers are arranged in ascending
order. STEP7:Stop the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
void fun(int a[5] ):/^ * function
declaration"/ int all (10,20,30,40,50):
clrscr();
fun(a):/"call to the function"/
getch()
void fun(int a[6])
int i;
for(i=0;i<5;1++)
printf("%d", "(a+1)); /or printf("%d",alil);"/ }

OUTPUT:

10, 20,30,40,50

RESULT:
Thus the program to arrange numbers in ascending order using one dimensional array is
executed successfully.

6
Ex.No: 3
Date: POINTERS AND STRUCTURES

AIM:
Write a program in C for pointers to structures.
ALGORITHM:
STEP1:Start the program
STEP2:Declare the variables and pointer variable.
STEP3:Read the value of variables.
STEP4:Using the structure do process.
STEP5:Print the output.
STEP6:Stop the program.

PROGRAM:
#include<stdio.h>
struct person{
int age;
float weight;
};
int main(){
struct person *personPtr,
person1; personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr-
>weight); return 0;
}
RESULT:
Thus the program for pointers and structure is executed successfully.

7
Ex.No: 4
Date: FILES: READING AND WRITING, FILE POINTERS, FILE OPERATIONS, R

AIM:
Write a program in C for files reading and writing, file pointers, file operations,
random access, processor directives.

Reading a file

fgetc(file_pointer): It returns the next character from the file pointed to by the file
pointer. When the end of the file has been reached, the EOF is sent back.

fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string
in a buffer in which the NULL character ‘\0’ is appended as the last character.

fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and


analyze data. It reads characters from the file and assigns the input to a list of variable
pointers variable_adresses using conversion specifiers. Keep in mind that as with
scanf, fscanf stops reading a string when space or newline is encountered.

PROGRAM:

#include <stdio.h>
int main()
{
FILE * file_pointer;
char buffer[30], c;
file_pointer = fopen("fprintf_test.txt",
"r"); printf("----read a line \n");
fgets(buffer, 50,
file_pointer); printf("%s\n",
buffer);
printf("----read and parse data- - -\n");
file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer
char str1[10], str2[2], str3[20], str4[2];
fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);
printf("Read String1 |%s|\n", str1);
printf("Read String2 |%s|\n", str2);
printf("Read String3 |%s|\n", str3);
printf("Read String4 |%s|\n", str4);
printf("----read the entire file- - -\n");
file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer
while ((c = getc(file_pointer)) != EOF) printf("%c", c);
fclose(file_pointer);
return 0;
}
8
Writing to file
The above program writes a single character into the fputc_test.txt file until it reaches the
next line symbol “\n” which indicates that the sentence was successfully written. The
process is to take each character of the array and write it into the file.
#include <stdio.h>
int main() {
int i;
FILE * fptr;
char fn[50];
char str[] = "Guru99 Rocks\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++) {
/* write to file using fputc() function */
fputc(str[i], fptr);
}
fclose(fptr);
return 0;
}
Random Access in File
fseek() function is used to take file pointer to a particular position data file.
Syntax: fseek(Fpointer, Position, Initial);
Fpointer is name of file pointer variable.

Position number of characters to be jumped.

Initial specifies the position from where file pointer should be jumped. It can three
values :
0: From the beginning of file.

1: Current position.
2: End of file
#include<stdio.h>
int main()
{
FILE *f1;
char line[80] , s;
int n;
f1=fopen(“data.txt”,”r”);
fgets(line,80,f1);
printf(“%s”,line);
fseek(f1,2,0);
/*File pointer jumped to 3rd character from beginning*/
s=getc(f); /*5th Character read from file*/ printf(“\n
%c”,s);

fseek(f1,2,1);
/*File pointer jumped to 3rd character from current
position*/

9
s=getc(f); printf(“\n
%c”,s);
fseek(f1,0,2);
/*File pointer jumped end of file* /
s=getc(f);
printf(“\n%c”,s);
fclose(f);
return(0);
}

Preprocessor Directive
The #error preprocessor directive indicates error. The compiler gives fatal
error if #error directive is found and skips further compilation process.

#include<stdio.h>
#ifndef MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif

RESULT:
Thus the program in C for files reading and writing, file pointers, file operations, random
access, processor directives is executed successfully.

1
Ex.No: 5
Date: DEVELOPMENT OF REALTIME C APPLICATION

Problem Statements for the Project


Create a file (binary or text of your choice) that contains information about a group of n
people. Information is entered from the keyboard, a person being described by: name
(string), first name (string character), and age (whole type without sign).
1. Read from the keyboard n (n input from the keyboard) such structures and write them
in a file (binary or text);
2. Display the contents of the file on the screen;
3. Read another keyboard from the keyboard as previously defined and check its
existence in the files. If it does not exist, it will be added. Re-display the contents of the
file on the screen;
4. Calculate and display the age average of all people in the file (only the information
in the file will be used!);
5. Sort the existing components in the files according to the field age (ascending
/ descending, optional);
6. Remove people with a specific name from the files (specified on the keyboard);
7. Check (by screen view) if the name of the 3rd person is correctly written in the files.
If not,
correct the file name! (You will see the message "Do you want to change the name (D /
N)?" For the user to express their choice).

Each of the above mentioned operations is provided to the program user in the form of
a "menu" with the options:
 1- file creation
 2- display the contents of the file
 3- add information to the file
 4- age average calculation
 5- sort file contents
 6- person removal
 7- correctness information analysis
 8- end program
Source Code
#include <stdio.h>
#include <stdlib.h>

char fileName[20];

int createFile(){
/* file is created in current working directory */
FILE * fptr = NULL;
int mode = 2;
printf("\n Enter name of file :
"); scanf(" %s", fileName);
fptr = fopen(fileName, "w");
if(fptr!=NULL)
fclose(fptr);
return 0;

1
}
void displayFileContents(){
FILE *fptr = fopen(fileName,
"r"); char c;
long int count = 0;
printf("\n---- File Content----------\n\n");
while ((c = getc(fptr)) != EOF)
{ putchar(c); count++;
}
if(count==0)
printf("\n Warning: File is empty!!");
else
fclose(fptr);

void addInfo(){
char name[50];
unsigned char age;
getchar();
printf("\n\n Enter Name :
"); gets(name);

/* check if name already exist */


FILE* fptr = fopen(fileName, "r");
char line[500];

char alreadyExist = 0;
while (fgets(line, sizeof(line), fptr)) {
if(strstr(line, name))
alreadyExist = 1;
}

fclose(fptr);

if(alreadyExist==1)
{
printf("\n Record already exist !!");
printf(" %s ", line);
}
else{
fptr = fopen(fileName, "a");
fputs(name, fptr);

printf("\n Enter Age : ");


scanf("%d",&age);

char buffage[5];
char temp[5];
strcpy(temp, " | ");

itoa(age, buffage, 10);

strcat(temp, buffage);
strcat(temp, "\n");
fputs(temp, fptr);

/* close the file */


fclose(fptr);
1
}

void calcualteAvgAge(){
FILE* fptr = fopen(fileName, "r");
char line[500];
char *ptr = NULL;
float avg = 0;
char alreadyExist = 0;
int count =0;
while (fgets(line, sizeof(line), fptr)) {
ptr = strtok(line, "|");
ptr = strtok(NULL, "|");
avg += atoi(ptr); count+
+;
}
if(count>0){
avg = avg/count;
printf("\nAverage Age is : %.2f",avg) ;
}
else{
printf("\n No data to calcualte avg age.");
}

void sortFileContents(){
FILE* fptr = fopen(fileName, "r");
char line[500];
float tempArr[500];
char *ptr = NULL;
int i=0, count=0;
while (fgets(line, sizeof(line), fptr)) {
count++;
ptr = strtok(line, "|");
ptr = strtok(NULL, "|");
tempArr[i++] = atoi(ptr);
}

int order=0;
printf("\n\n Press 1 for Assending order ");
printf("\n Press 2 for Desending order : ");
scanf("%d",&order);

/* sort the Age array in Descendin order */


float temp =0;
int j;
for(i=0; i<count; i++){
for(j=i+1; j<count;j++){

if(order==2){
if(tempArr[j] > tempArr[i])
{ temp=tempArr[j];
tempArr[j] =
tempArr[i]; tempArr[i]
= temp;
}
}
1
else{

1
if(tempArr[i] > tempArr[j])
{
temp=tempArr[j];
tempArr[j] = tempArr[i];
tempArr[i] = temp;
}
}

}
}

for(i=0; i<count; i++){


rewind(fptr);
while (fgets(line, sizeof(line), fptr)) {
float temp=0;
char tempLine[500];
memset(tempLine, NULL, sizeof(tempLine));
strcpy(tempLine, line);
ptr = strtok(line, "|");
ptr = strtok(NULL, "|");
temp = atoi(ptr);

if(temp == tempArr[i]){
printf("\n %s", tempLine);
break;
}

}
}

void removePerson(char *nameptr){


printf("\n --- Remove Person from Records ---");
char name[50];
memset(name, NULL, sizeof(name));

if(nameptr==NULL){ printf("\
n\n Enter Name : ");
getchar(); gets(name);
}
else
strcpy(name, nameptr);

FILE* fptr = fopen(fileName, "r");

if(fptr==NULL){
printf("\n Error: No record
exist"); return;
}

char temp[]="temp";
//file mode should be same as bas file
FILE* fptrTmp = fopen(temp, "w");
if(fptrTmp==NULL){
printf("\n Error: Unable to perform this operation");
return;
}

1
char line[500];
int count =0;
while (fgets(line, sizeof(line), fptr)) {
if(strstr(line, name)){
//don't copy it
count++;

printf("\n---debug: name matched line is : %s",line);


memset(line, NULL, sizeof(line));
continue;
}
else{
fputs(line, fptrTmp);
printf("\n putting : %s in new file", line);
}
memset(line, NULL, sizeof(line));
}

fclose(fptrTmp);
fclose(fptr);

if(count>0){
printf("fileName : %s removed ", fileName);

if(remove(fileName) == 0)
printf("\n File %s is deleted successfully", fileName);
else
printf("\n Error while deleting file %s ", fileName);

getchar(); getchar();
rename(temp, fileName);
printf("\n Success ! Reocrd found & deleted");
}
else{
printf("\n Error: Record not found");
}
remove(temp);
}

void correctInfo(){
/* create a temporary file */
FILE* fptr = fopen(fileName, "r");

if(fptr==NULL){
printf("\n Error: No record
exist"); return;
}

char temp[]="temp1";
char line[500];
//file mode should be same as bas file
FILE* fptrTmp = fopen(temp, "w");
while (fgets(line, sizeof(line), fptr)) {
fputs(line, fptrTmp);
//printf("\n putting : %s in new file", line);
memset(line, NULL, sizeof(line));
}
fclose(fptrTmp);
fclose(fptr);
1
fptrTmp = fopen(temp, "r");

float tempArr[500];
char *ptr = NULL;
char name[50];
memset(name, NULL, sizeof(name));

int i=0, count=0;


char choice='\0';
memset(line, NULL, sizeof(line));
while (fgets(line, sizeof(line), fptr)) {
count++;
printf("\n %s ", line);

printf("\n Do u want to update this record? y/n :");


scanf(" %c",&choice);

if(choice=='y'){
ptr = strtok(line, "|");
strcpy(name, ptr);
removePerson(name);
printf("\n\n Please enter new values ");
addInfo();
break;
}
}
close(fptr);
}

void menu(){
char choice = -1;

while(choice!=8){
printf("\n\n\n #### Main Menu ####\n\n");
printf("\n 1. File creation");
printf("\n 2. Display the contents of the file");
printf("\n 3. Add Info to file");
printf("\n 4. Age average calcualtion");
printf("\n 5. Sort file contents");
printf("\n 6. Person removal");
printf("\n 7. Correctness information analysis");
printf("\n 8. End program");

printf("\n\n Enter your choice : ");


scanf("%d", &choice);

switch(choice){
case 1:
if(createFile() == 0)
printf("\n Success : File created
successfully!");
else
printf("\n Error: Can't create file'");
break;
case 2:
displayFileContents();
break;
1
case 3:
addInfo();
break;
case
4: calcualteAvgAge();

break;
case sortFileContents();
5:

break; removePerson(NULL);
case
6:
correctInfo();
break;
case
7:

break;
case 8: printf("\n thanks for using the
application \n ");
default: printf("\n Error: Invalid Choice! Enter
again");
getchar();
}
}

int main(int argc, char *argv[]) {


menu();
return 0;
}

Execution of the Project

1
RESULT:
Thus the program is executed
and the output is verified.

1
Ex.No:6
Date: LIST USING ARRAY

AIM:
To perform various operations on List ADT using array implementation.

ALGORITHM:
1. Start
2. Create a list of n elements
3. Display list operations as a menu
4. Accept user choice
5. If choice = 1 then
Get position of element to be
deleted Move elements one position
upwards thereon.Decrement length
of the list
Else if choice = 2
Get position of element to be
inserted.Increment length of the list
Move elements one position downwards thereon
Store the new element in corresponding position
Else if choice = 3
Traverse the list and inspect each element
Report position if it exists.
6. Stop

PROGRAM

#include
<stdio.h>
#include
<conio.h>

void
create();
void insert();
void
search();
void
deletion();
void
display(); int
i, e, n, pos;
static int
1
b[50];
main()
{
int ch;
char g =
'y';
create();
do

1
{
printf("\n List Operations");
printf("\n 1.Deletion\n 2.Insert\n 3.Search\n4.Exit\n");
printf("Enter your
choice: "); scanf("%d",
&ch); switch(ch)
{
case 1:
deletion();
break;
case 2:
insert(); break;
case 3:
search();
break;
case 4:
exit(0);d efault:
printf("\n Enter the correct choice:");
}
printf("Do you want to continue:
"); fflush(stdin);
scanf("\n %c",&g);
} while(g=='y' || g=='Y');g etch();
}

void create()
{
printf("\n Enter the number of
elements:"); scanf("%d",&n);
printf("\n Enter list elements:
");for(i=0; i<n; i++)
scanf("%d", &b[i]);
}

void deletion()
{
printf("\n enter the position you want to delete: ");s
canf("%d", &pos);
if(pos >= n)
printf("\n Invalid location"); else
{
for(i=pos+1; i<n; i++)b[i-1]
= b[i];
n--;
printf("List elements after deletion"); display();
}
}
1
void search()
{
int flag = 0;
printf("\n Enter the element to be searched:
");scanf("%d", &e);
for(i=0; i<n; i++)
{
if(b[i] == e)
{
flag = 1;
printf("Element is in the %d position", i);b reak;
}
}
if(flag == 0)
printf("Value %d is not in the list", e);
}

void insert()
{
printf("\n Enter the position you need to insert: ");s
canf("%d", &pos);
if(pos >= n)
printf("\n Invalid location"); else
{

++n;
for(i=n; i>pos;
i--) b[i] = b[i-
1];
printf("\n Enter the element to insert: ");s
canf("%d", &e);
b[pos] = e;
}
printf("\n List after insertion:"); display();
}

void display()
{
for(i=0; i<n; i++) printf("\n
%d", b[i]);
}

OUTPUT

2
Enter the number of elements:5 Enter
list elements: 12 23 34 45 56

2
List Operations
1.Deletion 2.Insert
3.Search
4.Exit
Enter your choice:2
Enter the position you need to insert: 1 Enter the
element to insert: 99
List after insertion:
12
99
23
34
45
56
Do you want to continue: y

List Operations
1.Deletion 2.Insert
3.Search
4. Exit
Enter your choice:1
Enter the position you want to delete: 3

Elements after
deletion1 2 99
23
45
56
Do you want to continue: n

RESULT:

Thus various operations was successfully executed on list using array implementation.

2
Ex.No:7a Date:
STACK ARRAY

AIM:
To implement stack operations using array.

ALGORITHM:
1. Start
2. Define a array stack of size max= 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top
elementDecrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop

PROGRAM:
#include <stdio.h>
#include

<conio.h>#define static

int stack[max];

int top = -1;

void push(int

x)

stack[++top] = x;
}

2
int pop()
{
return (stack[top--]);
}

2
void view()
{
int i;
if (top < 0)
printf("\n Stack Empty \n");else
{
printf("\n Top-->");
for(i=top; i>=0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}
main()
{
int ch=0,
val; clrscr();
while(ch !=
4)
{
printf("\n STACK OPERATION \n");
printf("1.PUSH ");
printf("2.POP ");
printf("3.VIEW ");
printf("4.QUIT \n");
printf("Enter Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(top < max-1)
{
printf("\nEnter Stack element : ");
scanf("%d", &val);
push(val);
}
else
printf("\n Stack Overflow \
n");break; case 2:
if(top < 0)
printf("\n Stack Underflow \n");e lse
{
val = pop();
printf("\n Popped element is %d\n", val);
}
break;
2
case 3:
view();b reak;

2
case 4:
exit(0);d efault:
printf("\n Invalid Choice \n");
}
}
}

OUTPUT:

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 12

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 23

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 34

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 45

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3

Top--> 45 34 23 12

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 2

Popped element is

45

RESULT:
2
Thus push and pop operations of a stack was demonstrated using arrays

2
Ex.No:7b Date: Queue Array

AIM:
To implement queue operations using array.

ALGORITHM:
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then If rear < max -
1 Increment rear
Store element at current position of
rear Else
Print Queue Full
Else If choice = 2 then If front = –1 then
Print Queue empty

Else

Display current front element

Increment front

Else if choice=3 then


Display queue elements starting from front to
rear stop

PROGRAM:

include <stdio.h>
#include <conio.h>

#define max 5

static int

queue[max]; int

front = -1;

2
int rear = -1;

2
void insert(int x)
{
queue[++rear] =
x;i f (front == -1)
front = 0;
}
int remove()
{
int val;
val = queue[front];
if (front==rear && rear==max-1)f
ront = rear = -1;
else
front ++;
return (val);
}void view()
{
int i;

if (front == -1)
printf("\n Queue Empty \n");e lse
{
printf("\n Front-->");
for(i=front; i<=rear; i++)
printf("%4d", queue[i]);
printf(" <--Rear\n");
}
}main()
{
int 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 : ");s
canf("%d", &ch); switch(ch)
{
case 1:
if(rear < max-1)
{

2
printf("\n Enter element to be inserted : ");s
canf("%d", &val);
insert(val);
}

2
else
printf("\n Queue Full \n");
break; case 2:
if(front == -1)
printf("\n Queue Empty \n");e lse
{
val = remove();
printf("\n Element deleted : %d \n", val);
}
break;
case 3:
view();b
reak; case 4:
exit(0);d efault:
printf("\n Invalid Choice \n");
}
}
}

OUTPUT:

QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1

Enter element to be UEUE


inserted : 12Q

OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1

Enter element to be UEUE


inserted : 23Q

OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1

Enter element to be UEUE


inserted : 34Q

OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1

Enter element to be
inserted : 45Q OPERATION

2
UEUE
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1

2
Enter element to be UEUE
inserted : 56Q

OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1

Queue Full

QUEUE OPERATION
2. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 3

Front--> 12 23 34 45 56 <--Rear

RESULT:
Thus insert and delete operations of a queue was demonstrated using arrays

2
Ex. No. 8a Singly Linked List
Date:

AIM:
To define a singly linked list node and perform operations such as insertions
and
deletions dynamically.

ALGORITHM:
1. Start
2. Define single linked list nodes self referential structure
3. Create head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
Locate node after which insertion is to
be doneCreate a new node and get data
part
Insert new node at appropriate position by manipulating address
Else if choice = 2
Get node's data to be deleted.
Locate the node and delink the
nodeRearrange the links
Else
Traverse the list from Head node to node which points to null
7. Stop

PROGRAM:

#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
#include <string.h>

struct node
{
int label;
struct node *next;
};

main()
{
int ch, fou=0;i
nt k;
struct node *h, *temp, *head, *h1;
2
head = (struct node*) malloc(sizeof(struct node));h ead->label
= -1;

2
head->next = NULL;

while(-1)
{
clrscr();
printf("\n\n SINGLY LINKED LIST OPERATIONS \
n"); printf("1->Add "); printf("2-
>Delete "); printf("3-
>View "); printf("4-
>Exit \n"); printf("Enter
your choice : ");
scanf("%d", &ch);

switch(ch)
{
/* Add a node at any intermediate location */c ase 1:
printf("\n Enter label after which to add : ");scanf("%d", &k);

h = head;
fou = 0;

if (h->label ==
k)fou = 1;

while(h->next != NULL)
{
if (h->label == k)
{
fou=1;
break;
}
h = h->next;
}
if (h->label ==
k)fou = 1;

if (fou != 1)
printf("Node not found\n"); else
{
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : "); scanf("%d",
&temp->label);
temp->next = h->next;h -
>next = temp;
}
break
3
;

/* Delete any intermediate node */c ase 2:


printf("Enter label of node to be deleted\n");scanf("%d",

3
&k);
fou =
0;
h = h1 = head;
while (h->next != NULL)
{
h = h->next;
if (h->label == k)
{
fou = 1;
break;
}
}

if (fou == 0)
printf("Sorry Node not found\n"); else
{
while (h1->next !=
h)h 1 = h1-
>next;
h1->next = h->next;
free(h);
printf("Node deleted successfully \n");
}
break
;

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

case 4:
exit(0);
}
}
}
OUTPUT:

SINGLY LINKED LIST OPERATIONS


1->Add 2->Delete 3->View nter
4->ExitE your choice : 1
3
Enter label after which new node is to be added : -1
Enter label for new node : 23

SINGLY LINKED LIST OPERATIONS

3
1->Add 2->Delete 3->View nter
4->ExitE your choice : 1
Enter label after which new node is to be added :
23Enter label for new node : 67

SINGLY LINKED LIST OPERATIONS


1- >Add 2->Delete 3->View 4->Exit
Enter your choice : 3
HEAD -> 23 -> 67 -> NULL

RESULT:
Thus operation on single linked list is performed.

3
Ex. No. 8b Stack Using Linked List
Date:
AIM:
To implement stack operations using linked list.
ALGORITHM:
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to
first node
Make head node point to
new nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of
temp nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop

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));h
ead->next = NULL;

3
while(1)
{

3
printf("\n Stack using Linked List \n");p rintf("1-
>Push ");
printf("2->Pop
"); printf("3-
>View ");
printf("4->Exit \
n");
printf("Enter your choice : ");
scanf("%d", &ch);

switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : "); scanf("%d",
&temp->label);
h = head;
temp->next = h->next;h -
>next = temp; break;

case 2:
/* Delink the first node */h = head-
>next;
head->next = h->next;

printf("Node %s deleted\n", h->label); free(h);


break;

case 3:
printf("\n HEAD -> "); h
= head;
/* Loop till last hile(h-
node */w
>next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n"); break;

case 4:
exit(0);
}
}
}

3
OUTPUT:

Stack using Linked List


1->Push 2->Pop 3->View 4->Exit

3
Enter your choice : 1
Enter label for new node ew
: 23N node added

Stack using Linked List


1->Push 2->Pop 3->View 4-
>Exit Enter your choice : 1
Enter label for new node : 34

Stack using Linked List


1- >Push 2->Pop 3->View 4->Exit
Enter your choice : 3
HEAD -> 34 -> 23 -> NULL

RESULT:
Thus push and pop operations of a stack was demonstrated using linked list.

3
Ex. No. 8c Queue Using Linked
List Date:
AIM:
To implement queue operations using linked list.
ALGORITHM:
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to
first node
Make head node point to
new nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of
temp nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop

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));h

3
ead->next = NULL;

3
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)
{
case 1:
/* 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);
}
printf("NULL \n"); break;

case 4:
exit(0);
3
}
}
}

3
OUTPUT:

Queue using Linked List


1->Insert 2->Delete 3->View nter
4->ExitE your choice : 1
Enter label for new node : 12

Queue using Linked List


1->Insert 2->Delete 3->View nter
4->ExitE your choice : 1
Enter label for new node : 23

Queue using Linked List


1- >Insert 2->Delete 3->View 4->Exit
Enter your choice : 3
HEAD -> 12 -> 23 -> NULL

RESULT:
Thus insert and delete operations of a queue was demonstrated using linked list.
3
Ex. No. 9a Infix To Postfix Conversion
Date:

AIM:
To convert infix expression to its postfix form using stack operations.
ALGORITHM:
1. Start
2. Define a array stack of size max= 20
3. Initialize top = -1
4. Read the infix expression character-by-
character If character is an operand
print it
If character is an operator
Compare the operator’s priority with the stack[top] operator.
If the stack [top] has higher/equal priority than the input operator,
Pop it from the stack and print it.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack and
print it until a left parenthesis is encountered. Do not print the
parenthesis.
If character = $ then Pop out all operators, Print them and Stop

3
PROGRAM:

/* Conversion of infix to postfix expression */# include

<stdio.h>
#include <conio.h># include
<string.h> #define MAX 20

int top = -1;


char
stack[MAX];
char pop();
void push(char item);

int prcd(char symbol)


{
switch(symbol)
{
case '+':
case '-':
return 2;
break; case
'*':
case '/':
return 4;
break; case
'^':
case '$':
return 6;
break; case
'(':
case ')':
case '#':
returnbreak; 1;

}
}

int isoperator(char symbol)


{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
4
return 1;

4
break;d efault:
return 0;
}
}

void convertip(char infix[],char postfix[])


{
int i,symbol,j = 0; stack[++top] = '#';
for(i=0;i<strlen(infix);i++)
{
symbol = infix[i];
if(isoperator(symbol) == 0)
{
postfix[j] = symbol;j ++;
}
else
{
if(symbol == '(')
push(symbol
);
else if(symbol == ')')
{
while(stack[top] != '(')
{
postfix[j] = pop(); j++;
}
pop(); //pop out (.
}
else
{
if(prcd(symbol) > prcd(stack[top]))
push(symbol);
else
{
while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop(); j++;
}
push(symbol);
}
}
}
}

while(stack[top] != '#')
{
4
postfix[j] = pop();

4
j++;
}
postfix[j] = '\0';
}

main()
{
char infix[20],postfix[20]; clrscr();
printf("Enter the valid infix string: ");gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");p
uts(postfix); getch();
}

void push(char item)


{
top++;
stack[top] = item;
}

char pop()
{
char a;
a = stack[top];t op--
;
return a;
}

OUTPUT

Enter the valid infix string:


(a+b*c)/(d$e) The corresponding postfix
string is: abc*+de$/

Enter the valid infix string: a*b+c*d/e


The corresponding postfix string is: ab*cd*e/+

Enter the valid infix string: a+b*c+(d*e+f)*g


The corresponding postfix string is: abc*+de*f+g*+

RESULT:
4
Thus the given infix expression was converted into postfix form using stack.

4
Ex. No. 9b Postfix Expression Evaluation
Date:

AIM:
To evaluate the given postfix expression using stack operations.

ALGORITHM:
1. Start
2. Define a array stack of size max=20
3. Initialize top=-1
4. Read the postfix expression character-by-
character If character is an operand push it
onto the stackIf character is an operator
Pop topmost two elements from stack.
Apply operator on the elements and push the result onto the stack,
5. Eventually only result will be in the stack at end of the expression.
6. Pop the result and print it.
7. Stop

4
PROGRAM:

/* Evaluation of Postfix expression using stack */# include

<stdio.h>
#include <conio.h>

struct stack
{
int top; float
a[50];
}s;

main()
{
char pf[50]; float
d1,d2,d3; int i;
clrscr();

s.top = -1;
printf("\n\n Enter the postfix expression:
");gets(pf); for(i=0; pf[i]!='\0'; i++)
{
switch(pf[i])
{
case
'0':
case
'1':
case
'2':
case
'3':
case
'4':
case
'5':
case
'6':
case
'7':
case
'8':
case
'9':
s.a[++s.top] = pf[i]-'0';break;

case '+':
4
d1 = s.a[s.top--];
d2 = s.a[s.top--];
s.a[++s.top] = d1 +
d2; break;

case '-':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[+
+s.top] = d1 - d2;break;

4
case '*':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] =
d1*d2; break;

case '/':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[+
+s.top] = d1 / d2; break;
}
}
printf("\n Expression value is %5.2f", s.a[s.top]);g etch();
}

OUTPUT:

Enter the postfix expression:


6523+8*+3+* Expression value is
288.00

4
RESULT:
Thus the given postfix expression was evaluated using stack.

4
Ex. No. 1 0 Binary Tree
Date:

AIM:
To implement program for the given binary tree.

ALGORITHM:
1. Start the program
2. Create a tree
3. Perform the Insertion, Deletion and Search operation
4. Stop the program

PROGRAM:

#include<stdio.
h>
#include<stdlib.
h> struct node
{int value;
struct node *left_child, *right_child;
};
struct node *new_node(int value)
{struct node *tmp = (struct node
*)malloc(sizeof(struct node)); tmp->value = value;
tmp->left_child = tmp->right_child =
NULL; return tmp;
}
void print(struct node *root_node) // displaying the nodes!
{if (root_node != NULL)
{
print(root_node->left_child);
printf("%d \n", root_node-
>value); print(root_node-
>right_child);
}
}
struct node* insert_node(struct node* node, int value) // inserting nodes!
{
if (node == NULL) return
new_node(value); if (value < node-
>value)
{
4
node->left_child = insert_node(node->left_child, value);
}
else if (value > node->value)

{
node->right_child = insert_node(node->right_child, value);
}
return node;
}
int main()
{
printf("TechVidvan Tutorial: Implementation of a Binary Tree in
C!\n\n"); struct node *root_node = NULL;
root_node = insert_node(root_node,
10); insert_node(root_node, 10);
insert_node(root_node, 30);
insert_node(root_node, 25);
insert_node(root_node, 36);
insert_node(root_node, 56);
insert_node(root_node, 78);
print(root_node);
return 0;
}

OUTPUT:
Implementation of a Binary Tree
in C! 10
25
30
36
56
78

RESULT:

Thus the program for binary tree has been successfully and output is verified

4
Ex. No. 11 Binary Search Tree
Date:
AIM
To insert and delete nodes in a binary search tree.
ALGORITHM:
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If (root==NULL)
root=node
else if (root->key<node-
>key)root-
>right=NULL
else
Root->left=node
3. For
Deletion

4. Stop

PROGRAM:

#include <stdio.h>
# include <stdlib.h>

struct node
{
int key;
struct node *left;s
truct node *right;
}
;
struct node *newNode(int item)
{
struct node *temp = (struct node
*)malloc(sizeof(structnode)); temp->key = item;
temp->left = temp->right = NULL;r
eturn temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
4
inorder(root->right);
}
}

struct node* insert(struct node* node, int key)


{
if (node == NULL)
return
newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else node->right = insert(node->right,
key); return
node;
}

struct node * minValueNode(struct node* node)


{
struct node* current = hile
node;w (current->left !=
NULL)
current = current->left;
return current;
}
if it is a leaf node
Remove immediately
Remove pointer between del node &
childif it is having one child
Remove link between del node&child
Link delnode is child with delnodes
parent
If it is a node with a children
Find min value in right subtree
Copy min value to delnode
placeDelete the duplicate

4
Program
#include <stdio.h>
# include <stdlib.h>

struct node
{
int key;
struct node *left;s
truct node *right;
}
;
struct node *newNode(int item)
{
struct node *temp = (struct node
*)malloc(sizeof(structnode)); temp->key = item;
temp->left = temp->right = NULL;r
eturn temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}

struct node* insert(struct node* node, int key)


{
if (node == NULL)
return
newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else node->right = insert(node->right,
key); return
node;
}

struct node * minValueNode(struct node* node)


{
struct node* current = hile
node;w (current->left !=
NULL)
5
current = current->left;
return current;
}

5
struct node* deleteNode(struct node* root, int key)
{
struct node
*temp;if (root ==
NULL)
return root;
if (key < root-
>key)
root->left = deleteNode(root->left, key); else if (key
> root->key)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
temp = root-
>right;
free(root);
return temp;
}
else if (root->right == NULL)
{
temp = root-
>left; free(root);
return temp;
}
temp = minValueNode(root->right); root-
>key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
main()
{
struct node *root = NULL;r oot
= insert(root, 50);root
= insert(root, 30);r
oot = insert(root,
20);r oot =
insert(root, 40);r oot
= insert(root, 70);r
oot = insert(root, 60);r
oot = insert(root, 80);
printf("Inorder traversal of the given tree \n");i norder(root);
printf("\nDelete 20\n"); root =
5
deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");i
norder(root); printf("\nDelete 30\n"); root =
deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");i
norder(root); printf("\nDelete 50\n");

5
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");i norder(root);
}

OUTPUT:

Inorder traversal of the given tree2


0 30 40 50 60 70 80
Delete 20
Inorder traversal of the modified tree3
0 40 50 60 70 80
Delete 30
Inorder traversal of the modified tree4
0 50 60 70 80
Delete 50
Inorder traversal of the modified tree4
0 60 70 80

RESULT:
5
Thus nodes were inserted and deleted from a binary search tree.

5
Ex. No. 12a Linear Search
Date:
AIM:
To perform linear search of an element on the given array.

ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements Ai,I=0,1,2,-n-1
4. Read searchvalue
5. Assign 0 to found
6. Check each array element against search
If Ai = search then

found = 1

Print "Element found"


Print position i
Stop
7. If found=0 then
print "Element not found"
8. Stop

5
PROGRAM:

# include
<stdio.h>
#include
<conio.h>

main()
{
int a[50],i, n, val, found; clrscr();

printf("Enter number of elements :


"); scanf("%d", &n);
printf("Enter Array Elements : \n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);

printf("Enter element to locate : ");s


canf("%d", &val);
found = 0; for(i=0;
i<n; i++)
{
if (a[i] == val)
{
printf("Element found at position %d", i);f ound
= 1; break;
}
}
if (found == 0)
printf("\n Element not found");g etch();
}

Output
RESULT:
Enter number of
elements : 7E Array
Elements :
23 6 12 5 0 32 10
Enter element to locate :
5 Element found at
position 3

5
nter
Thus an array was linearly searched for an element's existence.

5
Ex. No. 12b Binary Search
Date:

AIM:
To locate an element in a sorted array using Binary search method

ALGORITHM:
1. Start
2. Read number of array elements, say n
3. Create an array arrconsisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower<upper)
Determine middle element mid =
(upper+lower)/2If key = arr[mid] then
Print mid
Stop
Else if key > arr[mid]
thenlower = mid
+1
else
upper = mid – 1

7. Print "Element not found"


8. Stop

5
PROGRAM:

/* Binary Search on a sorted array */ #include

<stdio.h>
#include <conio.h>

main()
{
int a[50],i, n, upper, lower, mid, val, found;c lrscr();

printf("Enter array size : ");


scanf("%d", &n);
for(i=0; i<n; i+
+)a [i] = 2 * i;

printf("\n Elements in Sorted Order \


n");for(i=0; i<n; i++)
printf("%4d", a[i]);

printf("\n Enter element to locate : ");s


canf("%d", &val);
upper =
n; lower
= 0;
found = -
1;
while (lower <= upper)
{
mid = (upper +
lower)/2;if (a[mid] ==
val)
{
printf("Located at position %d", mid);
found = 1; break;
}
else if(a[mid] > val)u pper
= mid - 1;
else
lower = mid + 1;
}

if (found == -1)
printf("Element not
found");
getch();
5
}

5
OUTPUT:

Enter array size : 9


Elements in Sorted Order
0 2 4 6 8 10 12 14 16
Enter element to locate :
12 Located at position 6

Enter array size : 10


Elements in Sorted Order
0 2 4 6 8 10 12 14 16 18
Enter element to locate : 13
Element not found

RESULT:

5
Thus an element is located quickly using binary search method.

5
Ex. No. 13a Quick Sort
Date:

AIM:
To sort an array of N numbers using Quick sort.

ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements A
4. Select an pivot element X from Ai
5. Divide the array into 3 sequences: elements < x, x, elements > x
6. Recursively quick sort both sets (Ai<x and Ai>x)
7. Stop

5
PROGRAM:

/* Quick Sort */

#include <stdio.h> #include


<conio.h>

void qsort(int arr[20], int fst, int last);main()


{
int arr[30]; int
i, size;
printf("Enter total no. of the elements : ");
scanf("%d", &size);
printf("Enter total %d elements : \n", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
qsort(arr,0,size-1);
printf("\n Quick sorted elements \n");f
or(i=0; i<size; i++)
printf("%d\t", arr[i]); getch();
}

void qsort(int arr[20], int fst, int last)


{
int i, j, pivot, tmp;if(fst
< last)
{
pivot = fst;i
= fst;
j = last; while(i
< j)
{
while(arr[i] <=arr[pivot] &&
i<last) i++; while(arr[j] >
arr[pivot]) j--;
if(i <j )
{
tmp = arr[i]; arr[i]
= arr[j];a rr[j] =
tmp;
}
}
tmp = arr[pivot]; arr[pivot]
= arr[j]; arr[j] = tmp;
qsort(arr, fst, j-1);q
sort(arr, j+1, last);
5
}
}

OUTPUT:

Enter total no. of the nter total


elements : 8E 8 elements :
1
2
7
-1
0
4
-2
3

Quick sorted elements


-2 -1 0 1 2 3 4 7

RESULT:
6
Thus an array was sorted using quick sort's divide and conquer method.

6
Ex. No. 13b Merge
SortDate:

AIM:
To sort an array of N numbers using Merge sort.

ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop

6
PROGRAM:
#include <stdio.h>
#include <conio.h>

void merge(int [],int ,int ,int ); void


part(int [],int ,int );
int size;

main()
{
int i, arr[30];
printf("Enter total no. of elements : ");s
canf("%d", &size);
printf("Enter array elements :
");for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");f
or(i=0; i<size; i++)
printf("%d ",arr[i]); getch();
}

void part(int arr[], int min, int max)


{
int i, mid; if(min
< max)
{
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid+1, max);
merge(arr, min, mid, max);
}
if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
for(i=min; i<=max; i++)
printf("%d ", arr[i]);
}
}

void merge(int arr[],int min,int mid,int max)


{
int tmp[30]; int
i, j, k, m; j =
min;
m = mid + 1;
6
for(i=min; j<=mid && m<=max; i++)
{
if(arr[j] <= arr[m])
{
tmp[i] = arr[j]; j++;
}
else
{
tmp[i] = ++;
arr[m];m
}
}
if(j > mid)
{
for(k=m; k<=max; k++)
{
tmp[i] = arr[k];i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i] = arr[k];i++;
}
}
for(k=min; k<=max; k++) arr[k]
= tmp[k];
}

OUTPUT:

Enter total no. of elements : 8


Enter array elements : 24 13 26 1 2 27 38 15

Half sorted list : 1 13 24


26 Half sorted list : 2 15
27 38
Merge sorted list : 1 2 13 15 24 26 27 38

6
RESULT:
Thus array elements was sorted using merge sort's divide and conquer method.

6
Ex. No. 13c Insertion Sort
Date:

AIM:
To sort an array of N numbers using Insertion sort.

ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Sort the elements using insertion sort
In pass p, move the element in position p left until its correct place is
found among the first p + 1 elements.
Element at position p is saved in temp, and all larger elements
(prior toposition p) are moved one spot to the right. Then temp is
placed in thecorrect spot.
5. Stop

PROGRAM:

/* Insertion
Sort */m ain()
{
int i, j, k, n, temp, a[20], p=0;

printf("Enter total elements: ");


scanf("%d",&n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);

for(i=1; i<n; i++)


{
temp = a[i];j = i
- 1;
while((temp<a[j]) && (j>=0))
{
a[j+1] = a[j];j
= j - 1;
}
a[j+1] = temp;

p++;
printf("\n After Pass %d: ", p);f
6
or(k=0; k<n; k++)
printf(" %d", a[k]);
}
printf("\n Sorted List : "); for(i=0; i<n; i++)
printf(" %d", a[i]);
}

OUTPUT:

Enter total elements: 6 Enter array


elements: 34 8 64 51 32 21
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64

RESULT:
Thus array elements was sorted using insertion sort.

6
Ex. No. 14 Open Addressing Hashing Technique
Date:

AIM:
To implement hash table using a C program.

ALGORITHM:
1. Create a structure, data (hash table item) with key and value as data.
2. Now create an array of structure, data of some certain size (10, in this case).
But, the size of array must be immediately updated to a prime number just
greater than initial array capacity (i.e 10, in this case).
3. A menu is displayed on the screen.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define MAX ain()
10m
{
int a[MAX], num, key, i;
char ans;
int create(int);
void linearprobing(int[], int, int);
v oid display(int[]);
printf("\nCollision handling by linear probing\n\n"); for(i=0; i<MAX; i++)
a[i] = -1;
do
{
printf("\n Enter number:");
scanf("%d", &num);
key = create(num);
linearprobing(a, key, num);
printf("\nwish to continue?(y/n):"); ans =
getch();

6
} while( ans == 'y');
display(a);
}

int create(int num)


{
int key;
key = num % 10;
return key;
}

void linearprobing(int a[MAX], int key, int num)

{
int flag, i, count =
0;v oid display(int
a[]);flag = 0;
if(a[key] == -1)
a[key] = num;
else
{
i=0;
while(i < MAX)
{
if(a[i] != -
1) count+
+; i++;
}
if(count == MAX)
{
printf("hash table is full");
display(a); getch();
exit(1);
}
for(i=key+1; i<MAX; i++)
if(a[i] == - 1)
{
a[i] = num;
flag = 1;
break;
}
for(i=0; i<key && flag==0; i++ )i f(a[i] ==
-1)
{
a[i] = num;
flag = 1;
break;
6
}
}

void display(int a[MAX])


{
int i;
printf("\n Hash table is:");
for(i=0; i<MAX; i++)
printf("\n %d\t\t%d",i,a[i]);
}
OUTPUT:

Collision handling by linear probingEnter


number:1

wish to continue?(y/n):
Enter number:26
wish to continue?(y/n):
Enter number:62
wish to continue?(y/n):
Enter number:93
wish to continue?(y/n):
Enter number:84 wish to continue?(y/n):
Enter number:15
wish to continue?
(y/n):
Enter number:76
wish to continue?
(y/n):
Enter number:98
wish to continue?
(y/n):
Enter number:26
wish to continue?
(y/n):
Enter number:199
wish to continue?
(y/n):
Enter number:1234
wish to continue?(y/n):
Enter number:5678
hash table is
full Hash
table is:
0 1234
1 1
2 62
6
3 93
4 84
5 15
6 26
7 76
8 98
9 199

RESULT:
Thus hashing has been performed successfully.

You might also like