+ All Categories
Home > Documents > Cs 6212 Manual

Cs 6212 Manual

Date post: 11-Jul-2016
Category:
Upload: vishnu-kumar
View: 25 times
Download: 2 times
Share this document with a friend
96
CS6212–PDS Lab I cseannauniv.blogspot.in Vijai Anand 1 Index S. No Exp. Date Topics/ Units to be covered Sub. Date Conditional & Control Statements 1a Simple Calculator 1b Prime Number 1c Sum of Digits 1d Fibonacci Series 1e Perfect Number Functions , Arrays, Strings & Pointers 2a Shape Function 2b Factorial Recursion 2c Array Maximum 2d Matrix Addition 2e Matrix Multiplication 2f Palindrome 2g Paragraph Analysis 2h Pass by Reference Structures & Linked List 3a Payroll Application 3b Team-wise Sorting 3c Singly Linked List File Handling 4a Sequential File Access 4b Random File Access 4c File Copy Stack and Queue 5a Stack Array 5b Queue Array 5c Linked List Stack 5d Linked List Queue 5e Infix to Postfix 5f Expression Evaluation Sorting Algorithms 6a Bubble Sort 6b Quick Sort 6c Merge Sort 6d Shell Sort 6e Insertion Sort 6f Selection Sort Linear / Binary Search 7a Linear Search 7b Binary search
Transcript
Page 1: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

1

Index

S. No Exp. Date Topics/ Units to be covered Sub. DateConditional & Control Statements

1a Simple Calculator1b Prime Number1c Sum of Digits1d Fibonacci Series1e Perfect Number

Functions , Arrays, Strings & Pointers2a Shape Function2b Factorial Recursion2c Array Maximum2d Matrix Addition2e Matrix Multiplication2f Palindrome2g Paragraph Analysis2h Pass by Reference

Structures & Linked List3a Payroll Application3b Team-wise Sorting3c Singly Linked List

File Handling4a Sequential File Access4b Random File Access4c File Copy

Stack and Queue5a Stack Array5b Queue Array5c Linked List Stack5d Linked List Queue5e Infix to Postfix5f Expression Evaluation

Sorting Algorithms6a Bubble Sort6b Quick Sort6c Merge Sort6d Shell Sort6e Insertion Sort6f Selection Sort

Linear / Binary Search7a Linear Search7b Binary search

Page 2: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

2

Conditional Statements

The if statement is a two-way decision making statement. If a condition holdstrue, then corresponding true-block is executed; otherwise false-block is executed. Theelse 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 breakstatement is encountered. The default block is executed when none of the case valuematches.

The while is an entry-controlled loop, i.e., the condition is evaluated first. Ifcondition is true then body of the loop is executed. The loop is executed repeatedly untilthe 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 isexecuted once and then condition is evaluated. If true, then the process is repeated. Theloop is executed at least once.

The for statement is an entry and counter controlled loop. It contains threeparts namely initialize, condition and increment/decrement. The counter variable isinitialized once and the condition is evaluated. If condition is true, then body of the loopis executed. Counter variable is incremented/decremented each time before testing thecondition.

The break statement is used to exit from the loop in which it is contained. Thecontinue statement skips remaining part of the loop for that iteration.

Page 3: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

3

Ex. No. 1a SIMPLE CALCULATORDate:

AimTo implement a simple calculator using switch case statement.

AlgorithmStartDisplay calculator menuRead the operator symbol and operands n1, n2If operator = + then

calculate result = n1 + n2Else if operator = – then

calculate result = n1 – n2Else if operator = * then

calculate result = n1 * n2Else if operator = / then

calculate result = n1 / n2Else if operator = % then

calculate result = n1 % n2Else

print "Invalid operator"Print resultStop

Page 4: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

4

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

Page 5: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

5

Output

Simple Calculator + Summation - Difference * Product / Quotient % RemainderEnter the operator : -Enter operand1 and operand2 : 2 42 - 4 = -2

Simple Calculator + Summation - Difference * Product / Quotient % RemainderEnter the operator : %Enter operand1 and operand2 : 5 25 % 2 = 1

ResultThus simple calculator functionality was executed using menu-oriented

approach.

Page 6: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

6

Ex. No. 1b PRIME NUMBERDate:

AimTo print first 'n' numbers using for loop.

AlgorithmStartRead the value of nLoop j to generate numbers from 2 to 10000

Loop k in the range 2 to j/2Check if divisor existsIf j%k = 0 then

Examine next jIf there are no divisor for j then

Print jIncrement i by 1

If i = n thenStop

ElseExamine next j

Page 7: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

7

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 : 9Prime numbers : 2 3 5 7 11 13 17 19 23

ResultThus first set of prime numbers is displayed.

Page 8: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

8

Ex. No. 1c SUM OF DIGITSDate:

AimTo find the sum of the digits of a given number using while statement. .

AlgorithmStartRead numInitialize sum to 0.Repeat until num = 0

Obtain last digit d = num % 10Add d to sumnum = num / 10

Print sumStop

Page 9: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

9

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 : 58349Sum of digits : 29

ResultThus digits of the given number were summed up.

Page 10: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

10

Ex. No. 1d FIBONACCI SERIESDate:

AimTo print first N terms of the Fibonacci series assuming the first two terms as 0

and 1

AlgorithmStartRead no. of terms nInitialize f1 to 0 and f2 to 1.Print f1 and f2Initialize i to 3Repeat until i < n

Generate next term f3 = f1 + f2Print f3f1 = f2f2 = f3Increment i by 1

Stop

Page 11: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 series0 1 1 2 3 5 8 13 21 34

ResultThus first ‘n’ terms of Fibonacci series was generated.

Page 12: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

12

Ex. No. 1e PERFECT NUMBERDate:

AimTo find whether the given number is a perfect number or not.

AlgorithmStartRead number nInitialize sum to 0Loop i from 1 to n-1

Add the divisorsIf n%i = 0 then

sum = sum + iIf sum = n then

Print "Perfect Number"Else

Print "Not Perfect Number"

Page 13: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 : 6It is a perfect number

Enter any number : 20It is not a perfect number

ResultThus whether a given number is perfect or not is determined.

Page 14: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

14

Arrays, Strings, Pointers and Function

A function is a block of code which is used or to achieve a specific task. Functionsfacilitate top-down modular programming and avoid code redundancy. When functionsare 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 usedas return type, if the function does not return a value. Parameters can be passed tofunction either as value or reference (address). A function that calls itself is calledrecursive 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 startwith zero and the last index is size-1. Arrays can be either one dimensional or twodimensional. 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 isdynamic.

String is a sequence of characters terminated by a null character '\0'. String isdeclared as character array. C library provides string handling function under headerfile <string.h>. String variables are not preceded by a & in a scanf statement. getsfunction is used to read string with embedded whitespace.

Structure is a user-defined data type and is a collection of heterogeneouselements, i.e. elements can have dissimilar types. Elements in a structure are referred asmembers. Each 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 isgenerally obtained using sizeof operator. Members of a structure are accessed usingdot (.) operator.

Pointer variable is a variable that can store the address of another variable.Pointer variables are prefixed with * operator in declaration statement. Address of avariable is obtained using & (address) operator. A pointer variable can point to elementsof the same type only. A pointer variable can access value of the variable pointed to byusing the * dereference operator. Arguments must be of pointer type for pass-by-reference. When arguments are passed by reference, changes made within the functionare reflected in the calling function. Pointers can be used to voluminous data by passingan array (starting address).

Page 15: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

15

Ex. No. 2a SHAPE FUNCTIONDate:

AimTo invoke functions that compute areas of different shapes using switch case

conditional statement.

AlgorithmStartDisplay shape menuRead choiceIf choice = 1 then

Read sideCall square(side)

Else if choice = 2 thenRead radiusCall circle(radius)

Else if choice = 3 thenRead base, heightCall triangle(base, height)

Else if choice = 4 thenRead length, breadthCall rectangle(length, breadth)

Elseprint "Invalid choice"

Print areaStop

Function square (s)Compute area = s2

Return area

Function circle (r)Compute area = r2

Return area

Function triangle (b,h)Compute area = ½bhReturn area

Page 16: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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;

Page 17: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 Shapes1.Square 2.Circle 3.Triangle 4.RectangleEnter choice : 1Enter side : 4.3Area : 18.49

ResultThus areas of various shapes was computed using function.

Page 18: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

18

Ex. No. 2b FACTORIAL RECURSIONDate:

AimTo find the factorial of a number using recursive function.

AlgorithmStart

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)

Page 19: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

elsereturn (n * factorial(n-1));

}

Output

Enter a number : 6Factorial value : 720

Enter a number : 12Factorial value : 479001600

ResultThus factorial value of a given number was obtained through recursive function

call.

Page 20: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

20

Ex. No. 2c ARRAY MAXIMUMDate:

AimTo 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,…n–1

Assume first element A0 to be max

Compare each array element Ai with max

If max <Ai then max = Ai

Print max

Stop

Page 21: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 : 6Enter Array Elements38-711-90Maximum value = 11

ResultThus maximum element of an array was determined.

Page 22: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

22

Ex. No. 2d MATRIX ADDITIONDate:

AimTo add the given matrices using function.

AlgorithmStartRead the order of matrices as m and nRead 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

Page 23: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 24: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

24

printf("\n Contents of C matrix \n"); for(i=0; i<row; i++) { for(j=0; j<col; j++) { printf("%3d",c[i][j]); } printf("\n"); }

getch();}

Output

Enter order for matrix : 2 2

Enter elements for A matrix1 11 1

Enter elements for B matrix2 23 4

Contents of C matrix 3 3 4 5

ResultThus the given matrices were added.

Page 25: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

25

Ex. No. 2e MATRIX MULTIPLICATIONDate:

AimTo compute product of two matrices using two dimensional array.

AlgorithmStartRead the order of matrix A as m and nRead the order of matrix B as p and qIf n p then print "Multiplication not possible" and StopRead matrix A elements Aij

Read matrix B elements Bij

Initialize matrix C elements Cij to 0Compute product matrix Cij = Cij + Aik * Bkj where 0 i < m, 0 j < q and 0 k <nPrint matrix Cij, Stop

Page 26: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 order of matrix A : "); scanf("%d%d", &r1, &c1); printf("Enter order of matrix B : "); scanf("%d%d", &r2, &c2);

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;

Page 27: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

27

for(k=0; k<c1; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } }

printf("Product matrix C\n"); for(i=0; i<r1; i++) { for(j=0; j<c2; j++) { printf("%-4d",c[i][j]); } printf("\n"); } getch();}

Output

Enter order of matrix A : 2 3Enter order of matrix B : 3 2Enter matrix A elements1 1 11 1 1Enter matrix B elements2 22 22 2Product matrix C6 66 6

ResultThus product of given two matrices was obtained using arrays.

Page 28: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

28

Ex. No. 2f PALINDROMEDate:

Aim

To determine whether the input string is palindrome using string handlingfunctions.

AlgorithmStartRead the string, say strCopy stronto revusing strcpy functionReverse rev using strrev function

Compare str and revusing strcmp function

If outcome = 0 thenPrint "Given string is palindrome"

ElsePrint "Given string is not palindrome"

Stop

Page 29: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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:malayalamReversed string is:malayalamGiven string is a palindrome

Enter the string: ComputerReversed string is: retupmoCGiven string is not a palindrome

ResultThus the given input string is checked for palindrome using string handling

functions.

Page 30: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

30

Ex. No. 2g PARAGRAPH ANALYSISDate:

AimTo accept a line of text and to print the number of vowels, consonants,

digits and whitespaces.

AlgorithmStartRead paragraph using gets function.Convert text to lower caseAssign 0 to vow, dig, con, wsConsider each character

If character is a vowel then increment vowElse if character is a digit then increment digElse if character is a space then increment wsElse increment con

Print vow, dig, con, wsStop

Page 31: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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:

Page 32: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

32

con++; } }

printf("\n Vowel count : %d", vow); printf("\n Consonant count : %d", con); printf("\n Digit count : %d", dig); printf("\n Whitespace count : %d", ws); getch();}

Output

Enter a paragraph :I am a fine. Bye 123.

Vowel count : 6 Consonant count : 5 Digit count : 3 Whitespace count : 5

ResultThus statistics of the given paragraph was determined.

Page 33: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

33

Ex. No. 2h PASS BY REFERENCEDate:

AimTo demonstrate parameters passing to a function by reference.

AlgorithmStartRead values of a and bPrint a and bCall swapref function with address of a and bPrint a and bStop

Function swapref (x, y)Assign value pointed by variable x to a temporary variable tAssign value pointed by variable y to value pointed by variable xAssign value t to value pointed by variable y

Page 34: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 : 10Enter value for B : 20

Values after Pass by ReferenceValue of A : 20Value of B : 10

ResultThus values of variables were exchanged by passing parameters by reference.

Page 35: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

35

Structures and Linked Lists

C supports a constructed (user-defined) data type known as structure, which is amethod of packing related data of different types i.e., heterogeneous elements. A singlestructure 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 ofmemory required to store structure is sum of storage capacity of all members. Eachindividual 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 thesame storage area. The amount of memory required is same as that required for itslargest member.

Self-Referential structure is a structure where one of its members is a pointer tothe structure itself. Such structures are very useful in applications involving linked datastructures such as list and trees.

A linked list is a set of nodes where each node has two fields data and a link. Thelink field points to the next node by storing address of the next node. Operations on alinked list includes insertion and deletion of a node and traversal of the list. Backwardtraversal is not possible in a singly linked list.

Doubly linked list node contains an additional pointer that contains address ofthe previous node in the list. Both forward and backward traversal is possible in adoubly linked list.

Page 36: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

36

Ex. No. 3a PAYROLL APPLICATIONDate:

AimTo generate employee payroll for anorganization using structure.

AlgorithmStartDefine employee structure with fields empid, ename, basic, hra, da, it, gross andnetpayRead number of employees nRead empid, ename, and basic for n employees in an array of structure.For each employee, compute

hra = 2% of basicda = 1% of basicgross = basic + hra + dait = 5% of basicnetpay = gross - it

Print empid, ename, basic, hra, da, it, gross and netpay for all employeesStop

Page 37: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 38: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

38

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 Pay\n"); for(i=0;i<80;i++) printf("*"); for(i=0; i<n; i++) { printf("\n%d\t%-15s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f", emp[i].empid, emp[i].ename, 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();}

Output

Enter No. of Employees : 2

Enter Employee DetailsEnter Employee Id : 436Enter Employee Name :GopalEnter Basic Salary : 10000

Enter Employee DetailsEnter Employee Id : 463Enter Employee Name :RajeshEnter Basic Salary : 22000

XYZ & Co. Payroll

********************************************************************************EmpId Name Basic HRA DA IT Gross Net Pay********************************************************************************

436 Gopal 10000 200.00 100.00 500.00 10300.00 9800.00463 Rajesh 22000 440.00 220.00 1100.00 22660.00 21560.00

********************************************************************************

ResultThus payroll for employees was generated using structure.

Page 39: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

39

EX. 3B. TEAM-WISE SORTINGDate:

AimTo define a structure for a cricket player and to print a team wise list containing

names of players with their batting average.

AlgorithmStartDefine crickete structure with fields pcode, pname, tname, and bavgRead number of players nRead details of each player in an array of structure.Sort player structure according to team name.Print players detailsStop

Page 40: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 41: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

41

printf("\n\t PLAYER DETAILS-TEAM WISE \n"); printf("\n P.Code \t"); printf("%-15s %-15s", "Name", "Team"); printf("Bat. Avg \n"); for(i=0; i<n; i++) { printf("%d\t", player[i].plcode); printf("%-15s", player[i].name); printf("%-15s", player[i].tname); printf("%.2f\n", player[i].btavg); } getch();}

Output

Enter No. of Players : 6

Enter Player DetailsEnter player code : 23Enter player name : DhoniEnter team name : CSKEnter batting average : 45.23

Enter Player DetailsEnter player code : 34Enter player name : MaxwellEnter team name : PWEnter batting average : 67.2

Enter Player DetailsEnter player code : 17Enter player name : RainaEnter team name : CSKEnter batting average : 85

PLAYER DETAILS-TEAM WISEP.Code Name Team Bat. Avg17 Raina CSK 85.0023 Dhoni CSK 45.2334 Maxwell PW 67.20

ResultThus players details were sorted team-wise and printed.

Page 42: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

42

EX. 3C SINGLY LINKED LISTDate:

AimTo define a singly linked list node and perform operations such as insertions and

deletions dynamically.

AlgorithmStartDefine single linked list node as self referential structureCreate Head node with label = -1 and next = NULL usingDisplay menu on list operationAccept user choiceIf choice = 1 then

Locate node after which insertion is to be doneCreate a new node and get data partInsert the new node at appropriate position by manipulating address

Else if choice = 2Get node's data to be deleted.Locate the node and delink the nodeRearrange the links

ElseTraverse the list from Head node to node which points to null

Stop

Page 43: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

43

Program

/* 3c - Single Linked List */

#include <stdio.h>#include <conio.h>#include <process.h>#include <alloc.h>#include <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;

Page 44: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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;

Page 45: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 OPERATIONS1->Add 2->Delete 3->View 4->ExitEnter your choice : 1Enter label after which new node is to be added : -1Enter label for new node : 23

SINGLY LINKED LIST OPERATIONS1->Add 2->Delete 3->View 4->ExitEnter your choice : 1Enter label after which new node is to be added : 23Enter label for new node : 67

SINGLY LINKED LIST OPERATIONS1->Add 2->Delete 3->View 4->ExitEnter your choice : 3 HEAD -> 23 -> 67 -> NULL

ResultThus operation on single linked list is performed.

Page 46: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

46

File Handling

Applications require information stored on auxiliary storage device. Suchinformation is stored permanently as a data file that allows to access and alter theinformation whenever necessary.

Prior to performing any activity of a file, the file should be opened. By opening afile, link between the program and the operating system is established. This link existsby 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 openedthe 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 withthe first data set, fetch the next and so on until end-of-file is encountered. End-of-filecondition can be checked using feof function.

Random access means moving file pointer to the desired byte. Pre-definedfunctions that facilitate random access are:

ftell—to know current position of the file pointerrewind—to move file pointer to beginning of the filefseek—used to move the file pointer to the desired byte.

File I/O is generally either character or block oriented. Functions getc and putcis used to read/write a single character from the given file. Functions fread and fwrite isused to perform I/O as blocks of data, where each block is a fixed number of contiguousbytes. A block is generally represented as a structure.

Command-line arguments allow parameters to be passed to the main function onexecution. The two command-line arguments are argc, an integer variable whose valueis assigned to number of arguments given and argv, a string array that contains the listof arguments. The main function prototype is main(int argc, char *argv[]) to supportcommand-line arguments.

Page 47: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

47

EX. 4A SEQUENTIAL FILE ACCESSDate:

AimTo create a telephone directory and to locate a user details using sequential

access.

AlgorithmStartOpen empseq.dat file in append modeAdd records to the fileClose the fileOpen empseq.dat file in read modeGet person name.Check each record one by one from the first recordIf person name matches then print the details.Close the fileStop

Page 48: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 49: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

49

Output

Enter employee details

Enter Name ("xxx" to quit) : vijaiEnter Contact No. : 1234

Enter Name ("xxx" to quit) : anandEnter Contact No. : 9876

Enter Name ("xxx" to quit) : xxx

Enter Employee name to get phone no. : anandTelephone No. : 9876

ResultThus sequential access is performed to retrieve a person's contact details.

Page 50: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

50

EX. 4B RANDOM FILE ACCESSDate:

AimTo create a address book and to locate employee details using random access.

AlgorithmStartOpen emprand.dat file in append modeAutomatically generate employee id.Add records to the fileClose the fileOpen emprand.dat file in read modeGet employee id.Move the file pointer to the desired record using fseek functionPrint the details.Close the fileStop

Page 51: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 52: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

52

printf("Designation : %s\n", emp2.desig); } else printf("\n Incorrect Employee Id \n"); fclose(fd2);}

Output

Enter employee details

Employee Id : 100Enter Name ("xxx" to quit) : gopalEnter Designation : AP

Employee Id : 101Enter Name ("xxx" to quit) : arunEnter Designation : ASP

Employee Id : 102Enter Name ("xxx" to quit) : RajuEnter Designation : Prof

Employee Id : 103Enter Name ("xxx" to quit) : xxx

Enter Employee id : 102Employee Name : RajuDesignation : Prof

ResultThus random access is performed to directly obtain employee details.

Page 53: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

53

EX. 4B FILE COPYDate:

AimTo copy a file using sequential operations and command-line arguments.

AlgorithmStartOpen source file in read modeOpen dest file in write modeTill end of source file

Read a character from source fileWrite a character onto destination file

Print "File copied".Close all filesStop

Page 54: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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.cFile Copied

ResultThus file is copied using character-based sequential operation.

Page 55: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

55

Stacks and Queues

The stack is a list of elements placed on top of each other. A pointer alwayspoints to the topmost position of a stack called top. The two possible operation on stackis push and pop. It is implemented either using arrays or linked lists. The top is anindicator where both push and pop operations are performed. CDs in a disc spindle arean example of stack.

The insertion operation is termed as push. For each insertion the pointer top isincremented so that it retains the top-most position in the stack. The deletion operationof stack is termed as pop. Stack follows LIFO (Last In First Out) method i.e., the lastinserted element would be the first element to be deleted. The pointer top is made topoint the next element in order.

In a Queue, the set of elements are placed one after the another, just like peoplestanding in a queue at a reservation counter. In a Queue, there are two pointers namelyfront and rear. front points the first element and rear the last element in the Queue.

Queue is represented as FIFO (First In First Out). Insertions are carried out atthe REAR end the pointer is updated. Deletion is performed at the FRONT endremoving the oldest element and the pointer is updated.

Stack Queue

Applications of stack include infix to postfix conversion and evaluation ofexpression in postfix form. An infix arithmetic expression can be converted into apostfix expression if precedence of operators is known. Operators are sandwichedbetween operands in an infix expression whereas operators appear after operands inpostfix form. Expression in postfix form is evaluated by applying operators on operandsto its immediate left.

Page 56: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

56

Ex. No. 5a STACK ARRAYDate:

AimTo implement stack operations using array.

AlgorithmStartDefine a array stack of size max = 5Initialize top = -1Display a menu listing stack operationsAccept choiceIf choice = 1 then If top < max -1

Increment topStore element at current position of top

ElsePrint Stack overflow

If choice = 2 then If top < 0 then

Print Stack underflow Else

Display current top elementDecrement top

If choice = 3 then Display stack elements starting from topStop

Page 57: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 58: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 OPERATION1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 1

Enter Stack element : 12

STACK OPERATION1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 1

Enter Stack element : 23

STACK OPERATION

Page 59: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

59

1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 1

Enter Stack element : 34

STACK OPERATION1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 1

Enter Stack element : 45

STACK OPERATION1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 3

Top--> 45 34 23 12

STACK OPERATION1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 2

Popped element is 45

STACK OPERATION1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 3

Top--> 34 23 12

STACK OPERATION1.PUSH 2.POP 3.VIEW 4.QUITEnter Choice : 4

ResultThus push and pop operations of a stack was demonstrated using arrays.

Page 60: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

60

Ex. No. 5b QUEUE ARRAYDate:

AimTo implement queue operations using array.

AlgorithmStartDefine a array queue of size max = 5Initialize front = rear = –1Display a menu listing queue operationsAccept choiceIf choice = 1 then If rear < max -1

Increment rearStore element at current position of rear

ElsePrint Queue Full

If choice = 2 then If front = –1 then

Print Queue empty Else

Display current front elementIncrement front

If choice = 3 then Display queue elements starting from front to rear.Stop

Page 61: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 62: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 63: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

63

Output

QUEUE OPERATION1.INSERT 2.DELETE 3.VIEW 4.QUITEnter Choice : 1

Enter element to be inserted : 12

QUEUE OPERATION1.INSERT 2.DELETE 3.VIEW 4.QUITEnter Choice : 1

Enter element to be inserted : 23

QUEUE OPERATION1.INSERT 2.DELETE 3.VIEW 4.QUITEnter Choice : 1

Enter element to be inserted : 34

QUEUE OPERATION1.INSERT 2.DELETE 3.VIEW 4.QUITEnter Choice : 1

Enter element to be inserted : 45

QUEUE OPERATION1.INSERT 2.DELETE 3.VIEW 4.QUITEnter Choice : 1

Enter element to be inserted : 56

QUEUE OPERATION1.INSERT 2.DELETE 3.VIEW 4.QUITEnter Choice : 1

Queue Full

QUEUE OPERATION1.INSERT 2.DELETE 3.VIEW 4.QUITEnter Choice : 3

Front--> 12 23 34 45 56 <--Rear

ResultThus insert and delete operations of a queue was demonstrated using arrays.

Page 64: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

64

Ex. No. 5c LINKED LIST STACKDate:

AimTo implement stack operations using linked list.

AlgorithmStartDefine a singly linked list node for stackCreate Head nodeDisplay a menu listing stack operationsAccept choiceIf choice = 1 then Create a new node with data Make new node point to first node Make head node point to new nodeIf choice = 2 then Make temp node point to first node Make head node point to next of temp node Release memoryIf choice = 3 then Display stack elements starting from head node till nullStop

Page 65: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

65

Program

/* 5c - Stack using Single Linked List */

#include <stdio.h>#include <conio.h>#include <process.h>#include <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;

Page 66: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

66

printf("Node %s deleted\n", h->label); free(h); break;

case 3: printf("\n HEAD -> "); h = head; /* Loop till last node */ while(h->next != NULL) { h = h->next; printf("%d -> ",h->label); } printf("NULL \n"); break;

case 4: exit(0); } }}

Output

Stack using Linked List1->Push 2->Pop 3->View 4->ExitEnter your choice : 1Enter label for new node : 23New node added

Stack using Linked List1->Push 2->Pop 3->View 4->ExitEnter your choice : 1Enter label for new node : 34

Stack using Linked List1->Push 2->Pop 3->View 4->ExitEnter your choice : 3HEAD -> 34 -> 23 -> NULL

ResultThus push and pop operations of a stack was demonstrated using linked list.

Page 67: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

67

Ex. No. 5d LINKED LIST QUEUEDate:

AimTo implement queue operations using linked list.

AlgorithmStartDefine a singly linked list node for stackCreate Head nodeDisplay a menu listing stack operationsAccept choiceIf choice = 1 then Create a new node with data Make new node point to first node Make head node point to new nodeIf choice = 2 then Make temp node point to first node Make head node point to next of temp node Release memoryIf choice = 3 then Display stack elements starting from head node till nullStop

Page 68: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

68

Program

/* 5d - Queue using Single Linked List */

#include <stdio.h>#include <conio.h>#include <process.h>#include <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;

Page 69: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 List1->Insert 2->Delete 3->View 4->ExitEnter your choice : 1Enter label for new node : 12

Queue using Linked List1->Insert 2->Delete 3->View 4->ExitEnter your choice : 1Enter label for new node : 23

Queue using Linked List1->Insert 2->Delete 3->View 4->ExitEnter your choice : 3HEAD -> 12 -> 23 -> NULL

ResultThus push and pop operations of a stack was demonstrated using linked list.

Page 70: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

70

Ex. No. 5e INFIX TO POSTFIXDate:

AimTo convert infix expression to its postfix form using stack operations.

AlgorithmStartDefine a array stack of size max = 20Initialize top = -1Read the infix expression character-by-character If character is an operand print it If character is an operator

Compare the operator’s 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.

ElsePush 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 ituntil a left parenthesis is encountered. Do not print the parenthesis.

.

Page 71: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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;

Page 72: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 73: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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/eThe corresponding postfix string is: ab*cd*e/+

Enter the valid infix string: a+b*c+(d*e+f)*gThe corresponding postfix string is: abc*+de*f+g*+

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

Page 74: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

74

Ex. No. 5f EXPRESSION EVALUATIONDate:

AimTo evaluate the given postfix expression using stack operations.

AlgorithmStartDefine a array stack of size max = 20Initialize top = -1Read 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.

Page 75: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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;

Page 76: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

ResultThus the given postfix expression was evaluated using stack.

Page 77: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

77

Sorting

Sorting algorithms take input an unsorted array and number of array elementssay n. Sorting is basically based on comparison. Each stage in a sorting algorithm iscalled a pass.

Bubble sort is an older, easier and inefficient sorting algorithm. It works bycomparing each element of the array with the element next to it and swapping ifrequired. 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 anypass p, elements in positions 1 through p are in sorted order. In pass p, the pth elementleft is moved until its correct place is found among the first p elements.

Shell sort works by comparing elements that are distant. The distance betweencomparisons decreases as the algorithm runs until the last phase, in which adjacentelements are compared. Shell sort uses a sequence, h1, h2, . . . , ht, called the incrementsequence. After a phase, using some increment hk, all elements spaced hk apart aresorted.

Merge sort algorithm merges two sorted lists. It is a recursive algorithm, whereinmerge 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 whichever is less is put on to merged list.

Quick sort is the fastest known sorting algorithm. Like merge sort, quick sort isa 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 swapsit with the element at the index where it is supposed to be. The process is repeated suchthat nth minimum of the list is swapped with the element at n-1th index of the array.

Page 78: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

78

Ex. No. 6a BUBBLE SORTDate:

AimTo sort an array of N numbers using Bubble sort.

AlgorithmStartRead number of array elements nRead array elements Ai

Outer Index i varies from last element to first elementIndex j varies from first element to i-1

Compare elements Aj and Aj+1

If out-of-order then swap the elementsDisplay array elements after each pass

Display the final sorted listStop

Page 79: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

OutputEnter total numbers of elements: 8Enter 8 elements: 8 6 10 3 1 2 5 4After Pass 1 : 6 8 3 1 2 5 4 10After Pass 2 : 6 3 1 2 5 4 8 10After Pass 3 : 3 1 2 5 4 6 8 10After Pass 4 : 1 2 3 4 5 6 8 10After Pass 5 : 1 2 3 4 5 6 8 10After Pass 6 : 1 2 3 4 5 6 8 10After Pass 7 : 1 2 3 4 5 6 8 10Sorted List : 1 2 3 4 5 6 8 10

ResultThus an array was sorted using bubble sort.

Page 80: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

80

Ex. No. 6b QUICK SORTDate:

AimTo sort an array of N numbers using Quick sort.

AlgorithmStartRead number of array elements nRead array elements Ai

Select an pivot element x from Ai

Divide the array into 3 sequences: elements < x, x, elements > xRecursively quick sort both sets (Ai < x and Ai > x)Display the sorted array elementsStop

Page 81: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

Page 82: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

82

}}

Output

Enter total no. of the elements : 8Enter total 8 elements :127-104-23

Quick sorted elements-2 -1 0 1 2 3 4 7

ResultThus an array was sorted using quick sort's divide and conquer method.

Page 83: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

83

Ex. No. 6c MERGE SORTDate:

AimTo sort an array of N numbers using Merge sort.

AlgorithmStartRead number of array elements nRead array elements Ai

Divide the array into sub-arrays with a set of elementsRecursively sort the sub-arraysDisplay both sorted sub-arraysMerge the sorted sub-arrays onto a single sorted array.Display the merge sorted array elementsStop

Page 84: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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;

Page 85: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

85

for(i=min; j<=mid && m<=max; i++) { if(arr[j] <= arr[m]) { tmp[i] = arr[j]; j++; } else { tmp[i] = arr[m]; m++; } } if(j > mid) { for(k=m; k<=max; k++) { tmp[i] = arr[k]; i++; } } else { for(k=j; k<=mid; k++) { tmp[i] = arr[k]; i++; } } for(k=min; k<=max; k++) arr[k] = tmp[k];}

Output

Enter total no. of elements : 8Enter 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

ResultThus array elements was sorted using merge sort's divide and conquer method.

Page 86: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

86

Ex. No. 6d SHELL SORTDate:

AimTo sort an array of N numbers using Shell sort.

AlgorithmStartRead number of array elements nRead array elements Ai

Use an increment sequence ht to determine how far apart elements are to be sortedSort elements at distance ht, then elements at ht-1, etc.Finally sort the array using insertion sort.Display the sorted array elements.Stop

Page 87: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

OutputEnter no. of elements : 13Enter array elements : 81 94 11 93 12 35 17 95 28 58 41 75 15After pass :15 94 11 58 12 35 17 95 28 93 41 75 81After pass :15 12 11 17 41 28 58 94 35 81 95 75 93After pass :11 12 15 17 28 35 41 58 75 81 93 94 95Sorted List:11 12 15 17 28 35 41 58 75 81 93 94 95

ResultThus array elements was sorted using shell sort.

Page 88: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

88

Ex. No. 6e INSERTION SORTDate:

AimTo sort an array of N numbers using Insertion sort.

AlgorithmStartRead number of array elements nRead 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 passDisplay the sorted array elements.Stop

Page 89: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

OutputEnter total elements: 6Enter array elements: 34 8 64 51 32 21 After Pass 1: 8 34 64 51 32 21 After Pass 2: 8 34 64 51 32 21 After Pass 3: 8 34 51 64 32 21 After Pass 4: 8 32 34 51 64 21 After Pass 5: 8 21 32 34 51 64 Sorted List : 8 21 32 34 51 64

ResultThus array elements was sorted using insertion sort.

Page 90: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

90

Ex. No. 6f SELECTION SORTDate:

AimTo sort an array of N numbers using Selection sort.

AlgorithmStartRead number of array elements nRead 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. Swap ith element and the smallest element Display the array elements after each passDisplay the sorted array elements.Stop

Page 91: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

OutputEnter total elements: 5Enter 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

ResultThus array elements was sorted using selection sort.

Page 92: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

92

Searching

Searching is the process of locating a particular element in an array. The twosearching techniques are:

1. Linear search2. Binary search

Linear search involves each element to be compared against the key value startingfrom the first element. Linear search uses a for structure containing an if structure tocompare each element of an array with a search key. If search key is not found, thenvalue of –1 is returned. If the array being searched is not in any particular order, thenhalf 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 thatelement is returned.If the search key is less than the middle array element, the first half of thearray 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 asubarray or until the subarray consists of one element that is not equal to the searchkey. After each comparison, the binary search algorithm eliminates half of the elementsin the array being searched.

Page 93: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

93

Ex. No. 7a LINEAR SEARCHDate:

AimTo perform linear search of an element on the given array.

AlgorithmStartRead number of array elements nRead array elements Ai, i = 0,1,2,…n–1Read search valueAssign 0 to foundCheck each array element against search

If Ai = search thenfound = 1Print "Element found"Print position iStop

If found = 0 thenprint "Element not found"

Stop

Page 94: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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 : 7Enter Array Elements :23 6 12 5 0 32 10Enter element to locate : 5Element found at position 3

ResultThus an array was linearly searched for an element's existence.

Page 95: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

95

Ex. No. 7b BINARY SEARCHDate:

AimTo locate an element in a sorted array using Binary search method

AlgorithmStartRead number of array elements, say nCreate an array arr consisting n sorted elementsGet element, say key to be locatedAssign 0 to lower and n to upperWhile (lower < upper)

Determine middle element mid = (upper+lower)/2If key = arr[mid] then

Print midStop

Else if key > arr[mid] thenlower = mid + 1

elseupper = mid – 1

Print "Element not found"Stop

Page 96: Cs 6212 Manual

CS6212–PDS Lab I

cseannauniv.blogspot.in Vijai Anand

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

OutputEnter 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

ResultThus an element is located quickly using binary search method.


Recommended