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

Data Structure Lab Manual

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

Data Structure Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

191CS31A DATA STRUCTURES IN C LABORATORY

S.NO LIST OF EXPERIMENT DATE PAGE SIGNATURE


NO

1 Basic C Programs – looping, data manipulations, arrays

2 Programs using strings – string function implementation

3 Programs using structures and pointers

4 Programs involving dynamic memory allocations

Array implementation of stacks and queues


5

6 Linked list implementation of stacks and queues

7 Application of Stacks and Queues

8 Implementation of Trees, Tree Traversals

9 Implementation of Binary Search trees

10 Implementation of Linear search and binary search

11 Implementation Insertion sort, Bubble sort, Quick sort


and Merge Sort

12 Implementation Hash functions, collision resolution technique

Ex.no: 1.a Basic C Programs – looping, data manipulations, arrays Date:


Aim:

To write check the number is prime or not using For loop..

Algorithm:

Step 1: Start
Step 2: Read number n
Step 3: Set f=0
Step 4: For i=2 to n-1
Step 5: If n mod 1=0 then
Step 6: Set f=1 and break
Step 7: Loop
Step 8: If f=0 then print 'The given number is prime'
Step 9:else print 'The given number is not prime'
Step 10: Stop

Program:

#include <stdio.h>
int main()
{
int tally; int number;
unsigned char
flag=0;

printf("Enter an integer number : ");


scanf("%d",&number);

for(tally=2; tally<(number/2); tally++)


{ if(number%tally ==0)
{ flag=1;
break;
}
}

if(flag==0)
printf("\n %d is a prime number.",number);
else
printf("\n %d is not a prime number.",number);
return 0;
}
OUTPUT:

Enter an integer number:117

117 is not a prime number.

Enter an integer number: 112

112 is not a prime number.

RESULT:

Thus the program was written and executed successfully.


Ex.no:1.b Program for Palindrome Using while loop Date:
Aim:

To write a program for print the numbers using while loop

Algorithm:

Step 1: Start the program

Step 2: while loop starts with a condition.

Step 3: First, the condition is evaluated

Step 4: the condition is true then the statements in the body of the while are executed, Step 5:
again the condition is checked if it is still true then once again statements in the body of the while
are executed

Step 6:End the program

Program:
#include <stdio.h>
int main()
{ int number, revNumber=0, rem=0,tempNumber;

printf("Enter an integer number: ");


scanf("%d", &number);

tempNumber=number;

while(tempNumber!=0)
{ rem=tempNumber%10;
revNumber=revNumber*10+rem
; tempNumber/=10;
}
/* checking if number is equal to reverse number */
if(revNumber==number)
printf("%d is a palindrome.", number);
else
printf("%d is not a palindrome.", number);

return 0;
}

OUTPUT

Enter an integer number: 12321

12321 is a palindrome.

Enter an integer number: 1234

1234 is not a palindrome.

RESULT:

Thus the program was written and executed successfully.


Ex.no:1.c Program Using do while loop Date:
Aim:

To write the program for print the numbers using do while loop

Algorithm:

Step 1:Start the program


Step 2: which tests the condition before the code within the block is

executed Step 3: the do-while loop is an exit-condition loop

Step 4:This means that the code must always be executed first and then the expression or
test condition is evaluated.

Step 5: If it is true, the code executes the body of the loop again.

Step 6: End the Program

Program
#include <stdio.h>

int main()

{
int j=0;

do

{ printf("Value of variable j is: %d\n", j); j+

+; }while (j<=3); return 0;

}
OUTPUT:

Value of variable j is : 0

Value of variable j is : 1

Value of variable j is : 2

Value of variable j is : 3
RESULT:

Thus the program was written and executed successfully.


Ex.no: 1.d Program using Data Manipulations Date:

Aim:
To write a program for Reversing the number using Data Manipulations.

Algorithm:

Step 1:Start the program step 2: Intilize reverse=0. step 3: Read


the digit step 4: Check whether digit>0 then go to step 5 else go
to step 9 step 5: reverse =reverse *10 step 6:
reverse=reverse+digit%10 step 7: digit =digit/10 step 8: Go to
step 4 step 9: Print reverse
step 10: Stop the program

Program

#include <stdio.h>

int main()
{ int n; int dig,
revNumber;

printf("\nEnter an integer number :");


scanf("%d",&n);

/*Reversing Number*/
revNumber=0;

while(n>0)
{ dig=n%10; /*get digit*/
revNumber=(revNumber*10)+dig;
n=n/10; }

printf("\nReverse Number is :
%d\n",revNumber); return 0;
}

OUTPUT:

Enter an integer number : 1234


Reverse Number is : 4321
RESULT:

Thus the program was written and executed successfully.


Ex.no:1.e Program to Calculate Sum & Average of an Array
Date:

Aim:

To write a program to calculate Sum and Average of an Array

Algorithm:

Step1: Create an array of integer of some certain maximum capacity (10, in this case). Step 2:
From users, take a number N as input, which will indicate the number of elements in the array
(N <= maximum capacity).
Step 3: Iterating through for loops (from [0 to N) ), take integers as input from user and
print them. These input are the elements of the array.
Step 4: Now, start summation by iterating through all the elements and adding positive and
negative number separately to print as well as combined to calculate average. Step 5: To
calculate average, the overall sum (sum of positive + negative integers) is divided by total
number of elements in the array.

Step 6: Print the average calculated.

Program:
#include <stdio.h>
#define MAXSIZE 10
void main()
{ int array[MAXSIZE];
int i, num, negative_sum = 0, positive_sum = 0;
float total = 0.0, average;
printf ("Enter the value of N \n");
scanf("%d", &num);

printf("Enter %d numbers (-ve, +ve and zero) \n", num);


for (i = 0; i < num; i++)
{ scanf("%d", &array[i]);
} printf("Input array elements
\n"); for (i = 0; i < num; i++)
{ printf("%+3d\n", array[i]);
}
/* Summation starts */
for (i = 0; i < num; i++)
{ if (array[i] < 0)
{ negative_sum = negative_sum + array[i];
} else if (array[i] >
0)
{ positive_sum = positive_sum + array[i];
} else if (array[i] ==
0)
{
;
} total = total +
array[i] ;

} average = total / num; printf("\n Sum of all negative


numbers = %d\n", negative_sum); printf("Sum of all positive
numbers = %d\n", positive_sum); printf("\n Average of all input
numbers = %.2f\n", average); }

OUTPUT
Enter the value of N
10
Enter 10 numbers (-ve, +ve and zero)
-8
9
-100
-80
90
45
-23
-1
0
16
Input array elements
-8
+9
-100
-80
+90
+45
-23
-1
+0
+16
Sum of all negative numbers = -212
Sum of all positive numbers = 160
Average of all input numbers = -5.20

RESULT:
Thus the program was written and executed successfully.
Ex.no:1.f Program to Find the Largest Two Numbers in a given Array
Date:

Aim:

To write a program to Find the Largest Two Numbers in a given Array


Algorithm:

Step1: Declare an array of some fixed size, say 4.


Step 2: Using for loop, define the elements of the array.
Step 3: Consider the first element of array to be the first largest number (store it in a
variable, largest1).
Step 4: Consider the second element of array to be the second largest number (store it in
a variable, largest2).
Step 5: Now interchange both if largest1 is smaller than largest2.
Step 6: Run a for loop from third element of the array till the last element of the array,
wherein each element will be compared to the largest1.
i) If the array element is greater than largest1, then largest1 is assigned the array element.
And the value of largest1 gets transferred to largest2.
ii) If the array element is smaller than largest1 and but greater than largest2, then only
largest2 is assigned the array element.
Step 7: Running loop till end, will give us the actual first largest and second largest number.
Step 8: Exit

Program
#include <stdio.h>
#define MAX 4

void main()
{ int array[MAX], i, largest1, largest2, temp;

printf("Enter %d integer numbers \n", MAX);


for (i = 0; i < MAX; i++)
{ scanf("%d", &array[i]);
}

printf("Input integer are \n");


for (i = 0; i < MAX; i++)
{ printf("%5d", array[i]);
}

printf("\n");
/* assume first element of array is the first larges t*/

largest1 = array[0];
/* assume first element of array is the second largest */

largest2 = array[1]; if
(largest1 < largest2)
{ temp = largest1;
largest1 =
largest2;
largest2 = temp;
}

for (i = 2; i < 4; i++)


{ if (array[i] >= largest1)
{ largest2 = largest1;
largest1 = array[i];
} else if (array[i] >
largest2)
{ largest2 = array[i];
}
} printf("n%d is the first largest \n", largest1); printf("%d is

the second largest \n", largest2); printf("\n Average of %d

and %d = %d \n", largest1, largest2,

(largest1 + largest2) / 2);

}
OUTPUT
Enter 4 integer numbers
80
23
79
58
Input integer are
80 23 79 58

80 is the first largest


79 is the second largest

Average of 80 and 79 = 79
RESULT:

Thus the program was written and executed successfully.


PROGRAMS USING STRINGS – STRING FUNCTION
IMPLEMENTATION

Ex.no:2.a Read & write Strings in C using Printf() and Scanf() functions
Date:

Aim:
To write a Program for Read & write Strings in C using Printf() and Scanf()

functions Algorithm:

Step 1: Start the program


Step 2: String Declaration
Step 3:Reading the input string and storing it in nickname
Step 4: Array name alone works as a base address of array
Step 5: we can use nickname instead of &nickname
Step 6:End the program

Program:
#include <stdio.h>
#include <string.h>
int main()
{ char nickname[20]; printf("Enter

your Nick name:"); scanf("%s",

nickname);

printf("%s",nickname);

return 0;
}
Output:

Enter your Nick name:Negan

Negan
RESULT:

Thus the program was written and executed successfully.


Ex.no:2.b String function in C – strnlen Date:

Aim:

To write a program for find length of the string using string function in c -
strnlen

Algorithm:
Step 1: Start the program
Step 2: String Declaration
Step3: Reading the input string
Step 4:Strnlen function used to finr the length of the function
Step 5:print the length of the String
Step 6: End the program

Program:

#include <stdio.h>

#include <string.h>

int main()

{ char str1[20] = "BeginnersBook"; printf("Length of string str1 when

maxlen is 30: %d", strnlen(str1, 30)); printf("Length of string str1 when

maxlen is 10: %d",

strnlen(str1, 10)); return 0;

}
OUTPUT:

Length of string str1 when maxlen is 30: 13


Length of string str1 when maxlen is 10: 10

RESULT:
Thus the program was written and executed successfully.
Ex.no:2.c String function in C – strcmp Date:

Aim:
To write a program to find the string using string function in C

Algorithm:

Step 1: Start the program


Step 2: String Declaration
Step3: Reading the input string
Step 4:It is comparing first 8 characters of s1 and s2
Step 5:After that to display the output
Step 6:End the Program

Program:

#include <stdio.h>

#include <string.h>

int main()

{ char s1[20] = "BeginnersBook"; char

s2[20] = "BeginnersBook.COM"; if

(strcmp(s1, s2) ==0)

printf("string 1 and string 2 are equal");


}else

{ printf("string 1 and 2 are

different");

return 0;

}
OUTPUT:
string 1 and 2 are different
Result: Thus the program was written and executed
successfully. Ex.no:2.d String function in C – strncat
Date:

Aim:
To write a program for concatenation of two string using string

function Algorithm:

Step 1:Start the program


Step 2: String Declaration
Step3: Reading the input string
Step 4: It concatenates n characters of str2 to string str1.
Step 5:A terminator char (‘\0’) will always be appended at the end of the concatenated
string. Step 6: End the program

Program:
#include <stdio.h>

#include <string.h>

int main()

{ char s1[10] = "Hello";

char s2[10] = "World";

strncat(s1,s2, 3); printf("Concatenation using

strncat: %s", s1); return 0;

}
OUTPUT:
Concatenation using strncat: HelloWorld
RESULT:

Thus the program was written and executed successfully.


Ex.no:2.e String function in C – strcpy Date:

Aim:

To write a program for Copying string using string function

Algorithm:
Step1: Start the program
Step 2:size_t is unassigned short and n is a number.
Step 3:Case1: If length of str2 > n then it just copies first n characters of str2 into str1. Step
4:Case2: If length of str2 < n then it copies all the characters of str2 into str1 Step 5:And
appends several terminator chars(‘\0’) to accumulate the length of str1 to make it n. Step 6:
End the program

Program:

#include <stdio.h>

#include <string.h>

int main()

{ char s1[30] = "string 1"; char s2[30] = "string 2 :

I’m gonna copied into s1";

/* this function has copied s2 into s1*/

strcpy(s1,s2); printf("String

s1 is: %s", s1); return 0;

}
OUTPUT:

String s1 is: string 2: I'm gonna copied into s1


Result: Thus the program was written and executed

successfully.

Ex.no:3.a Programs using structures and pointers Date:


Aim:

To write a program for print the Student Records using Structures


and Pointers

Algorithm:
Step 1: Start the Program
Step 2: Structures can be created and accessed using pointers.
Step 3: the pointer variable of type struct name is created.
Step 4: A structure's member can be accesssed through pointer
Step 5:Referencing pointer to another address to access memory
Step 6:Then only the structure member through pointer can can
accessed. Step 7:End the program

Program:
#include <stdio.h>
#include <string.h>

struct student
{
int id; char
name[30]; float
percentage;
};

int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};struct
student *ptr;

ptr = &record1;
printf("Records of STUDENT1: \n"); printf(" Id
is: %d \n", ptr->id); printf(" Name is: %s \n", ptr-
>name); printf(" Percentage is: %f \n\n", ptr-
>percentage);

return 0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
RESULT:
Thus the program was written and executed successfully.
Ex.no:3.b Date: Program To copy a
Structure in C

Aim:

To write a program for to copy a structure in C

Algorithm:
Step 1:Start the program
Step 2:define pointers to structures in the same way as you define pointer to any other variable
Step 3:can store the address of a structure variable in the above defined pointer variable. Step
4:To find the address of a structure variable, place the '&'; operator before the structure's name
Step 5:To access the members of a structure using a pointer to that structure, you must use the
→ operator
Step 6:End the program

Program:
#include <stdio.h>
#include <string.h>
struct student
{
int id; char
name[30]; float
percentage;
};

int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2, *record3, *ptr1, record4;

printf("Records of STUDENT1 - record1 structure \


n"); printf(" Id : %d \n Name : %s\n Percentage :
%f\n", record1.id, record1.name, record1.percentage);

// 1st method to copy whole structure to another


structure record2=record1;

printf("\nRecords of STUDENT1 - Direct copy from "


\ "record1 \n"); printf(" Id : %d \n
Name : %s\n Percentage : %f\n", record2.id,
record2.name, record2.percentage);

// 2nd method to copy using memcpy


function ptr1 = &record1;
memcpy(record3, ptr1, sizeof(record1));

printf("\nRecords of STUDENT1 - copied from record1 "


\ "using memcpy \n"); printf(" Id : %d \n
Name : %s\n Percentage : %f\n",
record3->id, record3->name, record3-
>percentage);

// 3rd method to copy by individual members printf("\


nRecords of STUDENT1 - Copied individual "
\ "members from record1 \n");
record4.id=record1.id; strcpy(record4.name,
record1.name); record4.percentage =
record1.percentage; printf(" Id : %d \n
Name : %s\n Percentage : %f\n", record4.id,
record4.name, record4.percentage);

return 0;
}
OUTPUT:

Records of STUDENT1 – record1 structure


Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 – Direct copy from record1
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 – copied from record1 using memcpy
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 – Copied individual members from
record1 Id : 1
Name : Raju
Percentage : 90.500000

RESULT:

Thus the program was written and executed successfully.


Ex.no:4 Programs involving dynamic memory allocations Date:

Aim:
To write a dynamic memory allocation program to create memory for int , char and
float variable at run time.

Algorithm:
Step 1:Start the program
Step 2: Initializing and allocating memory dynamically
Step 3:malloc () function is used to allocate space in memory during the execution of
the program.
Step 4:malloc () does not initialize the memory allocated during execution. Step
5:It carries garbage value. malloc () function returns null pointer if it couldn't able
toallocate requested amount of memory. Step 6: End the program
Program:
#include <stdio.h>
#include <stdlib.h>

int main()
{ int *iVar;
char *cVar;
float *fVar;

/*allocating memory dynamically*/

iVar=(int*)malloc(1*sizeof(int));
cVar=(char*)malloc(1*sizeof(char));
fVar=(float*)malloc(1*sizeof(float));

printf("Enter integer value: ");


scanf("%d",iVar);

printf("Enter character value: "); scanf(" %c",cVar);


printf("Enter float value: "); scanf("%f",fVar); printf("Inputted
value are: %d, %c, %.2f\n",*iVar,*cVar,*fVar);

/*free allocated memory*/


free(iVar); free(cVar);
free(fVar);

return 0;
}

OUTPUT:
Enter integer value: 100

Enter character value: x

Enter float value: 123.45


Inputted value are: 100, x, 123.45
RESULT:
Thus the program was written and executed successfully.
Ex.no:5.a Implementation of Stack Using Array in C Date:

Aim:
To write a program for implementation of stack using array in C

Algorithm:
Step 1:Start the program
Step 2:Stack operations may involve initializing the stack,
Step 3:We initialize top at -1, as the index in array starts from 0. So we check if the top is
below zero or -1 to determine if the stack is empty.
Step 4:The process of putting a new data element onto stack, Push operation involves Checks if
the stack is full ,produces an error and exit.
Step 5: If the stack is not full, increments top to point next empty space. Adds data element to
the stack location, where top is pointing.
Step 6:A Pop operation may involve Checks if the stack is empty, produces an error and exit.
Step 7: If the stack is not empty, accesses the data element at which top is pointing. Decreases
the value of top by 1.
Step 8:End the program
Program:
#include<stdio.h>
int
stack[100],choice,n,top,x,i;
void push(void); void
pop(void); void display(void);
int main()
{
//clrscr(); top=-
1;
printf("\n Enter the size of
STACK[MAX=100]:"); scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{ printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{ case 1:
{ push();
break; }
case 2:
{ pop();
break; }
case 3:
{
display()
; break; }
case 4:
{ printf("\n\t EXIT POINT ");
break;
}
default:
{ printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
} while(choice!
=4); return 0; } void
push()
{
if(top>=n-1)
{ printf("\n\tSTACK is over
flow");

}
else
{ printf(" Enter a value to be pushed:");
scanf("%d",&x); top++;
stack[top]=x;
}
} void
pop()
{ if(top<=-1)
{ printf("\n\t Stack is under flow");
}
else
{ printf("\n\t The popped elements is
%d",stack[top]); top--;
}
} void
display()
{ if(top>=0)
{ printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{ printf("\n The STACK is empty");
}
}
OUTPUT:
Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY

1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12
Enter the Choice:1
Enter a value to be pushed:24

Enter the Choice:1


Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98
24
12
Press Next Choice
Enter the Choice:2

The popped elements is 98


Enter the Choice:3

The elements in STACK

24
12
Press Next Choice
Enter the Choice:4

EXIT POINT
RESULT:
Thus the program was written and executed successfully.
Ex.no:5.b Implementation of Queue using Array in C Date:

Aim:
To write a program for implementation of Queue using array in C

Algorithm:
Step 1:Queue operations may involve initializing or defining the queue, utilizing it, and
then completely erasing it from the memory.
Step2:This function helps to see the data at the front of the queue. The algorithm
of peek() ,Implementation of peek() function
Step 3:we just check for the rear pointer to reach at MAXSIZE to determine that the queue
is full,Implementation of isfull() function
Step 4:If the value of front is less than MIN or 0, it tells that the queue is not yet
initialized, hence empty.
Step 5:Check if the queue is full produce overflow error and exit.
Step 6:If the queue is not full, increment rear pointer to point the next empty
space. Step 7: Add data element to the queue location, where the rear is pointing.
Step 8:Check if the queue is empty.produce underflow error and exit.

Step9:If the queue is not empty, access the data where front is pointing. Increment front pointer
to point to the next available data element.
Program:
#include<stdio.h>
#include<conio.h
> #define n 5 void
main()
{ int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
//clrscr();
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{ printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch) { case
1:
if(rear==x) printf("\n Queue
is Full");
else
{ printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==
rear)

{ printf("\n Queue is empty");


}
else
{ printf("\n Deleted Element is
%d",queue[front++]); x++;
}
break;
case 3:
printf("\n Queue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{ for(i=front; i<rear; i++)
{ printf("%d",queue[i]);
printf("\n"); } break;
case 4:
exit(0);
default:
printf("Wrong Choice: please see the
options"); }
}
}
getch();
}
OUTPUT:
Queue using Array
1.Insertion
2.Deletion
3.Display
4.Exit
Enter the Choice:1
Enter no 1:10
Enter the Choice:1
Enter no 2:54
Enter the Choice:1
Enter no 3:98
Enter the Choice:1
Enter no 4:234 Enter
the Choice:3 Queue
Elements are:
10
54
98
234
Enter the Choice:2
Deleted Element is 10
Enter the Choice:3
Queue Elements are:
54
98
234
Enter the Choice:4

RESULT:
Thus the program was written and executed successfully.
Ex.no:6.a C Program to Implement a Stack using Linked List Date:

Aim:
To write a C Program to Implement a Stack using Linked List

Algorithm:
Step 1:Start the program
Step 2:push an element into stack.
Step 3:struct node* push(struct node* head,int data)
struct node* tmp = (struct node*)malloc(sizeof(struct node)); if(tmp ==
NULL) Step 4:exit(0);
Step 5: tmp->data = data;
Step 6:tmp->next = head; head = tmp;
Step 7:return head Step
8:Stop the program
Program:
#include <stdio.h>
#include
<stdlib.h>
struct node
{ int info;
struct node
*ptr; }*top,*top1,*temp;

int topelement();
void push(int
data); void pop();
void empty(); void
display(); void
destroy(); void
stack_count(); void
create(); int count
= 0;

void main()
{ int no, ch, e;

printf("\n 1 - Push"); printf("\


n 2 - Pop"); printf("\n 3 -
Top"); printf("\n 4 -
Empty"); printf("\n 5 -
Exit"); printf("\n 6 -
Dipslay"); printf("\n 7 -
Stack Count"); printf("\n 8 -
Destroy stack"); create();

while (1)
{ printf("\n Enter choice : ");
scanf("%d", &ch);

switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
/* Create empty stack

* Count stack elements


*/
printf("\n
void No. of elements in stack : %d",
stack_count()
count); }

/* Pushdataintostack*/
voidpush(int data)
{
if (top == NULL)
*/ void
{ create()
{ toptop
= =(structnode*)malloc(1*sizeof(struct
NULL;
} node)); top->ptr = NULL;
top->info= data;
/ }
else
{ {
=(struct tempnode *)malloc(1*sizeof(struct
node)); = temp->ptr top; temp->info data;
top = } = count++;
temp;

/* Display stack elements */


void display()
{
top1 = top;

if (top1 == NULL)
{
printf("Stack is empty");
return;
}

while (top1 != NULL)


{ printf("%d ", top1->info);
top1 = top1->ptr;
}
}

/* Pop Operation on stack */


void pop()
{
top1 = top;

if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}

* Return top element


*/ int
topelement() {

return(top->info);
1 - Push
2 - Pop
3 - Top
- Empty
4
- Exit
5 - Dipslay
6
- Stack Count
7 - Destroy stack
8 Enter choice : 1
Enter data : 56

Enter choice : 1
Enter data : 80

Enter choice : 2

Popped value : 80
Enter choice : 3

Top element : 56
Enter choice : 1
Enter data : 78

Enter choice : 1
Enter data : 90

Enter choice : 6
90 78 56
Enter choice : 7

No. of elements in stack : 3


Enter choice : 8

Allstack elements destroyed


Enter choice : 4

Stack is empty
Enter choice : 5

RESULT:
Thus the program was written and executed successfully.
Ex.no:6.b C Program to Implement a Queue using Linked List Date:

Aim:
To write a C Program to Implement a Queue using Linked List
Algorithm:
Step 1: Include all the header files which are used in the program. And declare all the
user defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL. Create a newNode
with given value and set 'newNode → next' to NULL.
Step 4:Check whether queue is Empty (rear == NULL), If it is Empty then,
set front = newNode and rear = newNode. If it is Not Empty then, set rear →
next = newNode and rear = newNode.
Step 5:If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and
terminate from the function. If it is Not Empty then, define a Node pointer 'temp' and set it to
'front'. Step 6: Then set 'front = front → next' and delete 'temp' (free(temp)).
If it is Not Empty then, define a Node pointer 'temp' and initialize with front. Step 7: Display
'temp → data --->' and move it to the next node. Repeat the same until 'temp' reaches to 'rear'
(temp → next != NULL). Finally! Display 'temp → data ---> NULL'.

Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct Node
{ int Data; struct
Node* next; }*rear,
*front;

void delQueue()
{ struct Node *temp, *var=rear;
if(var==rear)
{ rear = rear->next;
free(var);
}
else
printf("\nQueue Empty");
}

void push(int value)


{ struct Node *temp;
temp=(struct Node *)malloc(sizeof(struct
Node)); temp->Data=value; if (front == NULL)
{ front=temp;
front->next=NULL;
rear=front;
}
else
{ front->next=temp;
front=temp; front-
>next=NULL;
}
}

void display()
{ struct Node *var=rear;
if(var!=NULL)
{ printf("\nElements are as: ");
while(var!=NULL)
{ printf("\t%d",var->Data);
var=var->next;
}
printf("\
n"); }
else
printf("\nQueue is Empty");
}

int main()
{ int i=0; front=NULL; printf(" \n1. Push
to Queue"); printf(" \n2. Pop from
Queue"); printf(" \n3. Display Data of
Queue");
printf(" \n4. Exit\n");
while(1)
{ printf(" \nChoose Option: ");
scanf("%d",&i);
switch(i)
{ case 1:
{ int value; printf("\nEnter a valueber to push into
Queue: ");
scanf("%d",&value);
push(value);
display();
break;
} case 2:
{ delQueue();
display();
break;
} case 3:
{
display();
break;
} case 4:
{
exit(0)
;}
default:
{ printf("\nwrong choice for operation");
}
}
}
}
OUTPUT:
1.Push to Queue
2.Pop from Queue
3.Display Data of Queue
4.Exit
Choose Option: 1
Enter a valueber to push into Queue:
10 Elements are as: 10
Choose option : 1
Enter a valueber to push into Queue:
20 Elements are option : 1 as:
Choose 10 20
Enter a 20
valueber to
Elements are push 20
as: Choose into Queue
option : 2 30 20 30
Elements are
as: Choose
Option: 1
Enter a 30
valueber to
Elements are into Queue
as: Choose 40 30 40
Option:
RESULT:
push 10
Thus the program was written and executed successfully.
Ex.no:7.a Application of Stacks Date:

Infix to Postfix implementation in C


Aim:
To write a C program for implementing Infix to Postfix conversion

Algorithm:
Step 1: Scan the Infix string from left to right.
Step 2: Initialize an empty stack.
Step 3: If the scanned character is an operand, add it to the Postfix string. Step 4: If
the scanned character is an operator and if the stack is empty push the character to
stack. Step 5: If the scanned character is an Operator and the stack is not empty,
compare the precedence of the character with the element on top of the stack.
Step 6: character to stack. Repeat this step until the stack is not empty and top Stack
has precedence over the character.
Step 7: Repeat 4 and 5 steps till all the characters are scanned.
Step 8: After all characters are scanned, we have to add any character that the stack may have
to the Postfix string.
Step 9: If stack is not empty add top Stack to Postfix string and Pop the
stack. Step 10: Repeat this step as long as stack is not empty.
Program
#include <stdio.h>
#include
<conio.h>
#include <ctype.h>
#define SIZE 50
char s[SIZE]; int
top=-1; push(char
elem)
{ s[++top]=elem;
}

char pop()
{
return(s[top--]);
}

int pr(char elem)


{ switch(elem)
{ case '#': return
0; case '(': return
1; case '+': case
'-': return 2; case
'*': case '/':
return 3;
}
}

void main()
{ char infx[50],pofx[50],ch,elem;
int i=0,k=0; clrscr(); printf("\n\nRead the
Infix Expression ? ");
scanf("%s",infx); push('#');
while( (ch=infx[i++]) != '\0')
{ if( ch == '(') push(ch); else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{ while( s[top] != '(')
pofx[k++]=pop();
elem=pop(); }
else
{ while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
} while( s[top] !=
'#')
pofx[k++]=pop();
pofx[k]='\0';
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n",infx,pofx);
getch();
}
OUTPUT:

Enter the Infix Expression = A+(B*C-(D/E-F)*G)*H

Given Infix Expn= A+(B*C-(D/E-F)*G)*H


Postfix Expn:= ABC*DE/F-G*-H*+
RESULT:

Thus the program was written and executed successfully.


Ex.no:7.b Application of Queues

Date: Program for First Come First Served (FCFS)

Aim:
To write a program for First Come First Served

Algorithm:
Step 1:A Non-Preemptive scheduling algorithm. FIFO (First In First Out) Step
2:strategy assigns priority to process in the order in which they request the processor.
Step 3:The process that requests the CPU first is allocated the CPU first. Step 4:This is
easily implemented with a FIFO queue for managing the
tasks. Step 5:As the process come in, they are put at the end of the queue.
Step 6:As the CPU finishes each task, it removes it from the start of the queue and heads on to
the next task.

Program:
#include<stdio.h>

int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum 20):");
scanf("%d",&n);

printf("\nEnter Process Burst Time\n");


for(i=0;i<n;i++)
{ printf("P[%d]:",i+1);
scanf("%d",&bt[i]);
} wt[0]=0; //waiting time for first process

is 0

//calculating waiting time for(i=1;i<n;i+


+)
{ wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
} printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround

Time");
//calculating turnaround time for(i=0;i<n;i+
+)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
printf("\nP[%d]\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i])
;}

avwt/=i;
avtat/=i;
printf("\n\nAverage Waiting Time:%d",avwt); printf("\
nAverage Turnaround Time:%d",avtat);

return
0; }
OUTPUT

Enter total number of processes(maximum 20):3


Enter process Burst Time
P[1]:24
P[2]:3
P[3]:3

Process Burst Time Waiting Time Turnaround Time P[1] 24 0


24
P[2] 3 24 27
P[3] 3 27 30

Average Waiting Time:17


Average Turnaround Time:27
Process returned 0(0x0) execution time: 7.661 s
Press any key to continue.
RESULT:
Thus the program was written and executed successfully.
Ex.no:8 Implementation of Trees , Tree Traversals Date:

Aim:
To write a program for implementation of Trees ,Tree Traversals.

Algorithm:

Step1 : Start the program


Step 2 : Recursively traverse left subtree.
Step 3 : Visit root node.
Step 4 : Recursively traverse right subtree.
Step 5 : Visit root node.
Step 6 : Recursively traverse left subtree.
Step 7 : Recursively traverse right subtree.
Step 8 : Recursively traverse left subtree.
Step 9 : Recursively traverse right
subtree. Step 10 : Visit root node. Step 11

:End the program Program:

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

struct node {
int data;

struct node *leftChild;


struct node *rightChild;
};

struct node *root = NULL;

void insert(int data) {


struct node *tempNode = (struct node*)
malloc(sizeof(struct node)); struct node *current; struct
node *parent;
tempNode->data = data; tempNode-
>leftChild = NULL;
tempNode->rightChild =
NULL;
//if tree is empty
if(root == NULL)
{ root = tempNode;
} else { current =
root; parent =
NULL;

while(1) {
parent = current;

//go to left of the tree


if(data < parent->data) {
current = current->leftChild;

//insert to the left


if(current == NULL)
{ parent->leftChild =
tempNode; return;
}

} //go to right of the tree


else {
current = current->rightChild;

//insert to the right


if(current == NULL)
{ parent->rightChild =
tempNode; return;
}
}
}
}
}

struct node* search(int data)


{ struct node *current = root;
printf("Visiting elements: ");

while(current->data != data)
{ if(current != NULL)
printf("%d ",current-
>data); //go to left tree
if(current->data > data) {
current = current->leftChild;
} //else go to right tree else
{ current = current->rightChild;
}

//not found if(current


== NULL) {
return NULL;
}
}

return
current; }

void pre_order_traversal(struct node* root)


{ if(root != NULL) {
printf("%d ",root->data); pre_order_traversal(root-
>leftChild);
pre_order_traversal(root->rightChild);
}
}
void inorder_traversal(struct node* root)
{ if(root != NULL) {
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}

void post_order_traversal(struct node* root)


{ if(root != NULL) {
post_order_traversal(root->leftChild); post_order_traversal(root-
>rightChild)
; printf("%d ", root->data);
}
}

int main()
{ int i;
int array[7] = { 27, 14, 35, 10, 19, 31,
42 }; for(i = 0; i < 7; i++) insert(array[i]);

i = 31; struct node * temp =


search(i);

if(temp != NULL) {
printf("[%d] Element found.", temp-
>data); printf("\n");
}else { printf("[ x ] Element not found
(%d).\n",
i); }

i = 15; temp =
search(i);

if(temp != NULL) {
printf("[%d] Element found.", temp-
>data); printf("\n");
}else { printf("[ x ] Element not found
(%d).\n",
i); }

printf("\nPreorder traversal: ");


pre_order_traversal(root);

printf("\nInorder traversal: ");


inorder_traversal(root); printf("\nPost order
traversal: "); post_order_traversal(root);

return 0;
}
OUTPUT:

Visiting elements: 27 35 [31] Element found.

Visiting elements: 27 14 19 [ x ] Element not found (15).

Preorder traversal: 27 14 10 19 35 31 42

Inorder traversal: 10 14 19 27 31 35 42

Post order traversal: 10 19 14 31 42 35 27


RESULT:
Thus the program was written and executed successfully.
Ex.no:9 Implementation of Binary Search Trees Date:

Aim:
To write a program for Implementation of Binary Search Trees

Algorithm:

Step 1: Start the Program


Step 2: Pre-order traversal_In this traversal technique the traversal order is root-left-
right Step2.1: Process data of root node
Step 2.2: First, traverse left subtree completely
Step 2.3: Then, traverse right subtree
Step 3: Post-order traversal_In this traversal technique the traversal order is left-right-
root. Step 3.1: Process data of left subtree
Step 3.2: First, traverse right subtree
Step 3.3: Then, traverse root node
Step 4: In-order traversal_In in-order traversal, do the following:
Step 4.1: First process left subtree (before processing root node)
Step 4.2: Then, process current root node
Step 4.3: Process right subtree
Step 5: the Program

Program:
#include<stdlib.h>
#include<stdio.h>
struct bin_tree {
int data;
struct bin_tree * right, * left;
}; typedef struct bin_tree
node;

void insert(node ** tree, int val)


{ node *temp = NULL;
if(!(*tree))
{ temp = (node
*)malloc(sizeof(node)); temp->left =
temp->right = NULL; temp->data =
val;
*tree = temp;
return;
}
if(val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}

void print_preorder(node *
tree) { if
(tree)
{ printf("%d\n",tree->data);
print_preorder(tree->left);

print_preorder(tree->right);
}

void print_inorder(node * tree)


{
if (tree)
{
print_inorder(tree->left); printf("%d\n",tree-
>data);
print_inorder(tree->right);
}
}

void print_postorder(node *
tree) { if
(tree)
{
print_postorder(tree->left); print_postorder(tree-
>right)
; printf("%d\n",tree->data);
}
}

void deltree(node * tree)


{
if (tree)
{
deltree(tree->left); deltree(tree-
>right);
free(tree);
}
}
node* search(node ** tree, int
val) {
if(!(*tree))
{ return NULL;
}

if(val < (*tree)->data)


{
search(&((*tree)->left),
val); }
else if(val > (*tree)->data)
{ search(&((*tree)->right),
val); }
else if(val == (*tree)->data)
{ return *tree;
}
}

void main()
{ node *root;
node *tmp;
//int i;

root = NULL;
/* Inserting nodes into tree
*/ insert(&root, 9);
insert(&root, 4);
insert(&root, 15);
insert(&root, 6);

insert(&root, 12);
insert(&root, 17);
insert(&root, 2);

/* Printing nodes of tree */


printf("Pre Order Display\n");
print_preorder(root);

printf("In Order Display\n");


print_inorder(root);
printf("Post Order Display\n");
print_postorder(root);

/* Search node into tree */


tmp = search(&root, 4);
if (tmp)
{ printf("Searched node=%d\n",
tmp->data); }
else
{ printf("Data Not found in tree.\n");
}

/* Deleting all nodes of tree */


deltree(root);
}
OUTPUT:

Pre Order Display


9
4
2
6
15
12
17
In Order Display
2
4
6
9
12
15
17
Post Order Display
2
6
4
12
17
15
9
Searched node=4
RESULT:
Thus the program was written and executed successfully.
Ex.no:10.a Implementation of Linear Search And Binary Search
Date:

Aim:
To write a program a for Implementation of Linear Search

Algorithm:
Step 1: Read the search element from the user
Step 2: Compare, the search element with the first element in the list.
Step 3: If both are matching, then display "Given element found!!!" and terminate the function
Step 4: If both are not matching, then compare search element with the next element in the list.
Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in the
list. Step 6: If the last element in the list is also doesn't match, then display "Element not
found!!!" and terminate the function.

Program:

#include <stdio.h>
int main()
{ int array[100], search, c,
n;

printf("Enter the number of elements in array\n");


scanf("%d", &n); printf("Enter

%d integer(s)\n", n);

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


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

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


{
if (array[c] == search) /* If required element is found */ {
printf("%d is present at location %d.\n", search,
c+1); break;
}
} if (c == n) printf("%d isn't present in the array.\
n", search);

return 0;
}
OUTPUT:

Enter the number of elements in array


5
Enter 5 numbers
5
6
4
2
9
Enter the number to search
4
4 is present at location 3.
RESULT:
Thus the program was written and executed successfully.
Ex.no:10.b Implementation Of Binary Search Date:

Aim:
To write a program to Implementation of Binary Search

Algorithm:

Step 1:Given an array A of n elements with values or records A0, A1, ..., An−1, Step 2: sorted
such that A0 ≤ A1 ≤ ... ≤ An−1, and target value T, the following subroutine uses binary search
to find the index of T in A.
Step 3:Set L to 0 and R to n − 1.
Step 4: If L > R, the search terminates as unsuccessful.
Step 5: Set m (the position of the middle element) to the floor, or the greatest integer
less than (L + R) / 2.
Step 6: If Am < T, set L to m + 1 and go to step 2.
Step 7: If Am > T, set R to m − 1 and go to step 2.
Step 8:Now Am = T, the search is done; return m.
Program:
#include <stdio.h>

int main()
{ int c, first, last, middle, n, search,
array[100];

printf("Enter number of elements\n");


scanf("%d",&n); printf("Enter

%d integers\n", n);

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


scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) { if


(array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search,
middle+1); break; }
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}
OUTPUT:

Enter number of elements


7
Enter 7 integers
-4
5
8
9
11
43
485
Enter value to find
11
11 found at location 5

RESULT:
Thus the program was written and executed successfully.

Ex.no:11.a Implementation of Insertion Sort Date:

Aim:
To write a program for implementation of 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( );
}

You might also like