Sei sulla pagina 1di 52

EC8381 FUNDAMENTALS OF DATA STRUCTURES IN C LABORATORY

LAB MANUAL

1. Basic C Programs – looping, data manipulations, arrays

1. A. SUM OF N NUMBERS
AIM:
To write a c program for sum of N numbers
ALGORITHM:
1. Read the value of n.
2. Declare a variable i=1,sum=0.
3. Iteration for i=1 to n
Sum=sum+i.
4. Print sum
5. Stop.
#include<stdio.h>
int main()
{
int n, i, Sum = 0;

printf("\nPlease Enter any Integer Value\n");


scanf("%d", &n);

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


{
Sum = Sum + i;
}

printf("Sum of Natural Numbers = %d", Sum);


getch();
return 0;
}
OUTPUT:
Enter any integer value 5
Sum of natural numbers 15
RESULT:
Thus the c program for sum of N numbers was executed successfully.

1.B CALCULATOR
AIM:
To write a c program for designing a calculator
ALGORITHM:
1: Start the program
2: Read the two variable a and b
3: Display menu
4: Enter the option code
5: Evaluate option code with case statements
Step 5.1: case + r = a+b, print r. goto step 6
Step 5.2: case - r = a-b , print r. goto step 6
Step 5.3: case * r=a*b, print r. goto step 6
Step 5.4: case / r=a/b, print r. goto step 6
Step 6: Stop the program
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int a,b,c;
float r;
char c1;
clrscr();
printf("Enter the First Number : ");
scanf("%d",&a);
printf("\nEnter the Second Number : ");
scanf("%d",&b);
do
{
printf("\nWhich operations you want to perform (+,-,*,/,s)\n");
c=getch();
switch(c)
{
case '+':
r = a+b;
break;
case '-':
r = a-b;
break;
case '*':
r = a*b;
break;
case '/':
r = a/(float)b;
break;
case 's':
r = a*a;
break;
} // switch
if(c==' ')
printf("\nResult = %f\n",r);
else
printf("\nResult = %.f\n",r);
printf("\ndo you want continue (y/n) :");
c1 = getch();
} while (c1=='y' || c1=='Y');
}
RESULT:
Thus the c program for designing a calculator was executed successfully.
1.C. MATRIX ADDITION
AIM:
To write a c program for matrix addition
ALGORITHM:
1: Start the program
2: Read the number of rows and columns of two matrix.
3: c[i][j]=a[i][j] + b[i][j]
4: Stop the program
PROGRAM
#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],i,j,m,n;
clrscr();
printf("How many rows and columns?");
scanf("%d%d",&m,&n);
printf("\nEnter first matrix:\n");

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

printf("\nEnter second matrix:\n");

for(i=0;i<m;++i)
for(j=0;j<n;++j)
scanf("%d",&b[i][j]);

printf("\nMatrix after addition:\n");

for(i=0;i<m;++i)
{
for(j=0;j<n;++j)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d ",c[i][j]);
}

printf("\n");
}
getch();
return 0;
}
RESULT:
Thus the c program for matrix addition using array was executed successfully.

2. STRING FUNCTION
AIM:
To write a c program for string function implementation.

ALGORITHM:
1. Start
2. Declare variables
3. Read the text.
Display the menu options
Strlen,strcpy,strrev
4. Print the output
5. Stop the program.

PROGRAM

#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
char a[20],b[20],c[20];
int l;
clrscr();
printf("Enter the First String");
scanf("%s",&a);
printf("Enter the Second String");
scanf("%s",&b);
strcat(a,b);
printf("\nConcatenation of String a and b is:%s",a);
l=strlen(a);
printf("\nLength of String is %d",l);
strcpy(c,a);
printf("\nthe Copied String is %s",c);
strrev(a);
printf("\nreverse of String is %s",a);

getch();
}

OUTPUT:
Enter the first string
Data
Enter the second string
Structure
Concatenation of String a and b is Datastructure
Length of String is 13
The Copied String is Datastructure
Reverse of String is erutcurtsatad

RESULT:
Thus the c program for string function implementation was executed successfully.

3. PROGRAMS USING STRUCTURES AND POINTERS


AIM

To write a C Program to Generate salary slip of employees using structures and pointers.
ALGORITHM

1. Start
2. Declare variables
3. Read the number of employees .
4. Read allowances, deductions and basic for each employee.
5. Calculate net pay= (basic+ allowances)-deductions
6. Display the output of the Pay slip calculations for each employee.
7. Stop

PROGRAM
#include<stdio.h>
#include<conio.h>
#include "stdlib.h"
struct emp
{
int empno ;
char name[10],
answer ;
int bpay, allow, ded, npay ;
struct emp *next;
} ;
void main()
{
int i,n=0;
int more_data = 1;
struct emp e *current_ptr, *head_ptr; clrscr() ;
head_ptr = (struct emp *) malloc (sizeof(struct emp));
current_ptr = head_ptr;
while (more_data)
{
{
printf("\nEnter the employee number : ") ;
scanf("%d", & current_ptr->empno) ;
printf("\nEnter the name : ") ;
scanf("%s",& current_ptr->name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", & current_ptr ->bpay, & current_ptr ->allow, & current_ptr ->ded) ;
current_ptr->npay = current_ptr-> bpay + current_ptr->allow - current_ptr->ded ; n++;
printf("Would you like to add another employee? (y/n): ");
scanf("%s", answer);
if (answer!= 'Y')
{
current_ptr->next = (struct eme *) NULL;
more_data = 0;
}
else
{
current_ptr->next = (struct emp *) malloc (sizeof(struct emp));
current_ptr = current_ptr->next;
}
}
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
current_ptr = head_ptr;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", current_ptr->empno, current_ptr->name,
current_ptr->bpay, current_ptr->allow, current_ptr->ded,
current_ptr->npay) ;
current_ptr=current_ptr->next;
}
getch() ;
}
OUTPUT
Enter the number of
employees : 2 Enter the
employee number : 101 Enter
the name : Arun
Enter the basic pay, allowances & deductions : 5000 1000 250
Enter the employee number : 102 Enter the name : Babu
Enter the basic pay, allowances & deductions : 7000 1500 750
Emp.No. Name Bpay Allow Ded Npay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750

RESULT

Thus a C Program Salary slip of employees was executed and the output was obtained.

4. PROGRAMS INVOLVING DYNAMIC MEMORY ALLOCATIONS


AIM:
Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using malloc() function.
ALGORITHM:
1. Start the program.
2. Get the number of elements
3. Allocate the memory for the elements using malloc() function.
4. Stop the program.
PROGRAM:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

RESULT

Thus a C Program to find sum of n numbers using dynamic memory allocation was
executed and the output was obtained.

5. ARRAY IMPLEMENTATION OF STACKS AND QUEUES

5.a. Stack Array


AIM:
To write a C program for Array implementation of stacks
ALGORITHM:
1. Start the program
2. Inserting value into the stack

 Step 1: Check whether stack is FULL. (top == 4)


 Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and
terminate the function.
 Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack[top] to
value (stack[top] = value).

3. Delete a value from the Stack

 Step 1: Check whether stack is EMPTY. (top == -1)


 Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and
terminate the function.
 Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top-
-).

4. Displays the elements of a Stack

 Step 1: Check whether stack is EMPTY. (top == -1)


 Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
 Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top.
Display stack[i] value and decrement i value by one (i--).
 Step 3: Repeat above step until i value becomes '0'.

5. Stop the program

PROGRAM:

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

void push();
void pop();
void display();

int top; int a[5];

void main()
{
int choice; char ch; top=-1; clrscr();
do
{
printf("\n\t 1. PUSH");
printf("\n\t 2. POP");
printf("\n\t 3. DISPLAY");
printf("\n\t 4. EXIT"); printf("\nEnter your choice"); scanf("%d",&choice); switch(choice)
{
case 1: push(); break; case 2: pop(); break;
case 3: display();
break; case 4: exit(0); default:
printf("\nBAD CHOICE");
}
printf("\ndo you want to continue y/n");
ch=getche();
}
while(ch=='y');
}

void push()
{
int item; if(top==4)
printf("STACK IS FULL");
else
{
printf("Enter the item to be inserted");
scanf("%d",&item);
top=top+1; a[top]=item;
//top=tope;
}
}
void pop()
{
int item; if(top==-1)
printf("STACK IS EMPTY");
else
{
item=a[top]; top=top-1;
printf("%d is deleted",item);
//top=tope;
}
}
void display()
{
int i; for(i=top;i>=0;i--)
printf("\n%d",a[i]);
}
OUTPUT:

RESULT:
Thus the C program for Array implementation of stacks was executed successfully.

5.b. queue array


AIM:
To write a C program for Array implementation of queue.
ALGORITHM:
1. Start the program
2. Inserting value into the queue

Step 1: Check whether queue is FULL. (rear == SIZE-1)

Step 2: If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and
terminate the function.

Step 3: If it is NOT FULL, then increment rear value by one (rear++) and
set queue[rear] = value.

3. Deleting a value from the Queue

Step 1: Check whether queue is EMPTY. (front == rear)

Step 2: If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not


possible!!!" and terminate the function.

Step 3: If it is NOT EMPTY, then increment the front value by one (front ++). Then
display queue[front] as deleted element. Then check whether both front and rear are equal
(front == rear), if it TRUE, then set both front and rear to '-1' (front = rear = -1).
4. Displays the elements of a Queue

Step 1: Check whether queue is EMPTY. (front == rear)

Step 2: If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.

Step 3: If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front+1'.

Step 3: Display 'queue[i]' value and increment 'i' value by one (i++). Repeat the same
until 'i' value is equal to rear (i <= rear)

5. Stop the program

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
void insert();
void delet();
void display();
int front,rear; int q[5];
void main()
{
int choice; char ch; front=-1; rear=-1; clrscr(); do
{
printf("\n\t 1. INSERT");
printf("\n\t 2. DELETE");
printf("\n\t 3. DISPLAY");
printf("\n\t 4. EXIT"); printf("\nEnter your choice"); scanf("%d",&choice); switch(choice)
{
case 1: insert(); break; case 2: delet(); break;
case 3: display(); break; case 4: exit(0); default:
printf("\nBAD CHOICE");
}
printf("\ndo you want to continue y/n"); ch=getche();
}
while(ch=='y'||'Y');
}
void insert()
{
int item; if(((front==1)&&(rear==5))||(front==rear+1))
{
printf("QUEUE IS FULL");
}
else
{
printf("Enter the element"); scanf("%d",&item); if(front==-1)
{
front=1; rear=1;
}
else if(rear==5)
{ rear=0;
}
else{
rear=rear+1;
}
q[rear]=item;
}
}
void delet()
{
int item; if(front==-1)
{
printf("QUEUE IS EMPTY");
}
else
{
item=q[front]; if(front==rear)
{
front=-1; rear=-1;
}
else if(front==5)
{
front=0;
}
else
front=front+1;
printf("%d is deleted",item);
}
}
void display()
{
int i; if(front==-1)
printf("QUEUE IS EMPTY");
else
{
for(i=front;i<=rear;i++)
{
printf("\n%d",q[i]);
}
}
}
OUTPUT:

RESULT:
Thus the C program for Array implementation of queue was executed successfully.

6. LINKED LIST IMPLEMENTATION OF STACKS AND QUEUES


6.a. stack linked list
AIM:
To write a C program for Linked list implementation of stacks
ALGORITHM:
1. Start the program
2. Inserting an element into the Stack
Step 1: Create a newNode with given value.
Step 2: Check whether stack is Empty (top == NULL)
Step 3: If it is Empty, then set newNode → next = NULL.
Step 4: If it is Not Empty, then set newNode → next = top.
Step 5: Finally, set top = newNode.
3. Deleting an Element from a Stack
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and
terminate the function
Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4: Then set 'top = top → next'.
Step 7: Finally, delete 'temp' (free(temp)).
4. Displaying stack of elements
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same
until temp reaches to the first node in the stack (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'.
5. Stop the program

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
int data,ch,c;
struct node
{
int element;
struct node*next;
}*s=NULL;
void push(void);
void pop();
void display(void);
void main()
{
int ch,c,i;
printf("\n\t\t IMPLEMENTATION OF STACK USING LINKED LIST\n");
while(1)
{
printf("\n1.Push");
printf("\n2.Pop");
printf("\n3.Display");
printf("\n4.Exit");
printf("\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\nWrong choice");
break;
}
}
}
void push(void)
{
struct node*temp;
temp=malloc(sizeof(struct node));
printf("\nEnter the element:");
scanf("%d",&data);
temp->element=data;
temp->next=s;
s=temp;
}
void display(void)
{
struct node*P;
P=s;
if(s==NULL)
{
printf("\nStack is empty");
}
while(P!=NULL)
{
printf("\t%d",P->element);
P=P->next;
}
}
void pop(void)

{
struct node*temp,*next,*p;
if(s==NULL)
{
printf("\nStack is empty");
return;
}
temp=s;
printf("\nThe popped element is %d",temp->element);
s=temp->next;
free(temp);
}
OUTPUT:
RESULT:
Thus the C program for Linked list implementation of stacks was executed successfully.

6.b. QUEUE USING LINKED LIST


AIM:
To write a C program for Linked list implementation of stacks
ALGORITHM:
1. Start the program

2. Inserting an element into the Queue

Step 1: Create a newNode with given value and set 'newNode →


next' to NULL.
Step 2: Check whether queue is Empty (rear == NULL)
Step 3: If it is Empty then, set front = newNode and rear = newNode.
Step 4: If it is Not Empty then, set rear → next = newNode and rear =
newNode.

3. Deleting an Element from Queue

Step 1: Check whether queue is Empty (front == NULL).


Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not
possible!!!" and terminate from the function
Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to
'front'.
Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)).

4. Displaying the elements of Queue


Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the
function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize
with front.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the
same until 'temp' reaches to 'rear' (temp → next != NULL).
Step 5: Finally! Display 'temp → data ---> NULL'.
5. Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;

void insert(int);
void delete();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}
OUTPUT

RESULT:
Thus the C program for Linked list implementation of stacks was executed
successfully.
7. CONVERT INFIX TO POSTFIX EXPRESSION

AIM:
To write a „C‟ program to implement stack and use it to convert infix to postfix
expression.
ALGORITHM:-
1. Start the program
2. Scan the Infix string from left to right.
3. Initialise an empty stack.
4. If the scannned character is an operand, add it to the Postfix string. If the scanned
character is an operator and if the stack is empty Push the character to stack.
 If the scanned character is an Operand and the stack is not empty, compare the
precedence of the character with the element on top of the stack (topStack). If
topStack has higher precedence over the scanned character Pop the stack else
Push the scanned character to stack. Repeat this step as long as stack is not empty
and topStack has precedence over the character.
Repeat this step till all the characters are scanned.
5. (After all characters are scanned, we have to add any character that the stack may have
to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the
stack. Repeat this step as long as stack is not empty.
6. Return the Postfix string.
7. Terminate the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
char stack[100];
int top=0;
char exp[100];
struct table
{
char s[2];
int isp;
int icp;
}pr[7];
int isp(char c)
{
int i;
for(i=0;i<=6;i++)
if(pr[i].s[0]==c)
return(pr[i].isp);
return 0;
}
int icp(char c)
{
int i;
for(i=0;i<=6;i++)
if(pr[i].s[0]==c)
return(pr[i].icp);
return 0;
}
void main()
{
int i;
clrscr();
strcpy(pr[0].s,"^");
pr[0].isp=3;
pr[0].icp=4;

strcpy(pr[1].s,"*");
pr[1].isp=2;
pr[1].icp=2;

strcpy(pr[2].s,"/");
pr[2].isp=2;
pr[2].icp=2;
strcpy(pr[3].s,"+");
pr[3].isp=1;
pr[3].icp=1;

strcpy(pr[4].s,"-");
pr[4].isp=1;
pr[4].icp=1;

strcpy(pr[5].s,"(");
pr[5].isp=0;
pr[5].icp=4;
strcpy(pr[6].s,"=");
pr[6].isp=-1;
pr[6].icp=0;

clrscr();
stack[top]='=';
printf("enter the infix expression");
gets(exp);
i=0;
printf("the postfix expression is ")
while(i<strlen(exp))
{
if(isalpha(exp[i])==0)
{

if(exp[i]==')')
{
while(stack[top]!='(')
{
printf("%c",stack[top]);
top--;
}
top--;
}
else
{
while(isp(stack[top])>=icp(exp[i]))
{
printf("%c",stack[top]);
top--;
}
top++;
stack[top]=exp[i];
}
}
else
printf("%c",exp[i]);
i++;
}
while(top>0)
{
printf("%c",stack[top]);
top--;
}
getch();
}
OUTPUT:
enter the infix expression a*(s+d/f)+c
the postfix expression is asdf/+*c+
RESULT:
Thus the C program for convert infix expression to postfix expression was written,
executed and the output was verified successfully.

8. IMPLEMENTATION OF TREES, TREE TRAVERSALS

AIM:
To implement tree traversals using linked list.
ALGORITHM:-
Step 1: Start the process.
Step 2: Initialize and declare variables.
Step 3: Enter the choice. Inorder / Preorder / Postorder.
Step 4: If choice is Inorder then
-Traverse the left subtree in inorder.
-Process the root node.
-Traverse the right subtree in inorder.
Step 5: If choice is Preorder then
-Process the root node.
-Traverse the left subtree in preorder.
-Traverse the right subtree in preorder.
Step 6: If choice is postorder then
-Traverse the left subtree in postorder.
-Traverse the right subtree in postorder.
-Process the root node.
Step7: Print the Inorder / Preorder / Postorder traversal.
Step 8: Stop the process.

PROGRAM:

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

struct node
{
int a;
struct node *left;
struct node *right;
};

void generate(struct node **, int);


void infix(struct node *);
void postfix(struct node *);
void prefix(struct node *);
void delete(struct node **);

int main()
{
struct node *head = NULL;
int choice = 0, num, flag = 0, key;

do
{
printf("\nEnter your choice:\n1. Insert\n2. Traverse via infix\n3.Traverse via
prefix\n4. Traverse via postfix\n5. Exit\nChoice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter element to insert: ");
scanf("%d", &num);
generate(&head, num);
break;
case 2:
infix(head);
break;
case 3:
prefix(head);
break;
case 4:
postfix(head);
break;
case 5:
delete(&head);
printf("Memory Cleared\nPROGRAM TERMINATED\n");
break;
default: printf("Not a valid input, try again\n");
}
} while (choice != 5);
return 0;
}

void generate(struct node **head, int num)


{
struct node *temp = *head, *prev = *head;

if (*head == NULL)
{
*head = (struct node *)malloc(sizeof(struct node));
(*head)->a = num;
(*head)->left = (*head)->right = NULL;
}
else
{
while (temp != NULL)
{
if (num > temp->a)
{
prev = temp;
temp = temp->right;
}
else
{
prev = temp;
temp = temp->left;
}
}
temp = (struct node *)malloc(sizeof(struct node));
temp->a = num;
if (num >= prev->a)
{
prev->right = temp;
}
else
{
prev->left = temp;
}
}
}

void infix(struct node *head)


{
if (head)
{
infix(head->left);
printf("%d ", head->a);
infix(head->right);
}
}

void prefix(struct node *head)


{
if (head)
{
printf("%d ", head->a);
prefix(head->left);
prefix(head->right);
}
}

void postfix(struct node *head)


{
if (head)
{
postfix(head->left);
postfix(head->right);
printf("%d ", head->a);
}
}

void delete(struct node **head)


{
if (*head != NULL)
{
if ((*head)->left)
{
delete(&(*head)->left);
}
if ((*head)->right)
{
delete(&(*head)->right);
}
free(*head);
}
}
OUTPUT

Enter your choice:


1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 1
Enter element to insert: 5

Enter your choice:


1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 1
Enter element to insert: 3

Enter your choice:


1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 1
Enter element to insert: 4

Enter your choice:


1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 1
Enter element to insert: 6

Enter your choice:


1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 1
Enter element to insert: 2

Enter your choice:


1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 2
2 3 4 5 6
Enter your choice:
1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 3
5 3 2 4 6
Enter your choice:
1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 4
2 4 3 6 5
Enter your choice:
1. Insert
2. Traverse via infix
3. Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 5
Memory Cleared
PROGRAM TERMINATED

RESULT:
Thus the program to implement tree traversals using linked list.
9. IMPLEMENT BINARY SEARCH TREE

AIM:-
To write a „C‟ program to implement binary search tree.
ALGORITHM:-

Step 1: Start the process.


Step 2: Initialize and declare variables.
Step 3: Construct the Tree
Step 4: Data values are given which we call a key and a binary search tree
Step 5: To search for the key in the given binary search tree, start with the root node and
Compare the key with the data value of the root node. If they match, return the
root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by using
the left subtree.
Step 7: Otherwise, repeat the same process with the right subtree until either a match is
found or the subtree under consideration becomes an empty tree.
Step 8: Terminate the program

PROGRAM

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

struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
}*t,*temp;

int element;
void inorder(struct tree *);
void preorder(struct tree *);
void postorder(struct tree *);
struct tree * create(struct tree *, int);
struct tree * find(struct tree *, int);
struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *);
struct tree * findmax(struct tree *);
void main()
{
int ch;

do
{
printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");
printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n");
printf("\nEnter ur choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the data:");
scanf("%d",&element);
t=create(t,element);
inorder(t);
break;
case 2:
printf("\nEnter the data:");
scanf("%d",&element);
t=insert(t,element);
inorder(t);
break;
case 3:
printf("\nEnter the data:");
scanf("%d",&element);
t=del(t,element);
inorder(t);
break;
case 4:
printf("\nEnter the data:");
scanf("%d",&element);
temp=find(t,element);
if(temp->data==element)
printf("\nElement %d is at %d",element,temp);
else
printf("\nElement is not found");
break;
case 5:
temp=findmin(t);
printf("\nMax element=%d",temp->data);
break;
case 6:
temp=findmax(t);
printf("\nMax element=%d",temp->data);
break;
case 7:
inorder(t);
break;
case 8:
preorder(t);
break;
case 9:
postorder(t);
break;
case 10:
exit(0);
}
}while(ch<=10);
}

struct tree * create(struct tree *t, int element)


{
t=(struct tree *)malloc(sizeof(struct tree));
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}

struct tree * find(struct tree *t, int element)


{
if(t==NULL)
return NULL;
if(element<t->data)
return(find(t->lchild,element));
else
if(element>t->data)
return(find(t->rchild,element));
else
return t;
}

struct tree *findmin(struct tree *t)


{
if(t==NULL)
return NULL;
else
if(t->lchild==NULL)
return t;
else
return(findmin(t->lchild));
}

struct tree *findmax(struct tree *t)


{
if(t!=NULL)
{
while(t->rchild!=NULL)
t=t->rchild;
}
return t;
}

struct tree *insert(struct tree *t,int element)


{
if(t==NULL)
{
t=(struct tree *)malloc(sizeof(struct tree));
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}
else
{
if(element<t->data)
{
t->lchild=insert(t->lchild,element);
}
else
if(element>t->data)
{
t->rchild=insert(t->rchild,element);
}
else
if(element==t->data)
{
printf("element already present\n");
}
return t;
}
}

struct tree * del(struct tree *t, int element)


{
if(t==NULL)
printf("element not found\n");
else
if(element<t->data)
t->lchild=del(t->lchild,element);
else
if(element>t->data)
t->rchild=del(t->rchild,element);
else
if(t->lchild&&t->rchild)
{
temp=findmin(t->rchild);
t->data=temp->data;
t->rchild=del(t->rchild,t->data);
}
else
{
temp=t;
if(t->lchild==NULL)
t=t->rchild;
else
if(t->rchild==NULL)
t=t->lchild;
free(temp);
}
return t;
}

void inorder(struct tree *t)


{
if(t==NULL)
return;
else
{
inorder(t->lchild);
printf("\t%d",t->data);
inorder(t->rchild);
}
}

void preorder(struct tree *t)


{
if(t==NULL)
return;
else
{
printf("\t%d",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void postorder(struct tree *t)
{
if(t==NULL)
return;
else
{
postorder(t->lchild);
postorder(t->rchild);
printf("\t%d",t->data);
}
}

OUTPUT:

BINARY SEARCH TREE


****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :1

Enter the data:10


10
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:20


10 20
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:30


10 20 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:25


10 20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :4

Enter the data:25

Element 25 is at 2216
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :5

Max element=10
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :6

Max element=30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :7
10 20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :8
10 20 30 25
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :9
25 30 20 10
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :3

Enter the data:10


20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :10

RESULT:
Thus the c program for implementation of Binary Search trees was executed successfully.
10. IMPLEMENTATION OF LINEAR SEARCH AND BINARY SEARCH

10. A.IMPLEMENT LINEAR SEARCH

AIM
Write a C Program for Linear search using array
ALGORITHM
Linear Search (Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

PROGRAM
#include <stdio.h>
void main()
{
int array[10];
int i, num, keynum, found = 0;

printf("Enter the value of num \n");


scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%dn", array[i]);
}
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Linear search begins */
for (i = 0; i < num ; i++)
{
if (keynum == array[i] )
{
found = 1;
break;
}
}
if (found == 1)
printf("Element is present in the array\n");
else
printf("Element is not present in the array\n");
}

OUTPUT:

Enter the value of num


5
Enter the elements one by one
456
78
90
40
100
Input array is
456
78
90
40
100
Enter the element to be searched
70
Element is not present in the array

RESULT:
Thus the c program for implementation of Linear search was executed successfully.

10. B.PROGRAM TO SEARCH AN ELEMENT USING BINARY SEARCH

AIM
Write a C Program for Binary search using Recursion
ALGORITHM:
Step-1 Start the program
Step-2 Declare an array a[50], i, n and loc as „int‟ data type
Step-3 Declare bin( ) function as „int‟ data type
Step-4 Enter the size of array
Step-5 for i=0 to less than „n‟
Step-5.1 Read and placed in a[i]
Step-6 for i=0 to less than „n‟
Step-6.1 print „a(i)
Step-7 Enter element to be searched
Step-8 Assign loc=bin(a,o,n)
Step-9 Check if (loc==0)
Step-9.1 Print “unsuccessful search %d not found”
Step-10 else
Step-10.1 Print “Successful search found”
Step-11 Stop the program
Recursive Function
Step-1 Global declaration of an array b(50) low and high
Step-2 Declare mid as „static int‟ of local declaration and „i‟ as„int‟ data type
Step-3 mid=(low+high)
Step-3.1 check if (key<b(mid))
Step-3.2 high = mid-1
Step-3.2.1 bin(b, low, high)
Step-3.3 else if (key==b(mid))
Step-3.3.1 low = mid+1
Step-3.3.2 bin (b, low, high)
Step-3.4 else if (key==b(mid)))
Step-3.4.1 return(mid+1)
Step-4 else
Step-4.1 return(0)
Step-5 Stop the program.

PROGRAM
#include <stdio.h>
void binary_search();
int a[50], n, item, loc, beg, mid, end, i;
void main()
{
printf("\nEnter size of an array: ");
scanf("%d", &n);
printf("\nEnter elements of an array in sorted form:\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]); .
printf("\nEnter ITEM to be searched: ");
scanf("%d", &item);
binary_search();
getch();
}
void binary_search()
{
beg = 0;
end = n-1;
mid = (beg + end) / 2;
while ((beg<=end) && (a[mid]!=item))
{
if (item < a[mid])
end = mid - 1;
else
beg = mid + 1;
mid = (beg + end) / 2;
}
if (a[mid] == item)
printf("\n\nITEM found at location %d", mid+1);
else
printf("\n\nITEM doesn't exist");
}
OUTPUT:
Enter size of an array: 6
Enter elements of an array in sorted form:
10 20 30 40 50 60
Enter ITEM to be searched: 30
ITEM found at location 3
RESULT:
Thus the c program for implementation of binary search was executed successfully.

11. IMPLEMENTATION INSERTION SORT, BUBBLE SORT, QUICK SORT AND


MERGE SORT
11.a. BUBBLE SORT
Aim:
Write a c program for bubble sort
Algorithm:
1. Start.
2. Input the size of dimensional array(size=n).
3. Take the input elements to the initialized array.
4. Initialize i=0,j=i+1
5. When a[i]>a[i+1], go to step 6 else to step 8.
6. Swap elements
7. temp=a[i]
8. a[i]=a[j]
9. a[j]=temp
10. Increment i and j upto n-1,Go to step 5;
11. Display sorted array.
12. Stop.
Program: bubblesort.c
#include<stdio.h>
void main()
{
int n,i,j,a[10],b[10],temp;
clrscr();
for(i=0;i<10;i++)
{
//for removing junk values in the array //
a[i]=0;
b[i]=0;
}

printf("\nEnter no of elements\n");
scanf("%d",&n); //input for size of the array //
printf("\nEnter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]); // taking array elements //
for(i=0;i<n;i++)
{
b[i]=a[i]; //storing copy of array to an another array //
}
//Sorting array using BUBBLESORT method //
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("The given array of elements is \n");
for(i=0;i<n;i++)
{
printf("%d\t",b[i]); //prints the input array//
}
printf("\nThe sorted array of given array is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]); //prints the sorted array //
}
printf("\n");
getch();
}
Output:
Enter no of elements 5
Enter the elements 1 3 5 2 4
The given array of element is 1 3 5 2 4
The Sorted array of the given array is 1 2 3 4 5

Result:
Thus the program for bubble sort was executed successfully.

11.b. INSERTION SORT


Aim:
Write a c program for insertion sort
ALGORITHM:
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

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

void main( )

int

a[10],i,j,k,n;

clrscr( );

printf("How many elements you want to sort?\n");

scanf("%d",&n);
printf("\nEnter the Elements into an array:\n");

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

scanf("%d",&a[i]);

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

k=a[i];

for(j= i-1; j>=0 && k<a[j]; j--)

a[j+1]=a[j];

a[j+1]=k;

printf("\n\n Elements after sorting: \n");

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

printf("%d\n", a[i]);

getch( );

OUTPUT:

How many elements you want to sort ? : 6

Enter elements for an array : 78 23 45 8 32 36

After Sorting the elements are : 8 23 32 36 45 78

Result:
Thus the program for insertion sort was executed successfully.

11.c. QUICK SORT


AIM:
Write a program to implement Quick sort.
ALGORITHM:
1 Choose the highest index value has pivot
2 Take two variables to point left and right of the list excluding pivot
3 left points to the low index
4 right points to the high
5 while value at left is less than pivot move right
6 while value at right is greater than pivot move left
7 if both step 5 and step 6 does not match swap left and right
8 if left ≥ right, the point where they met is new pivot
PROGRAM:
#include<stdio.h>
void quicksort(int[ ],int,int);

void main( )

int low, high, pivot, t, n, i, j, a[10];

clrscr( );

printf("\nHow many elements you want to sort ? ");

scanf("%d",&n);

printf("\Enter elements for an array:");

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

scanf("%d",&a[i]);

low=0;

high=n-1;

quicksort(a,low,high);

printf("\After Sorting the elements are:");

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

printf("%d ",a[i]);

getch( );

void quicksort(int a[ ],int low,int high)

{
int pivot,t,i,j;

if(low<high)

pivot=a[low];

i=low+1;

j=high;

while(1)

{
while(pivot>a[i]&&i<=high)

i++;

while(pivot<a[j]&&j>=low)

j--;

if(i<j)

t=a[i];

a[i]=a[j];

a[j]=t;

else

break;

a[low]=a[j]; a[j]=pivot;

quicksort(a,low,j-1);

quicksort(a,j+1,high);
}

OUTPUT:

How many elements you want to sort ? : 6

Enter elements for an array : 78 23 45 8 32 36

After Sorting the elements are : 8 23 32 36 45 78


Result:
Thus the program for quick sort was executed successfully.

11.d. MERGE SORT


AIM:
Write a program to implement Merge sort.
ALGORITHM:

1.Start the program


2. if it is only one element in the list it is already sorted, return.
3. divide the list recursively into two halves until it can no more be divided.
4. merge the smaller lists into new list in sorted order.
5. Stop the program
PROGRAM:

#include<stdio.h>

void disp( );

void mergesort(int,int,int);

void msortdiv(int,int);

int a[50],n;

void main( )

int i;

clrscr( );

printf("\nEnter the n value:");

scanf("%d",&n);
printf("\nEnter elements for an array:");

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

scanf("%d",&a[i]);

printf("\nBefore Sorting the elements are:");

disp( );

msortdiv(0,n-1);

printf("\nAfter Sorting the elements are:");

disp( );

getch( );

void disp( )

int i; for(i=0;i<n;i++)

printf("%d ",a[i]);

}
void mergesort(int low,int mid,int high)

int t[50],i,j,k;

i=low;

j=mid+1;

k=low;

while((i<=mid) && (j<=high))

if(a[i]>=a[j])

t[k++]=a[j++];
else

t[k++]=a[i++];

while(i<=mid)

t[k++]=a[i++];

while(j<=high)

t[k++]=a[j++];

for(i=low;i<=high;i++)

a[i]=t[i];

void msortdiv(int low,int high)

int mid;

if(low!=high)

mid=((low+high)/2);

msortdiv(low,mid);

msortdiv(mid+1,high);

mergesort(low,mid,high);

OUTPUT:

How many elements you want to sort ? : 7

Enter elements for an array : 88 45 54 8 32 6 12


After Sorting the elements are : 6 8 12 32 45 54 88

Result:
Thus the program for merge sort was executed successfully.

Potrebbero piacerti anche