Cs6212 Programming and Data Structure Lab
Cs6212 Programming and Data Structure Lab
LAB MANUAL
For more Visit : www.EasyEngineering.net
ww Regulation : 2013
w.E
Branch : B.E. – CSE
Year & Semester asy : I Year / II Semester
REGULATION-2013
OBJECTIVES:
The students should be made to:
ww
Learn to use files
Learn to implement sorting and searching algorithms.
w.E
1. C Programs using Conditional and Control Statements.
2. C Programs using Arrays, Strings and Pointers and Functions.
asy
3. Representation of records using Structures in C – Creation of Linked List –
En
Manipulation of records in a Linked List.
4. File Handling in C – Sequential access – Random Access.
gin
5. Operations on a Stack and Queue – infix to postfix – simple expression evaluation
eer
using stacks -Linked Stack Implementation – Linked Queue Implementation.
6. Implementation of sorting algorithms.
7. Implementation of Linear search and Binary Search.
ing
.ne
t
TOTAL: 45 PERIODS
INDEX
SIGNATURE
S.NO DATE NAME OF THE PROGRAM OF THE REMARKS
FACULTY
CONDITIONAL AND CONTROL STATEMENTS
ww 5
6
Factorial of N Number using Recursion
Maximum of N Number using Array
7
8 w.E Computation of Matrix Multiplication
Determination of Palindrome
asy
STRUCTURES AND LINKED LIST
9 Generation of Payroll Application
En
10 Implementation of Singly Linked List
FILE HANDLING
11
12
Sequential File Access
Random File Access gin
STACK AND QUEUE
eer
13
Implementation of Stack using Linked
List
Implementation of Queue using Linked ing
14 List
Conversion of Infix to Postfix .ne
15
16
Expression
Evaluation of Postfix Expression
SORTING ALGORITHMS
t
Sorting N Numbers using Quick Sort
17
Sorting N Numbers using Merge Sort
18
LINEAR AND BINARY SEARCH
Searching an Element using Linear
19 Search
Searching an Element using Binary
20 Search
The “switch” statement tests expression value against a list of case values. When a
match is found, statements associated with that case is executed until a “break” statement is
encountered. The default block is executed when none of the case value matches.
ww
condition holds true. Minimum number of times the loop executed is 0.
w.E
The “do … while” construct provides an exit-controlled loop. Body of the loop is
executed once and then condition is evaluated. If true, then the process is repeated. The loop
is executed at least once.
asy
En
The “for” statement is an entry and counter controlled loop. It contains three parts
gin
namely initialize condition and increment/decrement. The counter variable is initialized once
and the condition is evaluated. If condition is true, then body of the loop is executed. Counter
eer
variable is incremented or decremented each time before testing the condition.
ing
The “break” statement is used to exit from the loop in which it is contained. The
“continue” statement skips remaining part of the loop for that iteration.
.ne
t
EX. NO: 1
DATE:
IMPLEMENTATION OF SIMPLE CALCULATOR
AIM
To implement a simple calculator using switch case statement.
ALGORITHM
1. Start
2. Display calculator menu
3. Read the operator symbol and operands n1, n2
ww 4. If operator = + then
5. calculate result = n1 + n2
6. Else if operator = – then
w.E
7. calculate result = n1 – n2
8. Else if operator = * then
asy
9. calculate result = n1 * n2
10. Else if operator = / then
11. calculate result = n1 / n2
12. Else if operator = % then
En
13. calculate result = n1 % n2
14. Else gin
15. print "Invalid operator"
16. Print result eer
17. Stop
ing
.ne
t
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
int n1, n2, result;
char op;
clrscr();
printf("\n Simple Calculator");
printf("\n + Summation");
printf("\n - Difference");
ww
printf("\n * Product");
printf("\n / Quotient");
printf("\n % Remainder");
w.E
printf("\n Enter the operator :”);
op = getchar();
scanf("%d%d",&n1,&n2);
switch(op)
asy
printf("Enter operand1 and operand2 :");
{
En
case '+':
result = n1 +n2;
gin
eer
break;
case '-':
ing
result = n1 - n2;
break;
case '*':
result = n1 * n2;
.ne
t
break;
case '/':
result = n1 / n2;
break;
case '%':
result = n1 % n2;
break;
default:
printf("Invalid operator");
exit(-1);
}
printf("%d %c %d = %d", n1, op, n2,result);
getch();
}
OUTPUT
Simple Calculator
+Summation
- Difference
* Product
/ Quotient
% Remainder
Enter the operator : -
Enter operand1 and operand2 : 2 4
ww
2 - 4 = -2
w.E
Simple Calculator
+Summation
- Difference asy
* Product
En
/ Quotient
gin
% Remainder
Enter the operator : % eer
Enter operand1 and operand2 : 5 2 ing
5%2=1
.ne
t
RESULT
Thus simple calculator functionality was executed using menu-oriented approach.
EX. NO: 2
DATE:
GENERATION OF PRIME NUMBER
AIM
To print first 'n' numbers using for loop.
ALGORITHM
1. Start
2. Read the value of n
3. Loop j to generate numbers from 2 to 10000
w.E
6. If j%k = 0 then
7. Examine next j
8. If there are no divisor for j then
9. Print j
10. Increment i by 1 asy
11. If i = n then
12. Stop En
13. Else
14. Examine next j gin
15. Stop.
eer
ing
.ne
t
#include <stdio.h>
#include <conio.h>
Void main()
{
int i=0,j,k,n,flg;
clrscr();
printf("\n Enter value for n : ");
scanf("%d", &n);
printf("Prime numbers : ");
for(j=2; j<=10000; j++)
{
ww
flg = 0;
for(k=2; k<=j/2; k++)
{
if (j%k == 0)
{ w.E
flg = 1;
break;
}
asy
}
En
if (flg == 0)
{
gin
eer
printf("%d", j);
i++;
ing
}
if (i == n)
break;
}
.ne
t
getch();
}
OUTPUT
Enter value for n: 9
Prime numbers: 2 3 5 7 11 13 17 19 23
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus first set of prime numbers is displayed.
EX. NO: 3
DATE:
SUMMATION OF N DIGITS
AIM
To find the sum of the digits of a given number using while statement.
ALGORITHM
1. Start
2. Read num
3. Initialize sum to 0.
ww 4.
5.
6.
Repeat until num = 0
Obtain last digit d = num % 10
Add d to sum
7.
8. w.E
num = num / 10
Print sum
9. Stop
asy
En
gin
eer
ing
.ne
t
ww
d=n % 10;
sum=sum+d;
n=n/10;}
w.E
printf("Sum of digits : %d", sum);
getch();
}
asy
En
gin
eer
ing
.ne
t
OUTPUT
Enter the numbers: 5 8 3 4 9
Sum of digits: 29
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus digits of the given number were summed up.
EX. NO: 4
DATE:
GENERATION OF FIBONACCI SERIES
AIM
To print first N terms of the Fibonacci series assuming the first two terms as 0 and 1
ALGORITHM
1. Start
2. Read no. of terms n
3. Initialize f1 to 0 and f2 to 1
ww 4. Print f1 and f2
5. Initialize i to 3
6. Repeat until i < n
w.E
7. Generate next term f3 = f1 + f2
8. Print f3
9. f1 = f2
10. f2 = f3 asy
11. Increment i by 1
12. Stop
En
gin
eer
ing
.ne
t
ww
printf("\n Fibonacci series \n");
printf("%ld \n %ld \n",f1,f2);
for(i=3; i<=n; i++)
{
f3 = f1 + f2;w.E
printf("%ld",f3);
f1 = f2;
f2 = f3;
asy
}
En
getch();
}
gin
eer
ing
.ne
t
OUTPUT
Enter number of terms: 10
Fibonacci series 0 1 1 2 3 5 8 13 21 34
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus first ‘n’ terms of Fibonacci series was generated.
w.E
as character array. C library provides string handling function under header file <string.h>.
String variables are not preceded by a “&” in a “scanf” statement. The function “gets" is
used to read string with embedded whitespace.
asy
Structure is a user-defined data type and is a collection of heterogeneous elements, i.e.
elements can have dissimilar types. Elements in a structure are referred as members. Each
En
member within a structure is assigned its own unique storage area. Memory allocation for a
structure is sum of memory required for each member. It is generally obtained using “sizeof”
gin
operator. Members of a structure are accessed using dot (.) operator.
Pointer variable is a variable that can store the address of another variable. Pointer
eer
variables are prefixed with “*” operator in declaration statement. Address of a variable is
obtained using & (address) operator. A pointer variable can point to elements of the same
ing
type only. A pointer variable can access value of the variable pointed to by using the “*”
dereference operator. Arguments must be of pointer type for pass-by-reference. When
.ne
arguments are passed by reference, changes made within the function are reflected in the
calling function. Pointers can be used to voluminous data by passing an array (starting
address).
EX. NO: 5
DATE:
FACTORIAL OF N NUMBER USING RECURSION
AIM
To find the factorial of a number using recursive function.
ALGORITHM
1. Start
2. Read the value of n
3. Call function factorial (n)
ww 4.
5.
6.
Print return value
Stop
Function factorial (n)
7.
8. w.E
If n=1 then return 1
Else return n*factorial (n-1)
asy
En
gin
eer
ing
.ne
t
ww
printf("Factorial value : %ld",f);
getch();
}
w.E
long factorial(int n)
{
if (n <= 1)
return(1);
asy
else
return (n * factorial(n-1));
En
}
gin
eer
ing
.ne
t
OUTPUT
Enter a number: 3
Factorial value: 6
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus factorial value of a given number was obtained through recursive function call.
EX. NO: 6
DATE:
MAXIMUM OF N NUMBERS USING ARRAY
AIM
To find the greatest of ’N’ numbers stored in an array.
ALGORITHM
1. Start
2. Read number of array elements as n
3. Read array elements Ai, i = 0, 1, 2…n–1
ww 4.
5.
6.
Assume first element A0 to be max
Compare each array element Ai with max
If max <Ai then max = Ai
7.
8. w.E
Print max
Stop
asy
En
gin
eer
ing
.ne
t
ww
scanf("%d", &a[i]);
max = a[0];
for(i=1; i<n; i++)
{
w.E
if (max < a[i])
max = a[i];
}
asy
printf("Maximum value = %d ",max);
getch();
En
}
gin
eer
ing
.ne
t
OUTPUT
Enter number of elements: 6
Enter Array Elements
3
8
-7
11
-9
0
ww
Maximum value = 11
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus maximum element of an array was determined.
EX. NO: 7
DATE:
COMPUTATION OF MATRIX MULTIPLICATION
AIM
To compute product of two matrices using two dimensional array.
ALGORITHM
1. Start
2. Read the order of matrix A as m and n
3. Read the order of matrix B as p and q
w.E
6. Read matrix B elements Bij
7. Initialize matrix C elements Cij to 0
8. Compute product matrix Cij = Cij + Aik * Bkj where 0 i < m, 0 j < q and 0 k < n
9. Print matrix Cij,
10. Stop asy
En
gin
eer
ing
.ne
t
ww
if (c1 != r2)
{
printf("Matrix multiplication not possible");
getch();
exit(0); w.E
}
asy
printf("Enter matrix Aelements\n");
for(i=0; i<r1; i++)
{
En
for(j=0; j<c1; j++)
{
gin
eer
scanf("%d", &a[i][j]);
}
ing
}
printf("Enter matrix Belements\n");
for(i=0; i<r2; i++)
{
.ne
t
for(j=0; j<c2; j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
c[i][j] = 0;
for(k=0; k<c1; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
printf("Product matrix C\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
printf("%-4d",c[i][j]);
}
printf("\n");
}
getch();
}
ww
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
Enter order of matrix A: 2 3
Enter order of matrix B: 3 2
Enter matrix A elements
1 1 1
1 1 1
Enter matrix B elements
2 2
2 2
ww
2 2
6 6 w.E
Product matrix C
6 6
asy
En
gin
eer
ing
.ne
t
RESULT
Thus product of given two matrices was obtained using arrays.
EX. NO. 8
DATE:
DETERMINATION OF PALINDROME
AIM
To determine whether the input string is palindrome using string handling functions.
ALGORITHM
1. Start
2. Read the string, say str
3. Copy str onto rev using strcpy function
4. Reverse rev using strrev function
w.E
7. Print "Given string is palindrome"
8. Else
asy
9. Print "Given string is not palindrome"
10. Stop
En
gin
eer
ing
.ne
t
ww
strrev(rev);
printf("Reversed string is: %s \n",rev);
x = strcmpi(str, rev);
if (x == 0)
w.E
printf("Given string is a palindrome");
else
asy
printf("Given string is not a palindrome");
getch();
}
En
gin
eer
ing
.ne
t
OUTPUT
Enter the string: malayalam
Reversed string is: malayalam
Given string is a palindrome
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus the given input string is checked for palindrome using string handling functions.
w.E
such as list and trees.
A linked list is a set of nodes where each node has two field’s data and a link. The
link field points to the next node by storing address of the next node. An operation on a
asy
linked list includes insertion and deletion of a node and traversal of the list. Backward
traversal is not possible in a singly linked list.
En
Doubly linked list node contains an additional pointer that contains address of the
gin
previous node in the list. Both forward and backward traversal is possible in a doubly linked
list.
eer
ing
.ne
t
EX. NO: 9
DATE:
GENERATION OF PAYROLL APPLICATION
AIM
To generate employee payroll for an organization using structure.
ALGORITHM
1. Start
2. Define employee structure with fields empid, ename, basic, hra, da, it, gross and
netpay
w.E
6. hra = 2% of basic
7. da = 1% of basic
asy
8. gross = basic + hra + da
9. it = 5% of basic
10. netpay = gross - it
En
11. Print empid, ename, basic, hra, da, it, gross and netpay for all employees
12. Stop
gin
eer
ing
.ne
t
ww
float netpay;
};
void main()
{
w.E
struct employee emp[50];
inti, j, n;
clrscr();
asy
printf("\n Enter No. of Employees : ");
scanf("%d", &n);
En
for(i=0; i<n ;i++)
{
gin
eer
printf("\n Enter Employee Details \n");
printf("Enter Employee Id : ");
ing
scanf("%d", &emp[i].empid);
printf("Enter Employee Name : ");
scanf("%s", emp[i].ename);
printf("Enter Basic Salary : ");
.ne
t
scanf("%d", &emp[i].basic);
}
for(i=0; i<n; i++)
{
emp[i].hra = 0.02 * emp[i].basic;
emp[i].da= 0.01 * emp[i].basic;
emp[i].it= 0.05 * emp[i].basic;
emp[i].gross = emp[i].basic + emp[i].hra + emp[i].da;
emp[i].netpay = emp[i].gross - emp[i].it;
}
printf("\n\n\n\t\t\t\tXYZ& Co.Payroll\n\n");
for(i=0;i<80;i++)
printf("*");
printf("EmpId\tName\t\tBasic\t HRA\t DA\t IT\tGross\t\tNet
ay\n");
for(i=0;i<80;i++)
printf("*");
for(i=0; i<n; i++)
{
printf("\n%d\t%-
15s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f",emp[i].empid,emp[i].ena
me, emp[i].basic, emp[i].hra, emp[i].da, emp[i].it,
emp[i].gross, emp[i].netpay);
}
printf("\n");
for(i=0;i<80;i++)
printf("*");
getch();
ww
}
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
Enter No. of Employees: 2
ww
Enter Employee Id : 463
w.E
Enter Employee Name: Rajesh
Enter Basic Salary : 22000
asy
XYZ & Co. Payroll
En
***************************************************************************
EmpId Name Basic HRA DA IT
gin
Gross Net Pay
RESULT
Thus payroll for employees was generated using structure.
EX. NO: 10
DATE:
ALGORITHM
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
w.E
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create a new node and get data part
asy
9. Insert the new node at appropriate position by manipulating address Else if choice = 2
10. Get node's data to be deleted.
En
11. Locate the node and delink the node
12. Rearrange the links
13. Else
gin
14. Traverse the list from Head node to node which points to null
15. Stop
eer
ing
.ne
t
ww
{
int ch, fou=0;
int k;
w.E
struct node *h, *temp, *head, *h1;
head = (struct node*) malloc(sizeof(struct node));
head->label = -1;
head->next = NULL;
while(-1)
asy
{
En
clrscr();
gin
printf("\n\n SINGLY LINKED LIST OPERATIONS \n");
eer
printf("1->Add");
printf("2->Delete");
ing
printf("3->View");
printf("4->Exit\n");
printf("Enter your choice : ");
scanf("%d", &ch);
.ne
t
switch(ch)
{
case 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;
ww
h->next = temp;
}
break;
case 2:
w.E
printf("Enter label of node to be deleted\n");
scanf("%d", &k);
fou = 0; asy
h = h1 = head;
while (h->next != NULL) En
{
h = h->next; gin
if (h->label == k)
{ eer
fou = 1;
break; ing
}
} .ne
if (fou == 0)
printf("Sorry Node not found\n");
else
t
{
while (h1->next != h)
h1 = h1->next;
h1->next = h->next;
free(h);
printf("Node deleted successfully \n");
}
break;
case 3:
printf("\n\n HEAD -> ");
h=head;
ww
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
SINGLY LINKED LIST OPERATIONS
1->Add 2->Delete 3->View 4->Exit
Enter your choice :1
Enter label after which new node is to be added : -1
Enter label for new node : 23
ww
Enter your choice :1
Enter label after which new node is to be added : 23
w.E
Enter label for new node : 67
RESULT
Thus operation on single linked list is performed.
FILE HANDLING
Applications require information stored on auxiliary storage device. Such information
is stored permanently as a data file that allows accessing and altering the information
whenever necessary.
Prior to performing any activity of a file, the file should be opened. By opening a file,
link between the program and the operating system is established. This link exists by means
of a structure termed as FILE, which is specified in header file “<stdio.h>”.
A file is opened using the standard function “fopen()”. If a file could not be opened
the “fopen()” returns a NULL. A file is opened in the given mode such as reading, writing,
appending, etc. After performing file I/O, the file is closed.
File access could be either sequential or random. Sequential access starts with the first
data set, fetch the next and so on until end-of-file is encountered. End-of-file condition can be
ww
checked using “feof” function.
w.E
Random access means moving file pointer to the desired byte. Pre-defined functions
that facilitate random access are:
“ftell”—to know current position of the file pointer
asy
“rewind”—to move file pointer to beginning of the file
En
“fseek”—used to move the file pointer to the desired byte.
gin
File I/O is generally either character or block oriented. Functions “getc” and “putc” is
used to read/write a single character from the given file. Functions “fread” and “fwrite” is
eer
used to perform I/O as blocks of data, where each block is a fixed number of contiguous
bytes. A block is generally represented as a structure.
ing
Command-line arguments allow parameters to be passed to the main function on
execution. The two command-line arguments are “argc”, an integer variable whose value is
assigned to number of arguments given and “argv”, a string array that contains the list of
arguments. The main function prototype is “main(int argc, char *argv[])” to support
.ne
t
command-line arguments.
EX.NO: 11
DATE:
ALGORITHM
1. Start
2. Open empseq.dat file in append mode
3. Add records to the file
4. Close the file
w.E
7. Check each record one by one from the first record
8. If person name matches then print the details.
asy
9. Close the file
10. Stop
En
gin
eer
ing
.ne
t
ww
FILE *fd1, *fd2;
char str[20];
int found = 0;
w.E
fd1 = fopen("empseq.dat", "a");
printf("\n\t Enter employee details \n");
while(1)
{
asy
printf("\n Enter Name (\"xxx\" to quit) : ");
scanf("%s", emp1.name);
En
if (strcmp(emp1.name,"xxx") == 0)
break;
gin
eer
printf("Enter Contact No. : ");
scanf("%ld", &emp1.mno);
ing
fwrite (&emp1, sizeof(emp1), 1, fd1);
}
fclose(fd1);
fd2 = fopen("empseq.dat", "r");
.ne
t
printf("\n Enter Employee name to get phone no. : ");
scanf("%s", str);
while(fread(&emp2, sizeof(emp2), 1, fd2))
{
if (strcmp(emp2.name, str) == 0)
{
printf("Telephone No. : %ld\n", emp2.mno);
found = 1;
break;
}
}
fclose(fd2);
if(!found)
printf("\n Employee does not exist");
}
OUTPUT
Enter employee details
Enter Name ("xxx" to quit): vijai
Enter Contact No. : 1234567899
Enter Name ("xxx" to quit) : anand
Enter Contact No. : 9876543211
Enter Name ("xxx" to quit): xxx
Enter Employee name to get phone no: anand
ww
Telephone No. : 9876543211
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus sequential access is performed to retrieve a person's contact details.
EX. NO : 12
Date:
RANDOM FILE ACCESS
AIM
To create a address book and to locate employee details using random access.
ALGORITHM
1. Start
2. Open emprand.dat file in append mode
3. Automatically generate employee id
4. Add records to the file
w.E
7. Get employee id.
8. Move the file pointer to the desired record using fseek function
9. Print the details.
10. Close the file
11. Stop asy
En
gin
eer
ing
.ne
t
ww
struct employee emp1, emp2;
FILE *fd1, *fd2;
char str[20];
w.E
int id, eno, pos, size;
fd1 = fopen("emprand.dat", "a");
fseek(fd1, 0, 2);
size = ftell(fd1);
asy
id = 100 + size / sizeof(emp1);
En
printf("\n Enter employee details \n");
while(1)
{
gin
eer
emp1.empid = id++;
printf("\n Employee Id : %d", emp1.empid);
ing
printf("\n Enter Name (\"xxx\" to quit) : ");
scanf("%s", emp1.name);
if (strcmp(emp1.name,"xxx") = =0)
break;
.ne
t
printf("Enter Designation : ");
scanf("%s", emp1.desig);
fwrite (&emp1, sizeof(emp1), 1, fd1);
}
size = ftell(fd1);
fclose(fd1);
fd2 = fopen("emprand.dat", "r");
printf("\n Enter Employee id : ");
scanf("%d", &eno);
pos = (eno - 100) * sizeof(emp2);
if (pos < size)
{
fseek(fd2, pos, 0);
fread(&emp2, sizeof(emp2), 1, fd2);
printf("Employee Name : %s\n", emp2.name);
ww
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
Enter employee details
Employee Id: 100
Enter Name ("xxx" to quit): gopal
Enter Designation: AP
ww
w.E
Employee Id: 102
Enter Name ("xxx" to quit): Raju
Enter Designation: Prof
asy
Employee Id: 103 En
Enter Name ("xxx" to quit): xxx gin
eer
Enter Employee id: 102
Employee Name: Raju ing
Designation:Prof .ne
t
RESULT
Thus random access is performed to directly obtain employee details.
w.E
REAR end the pointer is updated. Deletion is performed at the FRONT end removing the
oldest element and the pointer is updated.
asy
Applications of stack include infix to postfix conversion and evaluation of expression
in postfix form. An infix arithmetic expression can be converted into a postfix expression if
precedence of operators is known. Operators are sandwiched between operands in an infix
En
expression whereas operators appear after operands in postfix form. Expression in postfix
form is evaluated by applying operators on operands to its immediate left.
gin
eer
ing
.ne
t
EX. NO. 13
DATE:
IMPLEMENTATION OF STACK USING LINKED LIST
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
ww 5. Accept choice
6. If choice = 1 then
w.E
7. Create a new node with data
8. Make new node point to first node
9. Make head node point to new node
10. If choice = 2 then
asy
11. Make temp node point to first node
En
12. Make head node point to next of temp node
13. Release memory
14. If choice = 3 then
gin
15. Display stack elements starting from head node till null
16. Stop
eer
ing
.ne
t
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
void main()
{
ww
int ch = 0;
int k;
struct node *h, *temp, *head;
w.E
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
asy
printf("\n Stack using Linked List \n");
printf("1->Push ");
En
printf("2->Pop ");
printf("3->View");
gin
eer
printf("4->Exit \n");
printf("Enter your choice : ");
ing
scanf("%d", &ch);
switch(ch)
{
case 1:
.ne
t
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:
h = head->next;
head->next = h->next;
printf("Node %s deleted\n", h->label);
free(h);
break;
case 3:
printf("\n HEAD -> ");
h = head;
while(h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");
break;
case 4:
exit(0);
}
}
}
ww
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
Stack using Linked List
1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 23
ww
Enter label for new node : 34
w.E
Stack using Linked List
1->Push 2->Pop
asy 3->View 4->Exit
Enter your choice : 3
HEAD -> 34 -> 23 -> NULL En
gin
eer
ing
.ne
t
RESULT
Thus operations of a stack were demonstrated using linked list.
EX. NO. 14
DATE:
IMPLEMENTATION OF QUEUE USING LINKED LIST
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
ww 5. Accept choice
6. If choice = 1 then
w.E
7. Create a new node with data
8. Make new node point to first node
9. Make head node point to new node
10. If choice = 2 then
asy
11. Make temp node point to first node
En
12. Make head node point to next of temp node
13. Release memory
14. If choice = 3 then
gin
15. Display stack elements starting from head node till null
16. Stop
eer
ing
.ne
t
ww
int ch=0;
int k;
struct node *h, *temp, *head;
w.E
head = (struct node*) malloc(sizeof(struct node)); head->next
= NULL;
while(1)
{
asy
printf("\n Queue using Linked List \n");
printf("1->Insert ");
En
printf("2->Delete ");
printf("3->View ");
gin
eer
printf("4->Exit \n");
printf("Enter your choice : ");
ing
scanf("%d", &ch);
switch(ch)
{
case 1:
.ne
t
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
h = head;
while (h->next != NULL)
h = h->next;
h->next = temp;
temp->next = NULL;
break;
case 2:
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);
}
ww
}
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
Queue using Linked List
1->Insert 2- >Delete 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 12
ww
w.E
Queue using Linked List
1->Insert 2->Delete 3->View 4->Exit Enter your choice : 3
HEAD -> 12 -> 23 -> NULL
asy
En
gin
eer
ing
.ne
t
RESULT
Thus operations of a Queue were demonstrated using linked list.
EX. NO. 15
DATE:
CONVERSION OF INFIX TO POSTFIX EXPRESSION
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
ww 5. If character is an operator
6. Compare the operator’s priority with the stack[top] operator.
w.E
7. If the stack [top] operator has higher or equal priority than the input
8. operator,
9. Pop it from the stack and print it
10. Else
asy
11. Push the input operator onto the stack
En
12. If character is a left parenthesis, then push it onto the stack.
13. If the character is a right parenthesis, pop all the operators from the stack and print it
gin
14. Until a left parenthesis is encountered. Do not print the parenthesis.
15. Stop
eer
ing
.ne
t
ww
{
case '+':
case '-':
return 2;
break; w.E
case '*':
case '/':
return 4;
asy
break;
En
case '^':
case '$':
gin
eer
return 6;
break;
ing
case '(':
case ')':
case '#':
return 1;
.ne
t
break;
} }
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
break;
default:
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)
ww
{
postfix[j] = symbol;
j++;
}
else
w.E
{
if(symbol == '(') asy
push(symbol);
else if(symbol == ')') En
{
while(stack[top] != '(') gin
{
postfix[j] = pop(); eer
j++;
} ing
pop();
} .ne
else
{
if(prcd(symbol) > prcd(stack[top]))
t
push(symbol);
else
{
while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top] != '#')
{
postfix[j] = pop();
j++;
}
postfix[j] = '\0';
}
void main()
{
char infix[20],postfix[20];
clrscr();
ww
printf("Enter the valid infix string: ");
gets(infix);
w.E
convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
} asy
void push(char item)
{ En
top++;
stack[top] = item; gin
}
char pop() eer
{
char a; ing
a = stack[top];
top--; .ne
return a;
} t
OUTPUT
Enter the valid infix string: (a+b*c)/(d$e)
The corresponding postfix string is: abc*+de$/
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus the given infix expression was converted into postfix form using stack.
EX. NO: 16
DATE:
EVALUATION OF POSTFIX EXPRESSION
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
w.E
7. Pop topmost two elements from stack.
8. Apply operator on the elements and push the result onto the stack,
asy
9. Eventually only result will be in the stack at end of the expression.
10. Pop the result and print it.
11. Stop
En
gin
eer
ing
.ne
t
ww
int i;
clrscr();
s.top = -1;
w.E
printf("\n\n Enter the postfix expression: ");
gets(pf);
for(i=0; pf[i]!='\0'; i++)
{
asy
switch(pf[i])
{
En
case '0':
case '1':
gin
case '2':
case '3':
eer
case '4':
case '5':
ing
case '6':
case '7':
.ne
case '8':
case '9':
s.a[++s.top] = pf[i]-'0';
break;
t
case '+':
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;
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]);
getch();
ww
}
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
Enter the postfix expression: 6523+8*+3+*
Expression value is 288.00
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus the given postfix expression was evaluated using stack.
SORTING
Sorting algorithms take input an unsorted array and number of array elements says n.
Sorting is basically based on comparison. Each stage in a sorting algorithm is called a pass.
Bubble sort is an older, easier and inefficient sorting algorithm. It works by
comparing each element of the array with the element next to it and swapping if required.
After each pass, smaller values are bubbled to top of the list.
Insertion sort is one of the simplest algorithms. It consists of n-1 passes. For any pass
p, elements in positions 1 through p are in sorted order. In pass p, the p th element left is
moved until its correct place is found among the first p elements.
Shell sort works by comparing elements that are distant. The distance between
comparisons decreases as the algorithm runs until the last phase, in which adjacent elements
are compared. Shell sort uses a sequence, h1, h2, ht, called the increment sequence. After a
ww
phase, using some increment hk, all elements spaced hk apart are sorted.
w.E
Merge sort algorithm merges two sorted lists. It is a recursive algorithm, where in
merge sort is recursively applied to both halves of the original list. It is a classic divide-and-
conquer strategy. Once the subsets are sorted, entries in both sets are compared, and
asy
whichever is less is put on to merged list.
Quick sort is the fastest known sorting algorithm. Like merge sort, quick sort is a
En
divide-and-conquer recursive algorithm. It is based on selection of pivot element. Original list
is partitioned with elements less than pivot and elements greater than pivot.
gin
Selection sort is a very simple algorithm. It determines the minimum and swaps it
with the element at the index where it is supposed to be. The process is repeated such that nth
eer
minimum of the list is swapped with the element at n-1th index of the array.
ing
.ne
t
EX. NO. 17
DATE:
ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Select an pivot element x from Ai
ww 5.
6.
Divide the array into 3 sequences: elements < x, x, elements > x
Recursively quick sort both sets (Ai < x and Ai > x)
7.
8. w.E
Display the sorted array elements
Stop
asy
En
gin
eer
ing
.ne
t
ww
scanf("%d", &arr[i]);
qsort(arr,0,size-1);
printf("\n Quick sorted elements \n");
w.E
for(i=0; i<size; i++)
printf("%d\t", arr[i]);
getch();
}
asy
void qsort(int arr[20], int fst, int last)
{
En
int i, j, pivot, tmp;
if(fst < last)
gin
eer
{
pivot = fst;
ing
i = fst;
j = last;
while(i < j)
{
.ne
t
while(arr[i] <=arr[pivot] && i<last)
i++;
while(arr[j] > arr[pivot])
j--;
if(i <j )
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
tmp = arr[pivot];
arr[pivot] = arr[j];
arr[j] = tmp;
qsort(arr, fst, j-1);
ww
w.E
asy
En
gin
eer
ing
.ne
t
OUTPUT
Enter total no. of the elements: 8
Enter total 8 elements:
1
2
7
-1
0
4
ww
-2
3
w.E
Quick sorted element
-2 -1 0 1 asy
2 3 4 7
En
gin
eer
ing
.ne
t
RESULT
Thus an array was sorted using quick sort’s divide and conquers method.
EX. NO. 18
DATE:
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
ww 5.
6.
Recursively sort the sub-arrays
Display both sorted sub-arrays
w.E
asy
En
gin
eer
ing
.ne
t
ww
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
w.E
printf("\n Merge sorted list : ");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}
asy
En
void part(int arr[], int min, int max)
{
int mid;
gin
eer
if(min < max)
{
ing
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid+1, max);
merge(arr, min, mid, max);
.ne
t
}
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;
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)
ww
{
for(k=m; k<=max; k++)
{
w.E
tmp[i] = arr[k];
i++;
}
} asy
else
{ En
for(k=j; k<=mid; k++)
{ gin
tmp[i] = arr[k];
i++; eer
}
} ing
for(k=min; k<=max; k++)
arr[k] = tmp[k]; .ne
}
t
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
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus array elements were sorted using merge sort's divide and conquer method.
SEARCHING
Searching is the process of locating a particular element in an array. The two
searching techniques are:
1. Linear search
2. Binary search
Linear search involves each element to be compared against the key value starting
from the first element. Linear search uses a “for” structure containing an “if” structure to
compare each element of an array with a search key. If search key is not found, then value of
–1 is returned. If the array being searched is not in any particular order, then half the elements
of an array are likely to compared.
Binary search algorithm locates the middle element and compares with search key. If
ww
they are equal, the search key has been found and the subscript of that element is returned. If
the search key is less than the middle array element, the first half of the array is searched;
w.E
otherwise, the second half of the array is searched.
The binary search continues until the search key is equal to the middle element of a
sub array or until the sub array consists of one element that is not equal to the search key.
asy
After each comparison, the binary search algorithm eliminates half of the elements in the
array being searched.
En
gin
eer
ing
.ne
t
EX. NO. 19
DATE:
ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0, 1, 2…n–1
4. Read search value
ww 5. Assign 0 to found
6. Check each array element against search
w.E
7. If Ai = search then
8. found = 1
asy
9. Print "Element found"
10. Print position i
11. Stop
12. If found = 0 then
En
13. print "Element not found"
gin
eer
ing
.ne
t
ww
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;
w.E
for(i=0; i<n; i++)
{
if (a[i] == val)
{
asy
printf("Element found at position %d", i);
found = 1;
En
break;
}
gin
eer
}
if (found == 0)
ing
printf("\n Element not found");
getch();
}
.ne
t
OUTPUT
Enter number of elements: 7
Enter Array Elements:
23 6 12 5 0 32 10
Enter element to locate: 5
Element found at position 3
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus an array was linearly searched for an element's existence.
EX. NO. 20
DATE:
ALGORITHM
1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located
w.E
7. Determine middle element mid = (upper+lower)/2 If key = arr[mid] then
8. Print mid
asy
9. Stop
10. Else if key > arr[mid] then
11. lower = mid + 1
12. else
En
13. upper = mid – 1
14. Print "Element not found"
gin
eer
15. Stop
ing
.ne
t
ww
printf("\n Enter element to locate : ");
scanf("%d", &val);
upper = n;
lower = 0;
found = -1;
w.E
while (lower <= upper)
{ asy
mid = (upper + lower)/2;
att++; En
if (a[mid] == val)
{ gin
eer
printf("Found at index %d in %d attempts", mid, att);
found = 1;
break;
} ing
else if(a[mid] > val)
upper = mid - 1; .ne
else
lower = mid + 1;
}
t
if (found == -1)
printf("Element not found");
}
OUTPUT
Enter array size : 10
Elements in Sorted Order
0 2 4 6 8 10 12 14 16 18
Enter element to locate : 16
Found at index 8 in 2 attempts
ww
w.E
asy
En
gin
eer
ing
.ne
t
RESULT
Thus an element is located quickly using binary search method