Cs 6212 Manual
Cs 6212 Manual
Index
S. No
Exp. Date
Sub. Date
1a
1b
1c
1d
1e
Simple Calculator
Prime Number
Sum of Digits
Fibonacci Series
Perfect Number
Functions , Arrays, Strings & Pointers
2a
2b
2c
2d
2e
2f
2g
2h
Shape Function
Factorial Recursion
Array Maximum
Matrix Addition
Matrix Multiplication
Palindrome
Paragraph Analysis
Pass by Reference
Structures & Linked List
3a
3b
3c
Payroll Application
Team-wise Sorting
Singly Linked List
4a
4b
4c
5a
5b
5c
5d
5e
5f
6a
6b
6c
6d
6e
6f
Bubble Sort
Quick Sort
Merge Sort
Shell Sort
Insertion Sort
Selection Sort
File Handling
Sorting Algorithms
7a
7b
cseannauniv.blogspot.in
Linear Search
Binary search
Vijai Anand
CS6212PDS Lab I
Conditional 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 condition holds true. Minimum number of times the loop executed is 0.
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.
The for statement is an entry and counter controlled loop. It contains three
parts 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 variable is incremented/decremented each time before testing the
condition.
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.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 1a
SIMPLE CALCULATOR
Date:
Aim
To implement a simple calculator using switch case statement.
Algorithm
Start
Display calculator menu
Read the operator symbol and operands n1, n2
If operator = + then
calculate result = n1 + n2
Else if operator = then
calculate result = n1 n2
Else if operator = * then
calculate result = n1 * n2
Else if operator = / then
calculate result = n1 / n2
Else if operator = % then
calculate result = n1 % n2
Else
print "Invalid operator"
Print result
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Program
/* 1a - Simple Calculator using switch */
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
main()
{
int n1, n2, result;
char op;
clrscr();
printf("\n Simple Calculator");
printf("\n + Summation");
printf("\n - Difference");
printf("\n * Product");
printf("\n / Quotient");
printf("\n % Remainder");
printf("\n Enter the operator : ");
op = getchar();
printf("Enter operand1 and operand2 : ");
scanf("%d%d",&n1,&n2);
switch(op)
{
case '+':
result = n1 +n2;
break;
case '-':
result = n1 - n2;
break;
case '*':
result = n1 * n2;
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();
}
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Output
Simple Calculator
+ Summation
- Difference
* Product
/ Quotient
% Remainder
Enter the operator : Enter operand1 and operand2 : 2 4
2 - 4 = -2
Simple Calculator
+ Summation
- Difference
* Product
/ Quotient
% Remainder
Enter the operator : %
Enter operand1 and operand2 : 5 2
5 % 2 = 1
Result
Thus simple calculator functionality was executed using menu-oriented
approach.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 1b
PRIME NUMBER
Date:
Aim
To print first 'n' numbers using for loop.
Algorithm
Start
Read the value of n
Loop j to generate numbers from 2 to 10000
Loop k in the range 2 to j/2
Check if divisor exists
If j%k = 0 then
Examine next j
If there are no divisor for j then
Print j
Increment i by 1
If i = n then
Stop
Else
Examine next j
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Program
/* 1b - First N prime number */
#include <stdio.h>
#include <conio.h>
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++)
{
flg = 0;
for(k=2; k<=j/2; k++)
{
if (j%k == 0)
{
flg = 1;
break;
}
}
if (flg == 0)
{
printf("%d ", j);
i++;
}
if (i == n)
break;
}
getch();
}
Output
Enter value for n : 9
Prime numbers : 2 3 5
11
13
17
19 23
Result
Thus first set of prime numbers is displayed.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 1c
SUM OF DIGITS
Date:
Aim
To find the sum of the digits of a given number using while statement.
Algorithm
Start
Read num
Initialize sum to 0.
Repeat until num = 0
Obtain last digit d = num % 10
Add d to sum
num = num / 10
Print sum
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Program
/* 1c - Sum of digits in a given number */
#include <stdio.h>
#include <conio.h>
main()
{
int n, d, sum;
clrscr();
printf("Enter a number : ");
scanf("%d", &n);
sum = 0;
while(n)
{
d = n % 10;
sum = sum + d;
n = n / 10;
}
printf("Sum of digits : %d", sum);
getch();
}
Output
Enter a number : 58349
Sum of digits : 29
Result
Thus digits of the given number were summed up.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 1d
10
FIBONACCI SERIES
Date:
Aim
To print first N terms of the Fibonacci series assuming the first two terms as 0
and 1
Algorithm
Start
Read no. of terms n
Initialize f1 to 0 and f2 to 1.
Print f1 and f2
Initialize i to 3
Repeat until i < n
Generate next term f3 = f1 + f2
Print f3
f1 = f2
f2 = f3
Increment i by 1
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
11
Program
/* 1d - Fibonacci Series */
#include <stdio.h>
#include <conio.h>
main()
{
int i, n;
long f1, f2, f3;
clrscr();
f1 = 0;
f2 = 1;
printf("Enter number of terms : ");
scanf("%d", &n);
printf("\n Fibonacci series \n");
printf("%ld \n %ld \n",f1,f2);
for(i=3; i<=n; i++)
{
f3 = f1 + f2;
printf("%ld ",f3);
f1 = f2;
f2 = f3;
}
getch();
}
Output
Enter number of terms : 10
Fibonacci series
0 1 1 2 3 5 8 13 21 34
Result
Thus first n terms of Fibonacci series was generated.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 1e
12
PERFECT NUMBER
Date:
Aim
To find whether the given number is a perfect number or not.
Algorithm
Start
Read number n
Initialize sum to 0
Loop i from 1 to n-1
Add the divisors
If n%i = 0 then
sum = sum + i
If sum = n then
Print "Perfect Number"
Else
Print "Not Perfect Number"
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
13
Program
/* 1e - Perfect No : Sum of divisors : 6 = 2+3+1 */
#include <stdio.h>
#include <conio.h>
main()
{
int n, i, sum=0;
clrscr();
printf("Enter any number : ");
scanf("%d", &n);
for(i=1; i<n; i++)
{
if (n%i == 0)
sum += i;
}
if (sum == n)
printf("It is a perfect number");
else
printf("It is not a perfect number");
getch();
}
Output
Enter any number : 6
It is a perfect number
Result
Thus whether a given number is perfect or not is determined.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
14
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 2a
15
SHAPE FUNCTION
Date:
Aim
To invoke functions that compute areas of different shapes using switch case
conditional statement.
Algorithm
Start
Display shape menu
Read choice
If choice = 1 then
Read side
Call square(side)
Else if choice = 2 then
Read radius
Call circle(radius)
Else if choice = 3 then
Read base, height
Call triangle(base, height)
Else if choice = 4 then
Read length, breadth
Call rectangle(length, breadth)
Else
print "Invalid choice"
Print area
Stop
Function square (s)
Compute area = s2
Return area
Function circle (r)
Compute area = r2
Return area
Function triangle (b,h)
Compute area = bh
Return area
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
16
Program
/* 2a - Area of shapes using functions */
#include <stdio.h>
#include <conio.h>
#define pi 3.14
/* Function prototypes */
float square(float);
float circle(float);
float triangle(float, float);
float rectangle(float, float);
main()
{
int choice;
float side, radius, base, height, length, breadth, area;
clrscr();
printf("Area of Shapes \n");
printf("1.Square ");
printf("2.Circle ");
printf("3.Triangle ");
printf("4.Rectangle \n");
printf("Enter choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter side : ");
scanf("%f", &side);
area = square(side);
break;
case 2:
printf("Enter radius : ");
scanf("%f", &radius);
area = circle(radius);
break;
case 3:
printf("Enter base and height : ");
scanf("%f%f", &base, &height);
area = triangle(base, height);
break;
case 4:
printf("Enter length and breadth : ");
scanf("%f%f", &length, &breadth);
area = rectangle(length, breadth);
break;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
17
default:
printf("\n Invalid choice \n");
exit(0);
}
printf("Area : %5.2f", area);
getch();
}
float square(float s)
{
float a;
a = s * s;
return(a);
}
float circle(float r)
{
float a;
a = pi * r * r;
return(a);
}
float triangle(float b, float h)
{
float a;
a = 0.5 * b * h;
return(a);
}
float rectangle(float l, float b)
{
float a;
a = l * b;
return(a);
}
Output
Area of Shapes
1.Square 2.Circle
Enter choice : 1
Enter side : 4.3
Area : 18.49
3.Triangle
4.Rectangle
Result
Thus areas of various shapes was computed using function.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 2b
18
FACTORIAL RECURSION
Date:
Aim
To find the factorial of a number using recursive function.
Algorithm
Start
Read the value of n
Call function factorial(n)
Print return value
Stop
Function factorial (n)
If n=1 then return 1
Else return n*factorial(n-1)
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
19
Program
/* 2b - Factorial using recursion */
#include <stdio.h>
#include <conio.h>
long factorial(int);
main()
{
int n;
long f;
clrscr();
printf("Enter a number : ");
scanf("%d", &n);
f = factorial(n);
printf("Factorial value : %ld", f);
getch();
}
long factorial(int n)
{
if (n <= 1)
return(1);
else
return (n * factorial(n-1));
}
Output
Enter a number : 6
Factorial value : 720
Enter a number : 12
Factorial value : 479001600
Result
Thus factorial value of a given number was obtained through recursive function
call.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 2c
20
ARRAY MAXIMUM
Date:
Aim
To find the greatest of N numbers stored in an array.
Algorithm
Start
Read number of array elements as n
Read array elements Ai, i = 0,1,2,n1
Assume first element A0 to be max
Compare each array element Ai with max
If max <Ai then max = Ai
Print max
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
21
Program
/* 2c - Maximum of an array */
#include <stdio.h>
#include <conio.h>
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++)
scanf("%d", &a[i]);
max = a[0];
for(i=1; i<n; i++)
{
if (max < a[i])
max = a[i];
}
printf("Maximum value = %d ", max);
getch();
}
Output
Enter number of elements : 6
Enter Array Elements
3
8
-7
11
-9
0
Maximum value = 11
Result
Thus maximum element of an array was determined.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
22
Ex. No. 2d
MATRIX ADDITION
Date:
Aim
To add the given matrices using function.
Algorithm
Start
Read the order of matrices as m and n
Read matrix A elements Aij
Read matrix B elements Bij
Call function addmatrix (A, B, C, m, n)
Print matrix Cij,
Stop
Function addmatrix (a, b, c, r, c)
Compute resultant matrix by adding corresponding elements
Cij = Aij + Bkj
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
23
Program
/* 2d - Matrix addition using function */
#include <stdio.h>
#include <conio.h>
void add(int m1[5][5],int m2[5][5],int m3[5][5],int r,int c)
{
int i, j;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
m3[i][j] = m1[i][j] + m2[i][j];
}
}
}
main()
{
int a[5][5], b[5][5], c[5][5];
int i, j, row, col;
clrscr();
printf("\nEnter order for matrix : ");
scanf("%d%d",&row,&col);
printf("\nEnter elements for A matrix\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter elements for B matrix\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&b[i][j]);
}
}
add(a, b, c, row, col);
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
24
Output
Enter order for matrix : 2 2
Enter elements for A matrix
1 1
1 1
Enter elements for B matrix
2 2
3 4
Contents of C matrix
3 3
4 5
Result
Thus the given matrices were added.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 2e
25
MATRIX MULTIPLICATION
Date:
Aim
To compute product of two matrices using two dimensional array.
Algorithm
Start
Read the order of matrix A as m and n
Read the order of matrix B as p and q
If n
i < m, 0
j < q and 0
k<
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
26
Program
/* 2e - 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
scanf("%d%d",
printf("Enter
scanf("%d%d",
if (c1 != r2)
{
printf("Matrix multiplication not possible");
getch();
exit(0);
}
printf("Enter matrix A elements\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter matrix B elements\n");
for(i=0; i<r2; i++)
{
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;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
27
Output
Enter order of
Enter order of
Enter matrix A
1 1 1
1 1 1
Enter matrix B
2 2
2 2
2 2
Product matrix
6
6
6
6
matrix A : 2 3
matrix B : 3 2
elements
elements
Result
Thus product of given two matrices was obtained using arrays.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 2f
28
PALINDROME
Date:
Aim
To determine whether the input string is palindrome using string handling
functions.
Algorithm
Start
Read the string, say str
Copy stronto revusing strcpy function
Reverse rev using strrev function
Compare str and revusing strcmp function
If outcome = 0 then
Print "Given string is palindrome"
Else
Print "Given string is not palindrome"
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
29
Program
/* 2f - Palindrome using string functions */
#include <string.h>
#include <stdio.h>
#include <conio.h>
main()
{
charstr[40], rev[40];
int x;
clrscr();
printf("Enter the string: ");
scanf("%s", str);
strcpy(rev, str);
strrev(rev);
printf("Reversed string is: %s \n",rev);
x = strcmpi(str, rev);
if (x == 0)
printf("Given string is a palindrome");
else
printf("Given string is not a palindrome");
getch();
}
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
Result
Thus the given input string is checked for palindrome using string handling
functions.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 2g
30
PARAGRAPH ANALYSIS
Date:
Aim
To accept a line of text and to print the number of vowels, consonants,
digits and whitespaces.
Algorithm
Start
Read paragraph using gets function.
Convert text to lower case
Assign 0 to vow, dig, con, ws
Consider each character
If character is a vowel then increment vow
Else if character is a digit then increment dig
Else if character is a space then increment ws
Else increment con
Print vow, dig, con, ws
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
31
Program
/* 2g - Paragraph statistics */
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char str[80];
int i, j, len, vow, ws, dig, con, pun;
clrscr ();
printf("Enter a paragraph : \n");
gets(str);
len = strlen(str);
strlwr(str);
vow = ws = dig = con = pun = 0;
for(i=0; i<len; i++)
{
switch (str[i])
{
case ' ' :
ws++;
break;
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
vow++;
break;
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
dig++;
break;
case '.' :
case ',' :
pun++;
break;
default:
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
32
con++;
}
}
printf("\n
printf("\n
printf("\n
printf("\n
getch();
Output
Enter a paragraph :
I am a fine. Bye 123.
Vowel count : 6
Consonant count : 5
Digit count : 3
Whitespace count : 5
Result
Thus statistics of the given paragraph was determined.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 2h
33
PASS BY REFERENCE
Date:
Aim
To demonstrate parameters passing to a function by reference.
Algorithm
Start
Read values of a and b
Print a and b
Call swapref function with address of a and b
Print a and b
Stop
Function swapref (x, y)
Assign value pointed by variable x to a temporary variable t
Assign value pointed by variable y to value pointed by variable x
Assign value t to value pointed by variable y
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
34
Program
/* 2h - Pass by value and reference */
#include <stdio.h>
#include <conio.h>
void swapref(int *,int *);
main()
{
int a, b;
clrscr();
printf("Enter value for A: ");
scanf("%d", &a);
printf("Enter value for B: ");
scanf("%d", &b);
swapref(&a, &b);
printf("\n Values after Pass by Reference \n");
printf("Value of A : %d \n", a);
printf("Value of B : %d", b);
getch();
}
/* Pass by Reference*/
void swapref(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
Output
Enter value for A : 10
Enter value for B : 20
Values after Pass by Reference
Value of A : 20
Value of B : 10
Result
Thus values of variables were exchanged by passing parameters by reference.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
35
Doubly linked list node contains an additional pointer that contains address of
the previous node in the list. Both forward and backward traversal is possible in a
doubly linked list.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 3a
36
PAYROLL APPLICATION
Date:
Aim
To generate employee payroll for anorganization using structure.
Algorithm
Start
Define employee structure with fields empid, ename, basic, hra, da, it, gross and
netpay
Read number of employees n
Read empid, ename, and basic for n employees in an array of structure.
For each employee, compute
hra = 2% of basic
da = 1% of basic
gross = basic + hra + da
it = 5% of basic
netpay = gross - it
Print empid, ename, basic, hra, da, it, gross and netpay for all employees
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
37
Program
/* 3a - Payroll Generation */
#include <stdio.h>
#include <conio.h>
struct employee
{
int empid;
char name[15];
int basic;
float hra;
float da;
float it;
float gross;
float netpay;
};
main()
{
struct employee emp[50];
inti, j, n;
clrscr();
printf("\n Enter No. of Employees : ");
scanf("%d", &n);
for(i=0; i<n ;i++)
{
printf("\n Enter Employee Details\n");
printf("Enter Employee Id
: ");
scanf("%d", &emp[i].empid);
printf("Enter Employee Name : ");
scanf("%s", emp[i].ename);
printf("Enter Basic Salary : ");
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;
}
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
38
Output
Enter No. of Employees : 2
Enter
Enter
Enter
Enter
Employee Details
Employee Id
: 436
Employee Name :Gopal
Basic Salary : 10000
Enter
Enter
Enter
Enter
Employee Details
Employee Id
: 463
Employee Name :Rajesh
Basic Salary : 22000
Gopal
Rajesh
10000
22000
200.00
440.00
100.00
220.00
500.00 10300.00
1100.00 22660.00
9800.00
21560.00
********************************************************************************
Result
Thus payroll for employees was generated using structure.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
EX. 3B.
39
TEAM-WISE SORTING
Date:
Aim
To define a structure for a cricket player and to print a team wise list containing
names of players with their batting average.
Algorithm
Start
Define crickete structure with fields pcode, pname, tname, and bavg
Read number of players n
Read details of each player in an array of structure.
Sort player structure according to team name.
Print players details
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
40
Program
/* 3b - Cricket Statistics */
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct cricket
{
int plcode;
char name[15];
char tname[15];
float btavg;
};
main()
{
struct cricket player[50], temp;
int i, j, n;
clrscr();
printf("\n Enter No. of Players : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("\nEnter Player Details\n");
printf("Enter player code : ");
scanf("%d", &player[i].plcode);
printf("Enter player name : ");
scanf("%s", player[i].name);
printf("Enter team name : ");
scanf("%s", player[i].tname);
printf("Enter batting average : ");
scanf("%f", &player[i].btavg);
}
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if (strcmp(player[i].tname, player[j].tname) > 0)
{
temp = player[i];
player[i] = player[j];
player[j] = temp;
}
}
}
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
41
Output
Enter No. of Players : 6
Enter
Enter
Enter
Enter
Enter
Player Details
player code : 23
player name : Dhoni
team name : CSK
batting average : 45.23
Enter
Enter
Enter
Enter
Enter
Player Details
player code : 34
player name : Maxwell
team name : PW
batting average : 67.2
Enter
Enter
Enter
Enter
Enter
Player Details
player code : 17
player name : Raina
team name : CSK
batting average : 85
P.Code
17
23
34
Bat. Avg
85.00
45.23
67.20
Result
Thus players details were sorted team-wise and printed.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
EX. 3C
42
Date:
Aim
To define a singly linked list node and perform operations such as insertions and
deletions dynamically.
Algorithm
Start
Define single linked list node as self referential structure
Create Head node with label = -1 and next = NULL using
Display menu on list operation
Accept user choice
If choice = 1 then
Locate node after which insertion is to be done
Create a new node and get data part
Insert the new node at appropriate position by manipulating address
Else if choice = 2
Get node's data to be deleted.
Locate the node and delink the node
Rearrange the links
Else
Traverse the list from Head node to node which points to null
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
43
Program
/* 3c - Single Linked List */
#include
#include
#include
#include
#include
<stdio.h>
<conio.h>
<process.h>
<alloc.h>
<string.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch, fou=0;
int k;
struct node *h, *temp, *head, *h1;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->label = -1;
head->next = NULL;
while(-1)
{
clrscr();
printf("\n\n SINGLY LINKED LIST OPERATIONS \n");
printf("1->Add ");
printf("2->Delete ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
/* Add a node at any intermediate location */
case 1:
printf("\n Enter label after which to add : ");
scanf("%d", &k);
h = head;
fou = 0;
if (h->label == k)
fou = 1;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
44
while(h->next != NULL)
{
if (h->label == k)
{
fou=1;
break;
}
h = h->next;
}
if (h->label == k)
fou = 1;
if (fou != 1)
printf("Node not found\n");
else
{
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
temp->next = h->next;
h->next = temp;
}
break;
/* Delete any intermediate node */
case 2:
printf("Enter label of node to be deleted\n");
scanf("%d", &k);
fou = 0;
h = h1 = head;
while (h->next != NULL)
{
h = h->next;
if (h->label == k)
{
fou = 1;
break;
}
}
if (fou == 0)
printf("Sorry Node not found\n");
else
{
while (h1->next != h)
h1 = h1->next;
h1->next = h->next;
free(h);
printf("Node deleted successfully \n");
}
break;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
45
case 3:
printf("\n\n HEAD -> ");
h=head;
while (h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL");
break;
case 4:
exit(0);
}
}
}
Output
SINGLY LINKED LIST OPERATIONS
1->Add 2->Delete 3->View 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
Enter your choice : 1
Enter label after which new node is to be added : 23
Enter label for new node : 67
SINGLY LINKED LIST OPERATIONS
1->Add 2->Delete 3->View 4->Exit
Enter your choice : 3
HEAD -> 23 -> 67 -> NULL
Result
Thus operation on single linked list is performed.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
46
File Handling
Applications require information stored on auxiliary storage device. Such
information is stored permanently as a data file that allows to access and alter 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 checked using feof function.
Random access means moving file pointer to the desired byte. Pre-defined
functions that facilitate random access are:
ftellto know current position of the file pointer
rewindto move file pointer to beginning of the file
fseekused to move the file pointer to the desired byte.
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
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.
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
command-line arguments.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
EX. 4A
47
Date:
Aim
To create a telephone directory and to locate a user details using sequential
access.
Algorithm
Start
Open empseq.dat file in append mode
Add records to the file
Close the file
Open empseq.dat file in read mode
Get person name.
Check each record one by one from the first record
If person name matches then print the details.
Close the file
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
48
Program
/* 4a - Employee file using sequential access */
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct employee
{
char name[20];
long mno;
};
main()
{
struct employee emp1, emp2;
FILE *fd1, *fd2;
char str[20];
int found = 0;
fd1 = fopen("empseq.dat", "a");
printf("\n\t Enter employee details \n");
while(1)
{
printf("\n Enter Name (\"xxx\" to quit) : ");
scanf("%s", emp1.name);
if (strcmp(emp1.name,"xxx") == 0)
break;
printf("Enter Contact No. : ");
scanf("%ld", &emp1.mno);
fwrite (&emp1, sizeof(emp1), 1, fd1);
}
fclose(fd1);
fd2 = fopen("empseq.dat", "r");
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");
}
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
49
Output
Enter employee details
Enter Name ("xxx" to quit) : vijai
Enter Contact No. : 1234
Enter Name ("xxx" to quit) : anand
Enter Contact No. : 9876
Enter Name ("xxx" to quit) : xxx
Enter Employee name to get phone no. : anand
Telephone No. : 9876
Result
Thus sequential access is performed to retrieve a person's contact details.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
EX. 4B
50
Date:
Aim
To create a address book and to locate employee details using random access.
Algorithm
Start
Open emprand.dat file in append mode
Automatically generate employee id.
Add records to the file
Close the file
Open emprand.dat file in read mode
Get employee id.
Move the file pointer to the desired record using fseek function
Print the details.
Close the file
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
51
Program
/* 4b - Employee file with random access */
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct employee
{
int empid;
char name[20];
char desig[20];
};
main()
{
struct employee emp1, emp2;
FILE *fd1, *fd2;
char str[20];
int id, eno, pos, size;
fd1 = fopen("emprand.dat", "a");
fseek(fd1, 0, 2);
size = ftell(fd1);
id = 100 + size / sizeof(emp1);
printf("\n Enter employee details \n");
while(1)
{
emp1.empid = id++;
printf("\n Employee Id : %d", emp1.empid);
printf("\n Enter Name (\"xxx\" to quit) : ");
scanf("%s", emp1.name);
if (strcmp(emp1.name,"xxx") == 0)
break;
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);
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
52
printf("Designation
: %s\n", emp2.desig);
}
else
printf("\n Incorrect Employee Id \n");
fclose(fd2);
}
Output
Enter employee details
Employee Id : 100
Enter Name ("xxx" to quit) : gopal
Enter Designation : AP
Employee Id : 101
Enter Name ("xxx" to quit) : arun
Enter Designation : ASP
Employee Id : 102
Enter Name ("xxx" to quit) : Raju
Enter Designation : Prof
Employee Id : 103
Enter Name ("xxx" to quit) : xxx
Enter Employee id : 102
Employee Name : Raju
Designation
: Prof
Result
Thus random access is performed to directly obtain employee details.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
EX. 4B
53
FILE COPY
Date:
Aim
To copy a file using sequential operations and command-line arguments.
Algorithm
Start
Open source file in read mode
Open dest file in write mode
Till end of source file
Read a character from source file
Write a character onto destination file
Print "File copied".
Close all files
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
54
Program
/* 4c - File Copy using Command Line Arguments mycp.c */
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[])
{
FILE *src, *des;
char ch;
clrscr();
if (argc != 3)
{
printf("Arguments insufficient");
exit(-1);
}
src = fopen(argv[1], "r");
if( src == NULL )
{
printf("Source File not Accessible");
exit(-1);
}
while (1)
{
ch = getc(src);
if(ch == EOF)
break;
else
putc(ch, des);
}
printf("File Copied");
fclose(src);
fclose(des);
}
Output
> mycp hello.c hello1.c
File Copied
Result
Thus file is copied using character-based sequential operation.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
55
Stack
Queue
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 5a
56
STACK ARRAY
Date:
Aim
To implement stack operations using array.
Algorithm
Start
Define a array stack of size max = 5
Initialize top = -1
Display a menu listing stack operations
Accept choice
If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top element
Decrement top
If choice = 3 then
Display stack elements starting from top
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
57
Program
/* 5a - Stack Operation using Arrays */
#include <stdio.h>
#include <conio.h>
#define max 5
static int stack[max];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return (stack[top--]);
}
void view()
{
int i;
if (top < 0)
printf("\n Stack Empty \n");
else
{
printf("\n Top-->");
for(i=top; i>=0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}
main()
{
int ch=0, val;
clrscr();
while(ch != 4)
{
printf("\n STACK
OPERATION \n");
printf("1.PUSH ");
printf("2.POP ");
printf("3.VIEW ");
printf("4.QUIT \n");
printf("Enter Choice : ");
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
58
scanf("%d", &ch);
switch(ch)
{
case 1:
if(top < max-1)
{
printf("\nEnter Stack element : ");
scanf("%d", &val);
push(val);
}
else
printf("\n Stack Overflow \n");
break;
case 2:
if(top < 0)
printf("\n Stack Underflow \n");
else
{
val = pop();
printf("\n Popped element is %d\n", val);
}
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\n Invalid Choice \n");
}
}
}
Output
STACK
OPERATION
1.PUSH 2.POP 3.VIEW
Enter Choice : 1
4.QUIT
4.QUIT
OPERATION
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
59
4.QUIT
4.QUIT
45
34
23
4.QUIT
12
STACK
OPERATION
1.PUSH 2.POP 3.VIEW
Enter Choice : 2
4.QUIT
Popped element is 45
STACK
OPERATION
1.PUSH 2.POP 3.VIEW
Enter Choice : 3
Top-->
34
23
4.QUIT
12
STACK
OPERATION
1.PUSH 2.POP 3.VIEW
Enter Choice : 4
4.QUIT
Result
Thus push and pop operations of a stack was demonstrated using arrays.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 5b
60
QUEUE ARRAY
Date:
Aim
To implement queue operations using array.
Algorithm
Start
Define a array queue of size max = 5
Initialize front = rear = 1
Display a menu listing queue operations
Accept choice
If choice = 1 then
If rear < max -1
Increment rear
Store element at current position of rear
Else
Print Queue Full
If choice = 2 then
If front = 1 then
Print Queue empty
Else
Display current front element
Increment front
If choice = 3 then
Display queue elements starting from front to rear.
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
61
Program
/* 5b - Queue Operation using Arrays */
#include <stdio.h>
#include <conio.h>
#define max 5
static int queue[max];
int front = -1;
int rear = -1;
void insert(int x)
{
queue[++rear] = x;
if (front == -1)
front = 0;
}
int remove()
{
int val;
val = queue[front];
if (front==rear && rear==max-1)
front = rear = -1;
else
front ++;
return (val);
}
void view()
{
int i;
if (front == -1)
printf("\n Queue Empty \n");
else
{
printf("\n Front-->");
for(i=front; i<=rear; i++)
printf("%4d", queue[i]);
printf(" <--Rear\n");
}
}
main()
{
int ch= 0,val;
clrscr();
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
62
while(ch != 4)
{
printf("\n QUEUE OPERATION \n");
printf("1.INSERT ");
printf("2.DELETE ");
printf("3.VIEW ");
printf("4.QUIT\n");
printf("Enter Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(rear < max-1)
{
printf("\n Enter element to be inserted : ");
scanf("%d", &val);
insert(val);
}
else
printf("\n Queue Full \n");
break;
case 2:
if(front == -1)
printf("\n Queue Empty \n");
else
{
val = remove();
printf("\n Element deleted : %d \n", val);
}
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\n Invalid Choice \n");
}
}
}
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
63
Output
QUEUE OPERATION
1.INSERT 2.DELETE
Enter Choice : 1
3.VIEW
4.QUIT
3.VIEW
4.QUIT
3.VIEW
4.QUIT
3.VIEW
4.QUIT
3.VIEW
4.QUIT
3.VIEW
4.QUIT
3.VIEW
4.QUIT
Queue Full
QUEUE OPERATION
1.INSERT 2.DELETE
Enter Choice : 3
Front-->
12
23
34
45
56
<--Rear
Result
Thus insert and delete operations of a queue was demonstrated using arrays.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 5c
64
Date:
Aim
To implement stack operations using linked list.
Algorithm
Start
Define a singly linked list node for stack
Create Head node
Display a menu listing stack operations
Accept choice
If choice = 1 then
Create a new node with data
Make new node point to first node
Make head node point to new node
If choice = 2 then
Make temp node point to first node
Make head node point to next of temp node
Release memory
If choice = 3 then
Display stack elements starting from head node till null
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
65
Program
/* 5c - Stack using Single Linked List */
#include
#include
#include
#include
<stdio.h>
<conio.h>
<process.h>
<alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch = 0;
int k;
struct node *h, *temp, *head;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Stack using Linked List \n");
printf("1->Push ");
printf("2->Pop ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
h = head;
temp->next = h->next;
h->next = temp;
break;
case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
66
Output
Stack using Linked List
1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 23
New node added
Stack using Linked List
1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 34
Stack using Linked List
1->Push 2->Pop 3->View
Enter your choice : 3
HEAD -> 34 -> 23 -> NULL
4->Exit
Result
Thus push and pop operations of a stack was demonstrated using linked list.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 5d
67
Date:
Aim
To implement queue operations using linked list.
Algorithm
Start
Define a singly linked list node for stack
Create Head node
Display a menu listing stack operations
Accept choice
If choice = 1 then
Create a new node with data
Make new node point to first node
Make head node point to new node
If choice = 2 then
Make temp node point to first node
Make head node point to next of temp node
Release memory
If choice = 3 then
Display stack elements starting from head node till null
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
68
Program
/* 5d - Queue using Single Linked List */
#include
#include
#include
#include
<stdio.h>
<conio.h>
<process.h>
<alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch=0;
int k;
struct node *h, *temp, *head;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Queue using Linked List \n");
printf("1->Insert ");
printf("2->Delete ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
/* Reorganize the links */
h = head;
while (h->next != NULL)
h = h->next;
h->next = temp;
temp->next = NULL;
break;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
69
case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
printf("Node deleted \n");
free(h);
break;
case 3:
printf("\n\nHEAD -> ");
h=head;
while (h->next!=NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");
break;
case 4:
exit(0);
}
}
}
Output
Queue using Linked List
1->Insert 2->Delete 3->View
Enter your choice : 1
Enter label for new node : 12
Queue using Linked List
1->Insert 2->Delete 3->View
Enter your choice : 1
Enter label for new node : 23
Queue using Linked List
1->Insert 2->Delete 3->View
Enter your choice : 3
HEAD -> 12 -> 23 -> NULL
4->Exit
4->Exit
4->Exit
Result
Thus push and pop operations of a stack was demonstrated using linked list.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 5e
70
INFIX TO POSTFIX
Date:
Aim
To convert infix expression to its postfix form using stack operations.
Algorithm
Start
Define a array stack of size max = 20
Initialize top = -1
Read the infix expression character-by-character
If character is an operand print it
If character is an operator
Compare the operators priority with the stack[top] operator.
If the stack [top] operator has higher or equal priority than the input
operator,
Pop it from the stack and print it.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If the character is a right parenthesis, pop all the operators from the stack and
print it
until a left parenthesis is encountered. Do not print the parenthesis.
.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
71
Program
/* 5e - Conversion of infix to postfix expression */
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
int top = -1;
char stack[MAX];
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '^':
case '$':
return 6;
break;
case '(':
case ')':
case '#':
return 1;
break;
}
}
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
72
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)
{
postfix[j] = symbol;
j++;
}
else
{
if(symbol == '(')
push(symbol);
else if(symbol == ')')
{
while(stack[top] != '(')
{
postfix[j] = pop();
j++;
}
pop(); //pop out (.
}
else
{
if(prcd(symbol) > prcd(stack[top]))
push(symbol);
else
{
while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top] != '#')
{
postfix[j] = pop();
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
73
j++;
}
postfix[j] = '\0';
}
main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
}
void push(char item)
{
top++;
stack[top] = item;
}
char pop()
{
char a;
a = stack[top];
top--;
return a;
}
Output
Enter the valid infix string: (a+b*c)/(d$e)
The corresponding postfix string is: abc*+de$/
Enter the valid infix string: a*b+c*d/e
The corresponding postfix string is: ab*cd*e/+
Enter the valid infix string: a+b*c+(d*e+f)*g
The corresponding postfix string is: abc*+de*f+g*+
Result
Thus the given infix expression was converted into postfix form using stack.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 5f
74
EXPRESSION EVALUATION
Date:
Aim
To evaluate the given postfix expression using stack operations.
Algorithm
Start
Define a array stack of size max = 20
Initialize top = -1
Read the postfix expression character-by-character
If character is an operand push it onto the stack
If character is an operator
Pop topmost two elements from stack.
Apply operator on the elements and push the result onto the stack,
Eventually only result will be in the stack at end of the expression.
Pop the result and print it.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
75
Program
/* 5f - Evaluation of Postfix expression using stack */
#include <stdio.h>
#include <conio.h>
struct stack
{
int top;
float a[50];
}s;
main()
{
char pf[50];
float d1,d2,d3;
int i;
clrscr();
s.top = -1;
printf("\n\n Enter the postfix expression: ");
gets(pf);
for(i=0; pf[i]!='\0'; i++)
{
switch(pf[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s.a[++s.top] = pf[i]-'0';
break;
case '+':
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;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
76
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();
}
Output
Enter the postfix expression: 6523+8*+3+*
Expression value is 288.00
Result
Thus the given postfix expression was evaluated using stack.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
77
Sorting
Sorting algorithms take input an unsorted array and number of array elements
say 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 pth 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 phase, using some increment h k, all elements spaced hk apart are
sorted.
Merge sort algorithm merges two sorted lists. It is a recursive algorithm, wherein
merge sort is recursively applied to both halves of the original list. It is a classic divideand-conquer strategy. Once the subsets are sorted, entries in both sets are compared,
and whichever is less is put on to merged list.
Quick sort is the fastest known sorting algorithm. Like merge sort, quick sort is
a 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.
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 minimum of the list is swapped with the element at n-1th index of the array.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 6a
78
BUBBLE SORT
Date:
Aim
To sort an array of N numbers using Bubble sort.
Algorithm
Start
Read number of array elements n
Read array elements Ai
Outer Index i varies from last element to first element
Index j varies from first element to i-1
Compare elements Aj and Aj+1
If out-of-order then swap the elements
Display array elements after each pass
Display the final sorted list
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
79
Program
/* 6a - Bubble Sort */
#include <stdio.h>
main()
{
int n, t, i, j, k, a[20], p=0;
printf("Enter total numbers of elements: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=n-1; i>=0; i--)
{
for(j=0; j<i; j++)
{
if(a[j] > a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
p++;
printf("\n After Pass %d : ", p);
for(k=0; k<n; k++)
printf("%d ", a[k]);
}
printf("\n Sorted List : ");
for(i=0; i<n; i++)
printf("%d ", a[i]);
}
Output
Enter total numbers
Enter 8 elements: 8
After Pass 1 : 6 8
After Pass 2 : 6 3
After Pass 3 : 3 1
After Pass 4 : 1 2
After Pass 5 : 1 2
After Pass 6 : 1 2
After Pass 7 : 1 2
Sorted List : 1 2 3
of elements: 8
6 10 3 1 2 5 4
3 1 2 5 4 10
1 2 5 4 8 10
2 5 4 6 8 10
3 4 5 6 8 10
3 4 5 6 8 10
3 4 5 6 8 10
3 4 5 6 8 10
4 5 6 8 10
Result
Thus an array was sorted using bubble sort.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 6b
80
QUICK SORT
Date:
Aim
To sort an array of N numbers using Quick sort.
Algorithm
Start
Read number of array elements n
Read array elements Ai
Select an pivot element x from Ai
Divide the array into 3 sequences: elements < x, x, elements > x
Recursively quick sort both sets (Ai < x and Ai > x)
Display the sorted array elements
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
81
Program
/* 6b - Quick Sort */
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
main()
{
int arr[30];
int i, size;
printf("Enter total no. of the elements : ");
scanf("%d", &size);
printf("Enter total %d elements : \n", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
qsort(arr,0,size-1);
printf("\n Quick sorted elements \n");
for(i=0; i<size; i++)
printf("%d\t", arr[i]);
getch();
}
void qsort(int arr[20], int fst, int last)
{
int i, j, pivot, tmp;
if(fst < last)
{
pivot = fst;
i = fst;
j = last;
while(i < j)
{
while(arr[i] <=arr[pivot] && i<last)
i++;
while(arr[j] > arr[pivot])
j--;
if(i <j )
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
tmp = arr[pivot];
arr[pivot] = arr[j];
arr[j] = tmp;
qsort(arr, fst, j-1);
qsort(arr, j+1, last);
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
82
}
}
Output
Enter total no. of the elements : 8
Enter total 8 elements :
1
2
7
-1
0
4
-2
3
Quick sorted elements
-2
-1
0
Result
Thus an array was sorted using quick sort's divide and conquer method.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 6c
83
MERGE SORT
Date:
Aim
To sort an array of N numbers using Merge sort.
Algorithm
Start
Read number of array elements n
Read array elements Ai
Divide the array into sub-arrays with a set of elements
Recursively sort the sub-arrays
Display both sorted sub-arrays
Merge the sorted sub-arrays onto a single sorted array.
Display the merge sorted array elements
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
84
Program
/* 6c Merge sort */
#include <stdio.h>
#include <conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int size;
main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}
void part(int arr[], int min, int max)
{
int mid;
if(min < max)
{
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid+1, max);
merge(arr, min, mid, max);
}
if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
for(i=min; i<=max; i++)
printf("%d ", arr[i]);
}
}
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i, j, k, m;
j = min;
m = mid + 1;
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
85
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
Result
Thus array elements was sorted using merge sort's divide and conquer method.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 6d
86
SHELL SORT
Date:
Aim
To sort an array of N numbers using Shell sort.
Algorithm
Start
Read number of array elements n
Read array elements Ai
Use an increment sequence ht to determine how far apart elements are to be sorted
Sort elements at distance ht, then elements at ht-1, etc.
Finally sort the array using insertion sort.
Display the sorted array elements.
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
87
Program
/* 6d - Shell Sort */
#include <stdio.h>
main()
{
int n, i, j, k, temp, x, arr[100];
printf("Enter no. of elements : ");
scanf("%d", &n);
printf("Enter array elements : ");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);
for(i=n/2; i>0; i=i/2)
{
for(j=i; j<n; j++)
{
for(k=j-i; k>=0; k=k-i)
{
if(arr[k+i] >= arr[k])
break;
else
{
temp = arr[k];
arr[k] = arr[k+i];
arr[k+i] = temp;
}
}
}
printf("After Pass :");
for(x=0; x<n; x++)
printf("%d ", arr[x]);
}
printf("Sorted List: ");
for(i=0; i<n; i++)
printf("%d ", arr[i]);
}
Output
Enter no. of elements : 13
Enter array elements : 81 94 11
After pass :15 94 11 58 12
After pass :15 12 11 17 41
After pass :11 12 15 17 28
Sorted List:11 12 15 17 28
93 12 35 17
35 17 95
28 58 94
35 41 58
35 41 58
95 28 58 41
28 93 41
35 81 95
75 81 93
75 81 93
75 15
75 81
75 93
94 95
94 95
Result
Thus array elements was sorted using shell sort.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 6e
88
INSERTION SORT
Date:
Aim
To sort an array of N numbers using Insertion sort.
Algorithm
Start
Read number of array elements n
Read array elements Ai
Outer index i varies from second element to last element
Inner index j is used to compare elements to left of outer index
Insert the element into the appropriate position.
Display the array elements after each pass
Display the sorted array elements.
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
89
Program
/* 6e - Insertion Sort */
main()
{
int i, j, k, n, temp, a[20], p=0;
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp = a[i];
j = i - 1;
while((temp<a[j]) && (j>=0))
{
a[j+1] = a[j];
j = j - 1;
}
a[j+1] = temp;
p++;
printf("\n After Pass %d: ", p);
for(k=0; k<n; k++)
printf(" %d", a[k]);
}
printf("\n Sorted List : ");
for(i=0; i<n; i++)
printf(" %d", a[i]);
}
Output
Enter total elements: 6
Enter array elements: 34 8 64 51 32
After Pass 1:
8 34 64 51 32
After Pass 2:
8 34 64 51 32
After Pass 3:
8 34 51 64 32
After Pass 4:
8 32 34 51 64
After Pass 5:
8 21 32 34 51
Sorted List : 8 21 32 34 51 64
21
21
21
21
21
64
Result
Thus array elements was sorted using insertion sort.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 6f
90
SELECTION SORT
Date:
Aim
To sort an array of N numbers using Selection sort.
Algorithm
Start
Read number of array elements n
Read array elements Ai
Outer index i varies from first to last but one element
Inner index j is used to compare from i+1th element to last element.
Find the smallest element.
th
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
91
Program
/* 6f - Selection Sort */
#include <stdio.h>
main()
{
int n, i, j, k, t, min, a[20], p=0;
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter %d elements : ", n);
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=0; i<n-1; i++)
{
min = i;
for(j=i+1; j<n; j++)
{
if(a[j] < a[min])
min = j;
}
t = a[i];
a[i] = a[min];
a[min] = t;
p++;
printf("\n After Pass %d : ", p);
for(k=0; k<n; k++)
printf("%d ", a[k]);
}
printf("\n Sorted List : ");
for(i=0; i<n; i++)
printf("%d ", a[i]);
}
Output
Enter total elements: 5
Enter 5 elements : 7 2 8 5 4
After Pass 1 : 2 7 8 5 4
After Pass 2 : 2 4 8 5 7
After Pass 3 : 2 4 5 8 7
After Pass 4 : 2 4 5 7 8
Sorted List : 2 4 5 7 8
Result
Thus array elements was sorted using selection sort.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
92
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 is likely to compared.
Binary search algorithm locates the middle element and compares with search key.
If 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;
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
subarray or until the subarray consists of one element that is not equal to the search
key. After each comparison, the binary search algorithm eliminates half of the elements
in the array being searched.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 7a
93
LINEAR SEARCH
Date:
Aim
To perform linear search of an element on the given array.
Algorithm
Start
Read number of array elements n
Read array elements Ai, i = 0,1,2,n1
Read search value
Assign 0 to found
Check each array element against search
If Ai = search then
found = 1
Print "Element found"
Print position i
Stop
If found = 0 then
print "Element not found"
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
94
Program
/* Linear search on a sorted array */
#include <stdio.h>
#include <conio.h>
main()
{
int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter Array Elements : \n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;
for(i=0; i<n; i++)
{
if (a[i] == val)
{
printf("Element found at position %d", i);
found = 1;
break;
}
}
if (found == 0)
printf("\n Element not found");
getch();
}
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
Result
Thus an array was linearly searched for an element's existence.
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
Ex. No. 7b
95
BINARY SEARCH
Date:
Aim
To locate an element in a sorted array using Binary search method
Algorithm
Start
Read number of array elements, say n
Create an array arr consisting n sorted elements
Get element, say key to be located
Assign 0 to lower and n to upper
While (lower < upper)
Determine middle element mid = (upper+lower)/2
If key = arr[mid] then
Print mid
Stop
Else if key > arr[mid] then
lower = mid + 1
else
upper = mid 1
Print "Element not found"
Stop
cseannauniv.blogspot.in
Vijai Anand
CS6212PDS Lab I
96
Program
/* Binary Search on a sorted array */
#include <stdio.h>
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]);
printf("\n Enter element to locate : ");
scanf("%d", &val);
upper = n;
lower = 0;
found = -1;
while (lower <= upper)
{
mid = (upper + lower)/2;
att++;
if (a[mid] == val)
{
printf("Found at index %d in %d attempts", mid, att);
found = 1;
break;
}
else if(a[mid] > val)
upper = mid - 1;
else
lower = mid + 1;
}
if (found == -1)
printf("Element not found");
}
Output
Enter array size : 10
Elements in Sorted Order
0
2
4
6
8 10 12 14
Enter element to locate : 16
Found at index 8 in 2 attempts
16
18
Result
Thus an element is located quickly using binary search method.
cseannauniv.blogspot.in
Vijai Anand