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

Cs6212 Programming and Data Structure Lab

The document is a lab manual for a programming and data structures course. It outlines the course objectives of making students familiar with C programming and implementing abstract data types. It then lists 20 programming assignments that students must complete covering topics like conditional statements, arrays, structures, linked lists, file handling, stacks, queues, sorting, and searching algorithms.

Uploaded by

Pinky Saran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Cs6212 Programming and Data Structure Lab

The document is a lab manual for a programming and data structures course. It outlines the course objectives of making students familiar with C programming and implementing abstract data types. It then lists 20 programming assignments that students must complete covering topics like conditional statements, arrays, structures, linked lists, file handling, stacks, queues, sorting, and searching algorithms.

Uploaded by

Pinky Saran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

Dharmapuri – 636 703

LAB MANUAL
For more Visit : www.EasyEngineering.net

ww Regulation : 2013

w.E
Branch : B.E. – CSE
Year & Semester asy : I Year / II Semester

CS6212- PROGRAMMING AND DATA En


STRUCTURES LABORATORY I gin
eer
ing
.ne
t

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 1


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

ANNA UNIVERSITY CHENNAI

REGULATION-2013

CS6212 PROGRAMMING AND DATA STRUCTURES LABORATORY I

OBJECTIVES:
The students should be made to:

 Be familiar with c programming


 Be exposed to implementing abstract data types

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 2


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

INDEX

SIGNATURE
S.NO DATE NAME OF THE PROGRAM OF THE REMARKS
FACULTY
CONDITIONAL AND CONTROL STATEMENTS

1 Implementation of Simple Calculator


2 Generation of Prime Number
3 Summation of N Digits
4 Generation of Fibonacci Series
FUNCTIONS , ARRAYS, STRINGS & POINTERS

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 3


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

CONDITIONAL AND CONTROL STATEMENTS


The “if” statement is a two-way decision making statement. If a condition holds true,
then corresponding true-block is executed; otherwise false-block is executed. The “else” part
of an if statement is optional.

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.

The “while” is an entry-controlled loop, i.e., the condition is evaluated first. If


condition is true then body of the loop is executed. The loop is executed repeatedly until the

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 4


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 5


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (IMPLEMENTATION OF SIMPLE CALCULATOR)

#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();
}

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 6


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 7


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

ww 4. Loop k in the range 2 to j/2


5. Check if divisor exists

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 8


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (GENERATION OF PRIME NUMBER)

#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();
}

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 9


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 10


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 11


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (SUMMATION OF N DIGITS)


#include <stdio.h>
#include <conio.h>
main()
{
int n, d, sum;
clrscr();
printf("Enter the numbers : ");
scanf("%d", &n);
sum = 0;
while(n)
{

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 12


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 13


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 14


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (GENERATION OF FIBONACCI SERIES)


#include <stdio.h>
#include <conio.h>
void main()
{
int i, n;
long f1, f2, f3;
clrscr();
f1 = 0;
f2 = 1;
printf("Enter number of terms : ");
scanf("%d", &n);

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 15


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 16


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

ARRAYS, STRINGS, POINTERS AND FUNCTIONS


A function is a block of code which is used or to achieve a specific task. Functions
facilitate top-down modular programming and avoid code redundancy. When functions are
used in a program, its prototype must be declared. Prototype specifies return type, function
name, number and type of arguments that the function may take. “void” is used as return
type, if the function does not return a value. Parameters can be passed to function either as
value or reference (address). A function that calls itself is called recursive function.
An array is a collection of homogeneous elements i.e., of the same data-type. When
an array is declared a contiguous memory is allocated. Array index always start with zero and
the last index is size-1. Arrays can be either one dimensional or two dimensional. Array can
be passed as an argument to a function only by reference. Memory allocation using arrays are
static whereas using functions such as “malloc” is dynamic.
ww String is a sequence of characters terminated by a null character '\0'. String is declared

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).

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 17


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 18


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (FACTORIAL OF N NUMBER USING RECURSION)


#include <stdio.h>
#include <conio.h>
long factorial(int);
void main ()
{
int n;
long f;
clrscr();
printf("Enter a number : ");
scanf("%d", &n);
f = factorial(n);

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 19


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 20


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 21


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (MAXIMUM OF N NUMBERS USING ARRAY)


#include <stdio.h>
#include <conio.h>
void main()
{
int a[10];
int i, max, n;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter Array Elements \n");
for(i=0; i<n; i++)

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 22


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 23


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

ww 4. If np then print "Multiplication not possible" and Stop


5. Read matrix A elements Aij

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 24


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (COMPUTATION OF MATRIX MULTIPLICATION)


#include <stdio.h>
#include <conio.h>
main()
{
int a[10][10], b[10][10], c[10][10]; int r1, c1, r2, c2; inti,
j, k;
clrscr();
printf("Enter order of matrix A : ");
scanf("%d%d", &r1, &c1);
printf("Enter order of matrix B : ");
scanf("%d%d", &r2, &c2);

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];
}
}

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 25


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

}
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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 26


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 27


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

ww 5. Compare str and rev using strcmp function


6. If outcome = 0 then

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 28


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (DETERMINATION OF PALINDROME)


#include <string.h>
#include <stdio.h>
#include <conio.h>
void main()
{
charstr[40], rev[40];
int x;
clrscr();
printf("Enter the string: ");
scanf("%s", str);
strcpy(rev, str);

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 29


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

OUTPUT
Enter the string: malayalam
Reversed string is: malayalam
Given string is a palindrome

Enter the string: Computer


Reversed string is: retupmoC
Given string is not 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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 30


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

STRUCTURES AND LINKED LISTS


C supports a constructed (user-defined) data type known as structure, which is a
method of packing related data of different types i.e., heterogeneous elements. A single
structure may contain integer, floating-point, character, arrays and pointer elements. The
individual elements are referred as members.
Each member within a structure is assigned its own unique storage area. The amount
of memory required to store structure is sum of storage capacity of all members. Each
individual member of a structure is accessed by means of a member selector “.” operator.
Union is similar to structures. The members that compose a union all share the same
storage area. The amount of memory required is same as that required for its largest member.

ww Self-Referential structure is a structure where one of its members is a pointer to the


structure itself. Such structures are very useful in applications involving linked data structures

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 31


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

ww 3. Read number of employees n


4. Read empid, ename, and basic for n employees in an array of structure.
5. For each employee, compute

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 32


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (GENERATION OF PAYROLL APPLICATION)


#include <stdio.h>
#include <conio.h>
struct employee
{
int empid;
char name[15];
int basic;
float hra;
float da;
float it;
float gross;

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 33


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 34


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

OUTPUT
Enter No. of Employees: 2

Enter Employee Details


Enter Employee Id : 436
Enter Employee Name: Gopal
Enter Basic Salary : 10000

Enter Employee Details

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

436 Gopal 10000 200.00 100.00 500.00 10300.00 eer


***************************************************************************
9800.00
463 Rajesh 22000 440.00 220.00 1100.00 22660.00 21560.00 ing
***************************************************************************
.ne
t

RESULT
Thus payroll for employees was generated using structure.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 35


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

EX. NO: 10
DATE:

IMPLEMENTATION OF SINGLY LINKED LIST


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

ALGORITHM
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using

ww 4. Display menu on list operation


5. Accept user choice

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 36


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (IMPLEMENTATION OF SINGLY LINKED LIST)


#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
#include <string.h>
struct node
{
int label;
struct node *next;
};
void main()

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;

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 37


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

}
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;

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 38


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

while (h->next != NULL)


{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL");
break;
case 4:
exit(0);
}
}
}

ww
w.E
asy
En
gin
eer
ing
.ne
t

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 39


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

SINGLY LINKED LIST OPERATIONS


1->Add 2->Delete 3->View 4->Exit

ww
Enter your choice :1
Enter label after which new node is to be added : 23

w.E
Enter label for new node : 67

SINGLY LINKED LIST OPERATIONS asy


1->Add 2->Delete 3->View
En
4->Exit
Enter your choice :3
gin
HEAD -> 23 -> 67 -> NULL
eer
ing
.ne
t

RESULT
Thus operation on single linked list is performed.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 40


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 41


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

EX.NO: 11
DATE:

SEQUENTIAL FILE ACCESS


AIM
To create a telephone directory and to locate a user details using sequential access.

ALGORITHM
1. Start
2. Open empseq.dat file in append mode
3. Add records to the file
4. Close the file

ww 5. Open empseq.dat file in read mode


6. Get person name.

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 42


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (SEQUENTIAL FILE ACCESS)


#include <stdio.h>
#include <conio.h>
#include <string.h>
struct employee
{
char name[20];
long mno;
};
void main()
{
struct employee emp1, emp2;

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");
}

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 43


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 44


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

ww 5. Close the file


6. Open emprand.dat file in read mode

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 45


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (RANDOM FILE ACCESS)


#include <stdio.h>
#include <conio.h>
#include <string.h>
struct employee
{
Int empid;
char name[20];
char desig[20];
};
void main()
{

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 46


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

printf("Designation: %s\n", emp2.desig);


}
else
printf("\n Incorrect Employee Id \n");
fclose(fd2);
}

ww
w.E
asy
En
gin
eer
ing
.ne
t

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 47


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

OUTPUT
Enter employee details
Employee Id: 100
Enter Name ("xxx" to quit): gopal
Enter Designation: AP

Employee Id: 101


Enter Name ("xxx" to quit) : arum
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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 48


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

STACKS AND QUEUES


The stack is a list of elements placed on top of each other. A pointer always points to
the topmost position of a stack called top. The two possible operations on stack is push and
pop. It is implemented either using arrays or linked lists. The top is an indicator where both
push and pop operations are performed. CDs in a disc spindle are an example of stack.
The insertion operation is termed as push. For each insertion the pointer top is
incremented so that it retains the top-most position in the stack. The deletion operation of
stack is termed as pop. Stack follows LIFO (Last In First Out) method i.e., the last inserted
element would be the first element to be deleted. The pointer top is made to point the next
element in order.
In a Queue, the set of elements are placed one after another, just like people standing
in a queue at a reservation counter. In a Queue, there are two pointers namely front and rear.
Pointer “front” points the first element and “rear” the last element in the Queue.
ww Queue is represented as FIFO (First In First Out). Insertions are carried out at the

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 49


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 50


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (IMPLEMENTATION OF STACK USING LINKED LIST)

#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 -> ");

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 51


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 52


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

OUTPUT
Stack using Linked List
1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 23

Stack using Linked List


1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 53


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 54


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (IMPLEMENTATION OF QUEUE USING LINKED LIST)


#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 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;

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 55


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 56


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

OUTPUT
Queue using Linked List
1->Insert 2- >Delete 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 12

Queue using Linked


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

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 57


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 58


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (CONVERSION OF INFIX TO POSTFIX EXPRESSION)


#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
int top = -1;
char stack[MAX];
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)

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;

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 59


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 60


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

}
}
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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 61


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

OUTPUT
Enter the valid infix string: (a+b*c)/(d$e)
The corresponding postfix string is: abc*+de$/

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


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

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


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

ww
w.E
asy
En
gin
eer
ing
.ne
t

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 62


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

ww 4. Read the postfix expression character-by-character


5. If character is an operand push it onto the stack
6. If character is an operator

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 63


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (EVALUATION OF POSTFIX EXPRESSION)


#include <stdio.h>
#include <conio.h>
struct stack
{
int top;
float a[50];
}s;
void main()
{
char pf[50];
float d1,d2,d3;

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 ‘*’:

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 64


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 65


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 66


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 67


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

EX. NO. 17
DATE:

SORTING N NUMBERS USING QUICK SORT


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

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements 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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 68


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM(SORTING N NUMBERS USING QUICK SORT)


#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
void main()
{
int arr[30];
int i, size;
printf("Enter total no. of the elements : ");
scanf("%d", &size);
printf("Enter total %d elements : \n", size);
for(i=0; i<size; i++)

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 69


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

qsort(arr, j+1, last);


}
}

ww
w.E
asy
En
gin
eer
ing
.ne
t

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 70


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 71


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

EX. NO. 18
DATE:

SORTING N NUMBERS USING MERGE SORT


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

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements

ww 5.
6.
Recursively sort the sub-arrays
Display both sorted sub-arrays

w.E
asy
En
gin
eer
ing
.ne
t

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 72


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (SORTING N NUMBERS USING MERGE SORT)


#include <stdio.h>
#include <conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int size;
void main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements : ");

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++)

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 73


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB 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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 74


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 75


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 76


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

EX. NO. 19
DATE:

SEARCHING AN ELEMENT USING LINEAR SEARCH


AIM
To perform linear search of an element on the given array.

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0, 1, 2…n–1
4. Read 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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 77


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (SEARCHING AN ELEMENT USING LINEAR SEARCH)


#include <stdio.h>
#include <conio.h>
void main()
{
int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter Array Elements : \n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 78


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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.

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 79


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

EX. NO. 20
DATE:

SEARCHING AN ELEMENT USING BINARY SEARCH


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

ALGORITHM
1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located

ww 5. Assign 0 to lower and n to upper


6. While (lower < upper)

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 80


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

PROGRAM (SEARCHING AN ELEMENT USING BINARY SEARCH)


#include <stdio.h>
void main()
{
int a[50],i, n, upper, lower, mid, val, found, att=0;
printf("Enter array size : ");
scanf("%d", &n);
for(i=0; i<n; i++)
a[i] = 2 * i;
printf("\n Elements in Sorted Order \n"); for(i=0; i<n; i++)
printf("%4d", a[i]);

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");
}

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 81


Visit : www.EasyEngineering.net
CS6212-PROGRAMMING AND DATA STRUCTURES LAB I

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

VVIT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 82


Visit : www.EasyEngineering.net

You might also like