77
SEMESTER: II BRANCH: CSE-A LAB MANUAL (EVEN Semester 2015-2016) Prepared by Mr.M.AZHAGIRI, Asst.Professor, Department of Computer Science & Engineering, Kingston Engineering College.

PDS LAB 1 Manual

Embed Size (px)

DESCRIPTION

Anna University First Year PDS 1 Lab Manual

Citation preview

Page 1: PDS LAB 1 Manual

SEMESTER: II BRANCH: CSE-A

LLAABB MMAANNUUAALL (EVEN Semester 2015-2016)

Prepared by

Mr.M.AZHAGIRI, Asst.Professor,

Department of Computer Science & Engineering,

Kingston Engineering College.

Page 2: PDS LAB 1 Manual

CS6212 PROGRAMMING AND DATA STRUCTURES LABORATORY I L T P C

0 0 3 2

OBJECTIVES:

The students should be made to:

Be familiar with c programming

Be exposed to implementing abstract data types

Learn to use files

Learn to implement sorting and searching algorithms.

1. C Programs using Conditional and Control Statements

2. C Programs using Arrays, Strings and Pointers and Functions

3. Representation of records using Structures in C

– Creation of Linked List

– Manipulation of records in a Linked List

4. File Handling in C

– Sequential access

– Random Access

5. Operations on a Stack and Queue

– infix to postfix

– simple expression evaluation using stacks

- Linked Stack Implementation

– Linked Queue Implementation

6. Implementation of sorting algorithms

7. Implementation of Linear search and Binary Search.

TOTAL: 45 PERIODS

OUTCOMES:

At the end of the course, the student should be able to:

Design and implement C programs for implementing stacks, queues, and linked lists.

Apply good programming design methods for program development.

Apply the different data structures for implementing solutions to practical problems.

Develop searching and sorting programs.

LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:

Standalone desktops with C compiler 30 Nos.

(or)

Server with C compiler supporting 30 terminals or more

Page 3: PDS LAB 1 Manual

1. C Programs using Conditional and Control Statements

A. Simple Calculator

B. Prime Number

C. Sum of Digits

D. Fibonacci Series

E. Perfect Number

2. C Programs using Arrays, Strings and Pointers and Functions

A. Shape Function

B. Factorial Recursion

C. Array Maximum

D. Matrix Addition

E. Matrix Multiplication

F. Palindrome

G. Paragraph Analysis

H. Pass by Reference

3. Representation of records using Structures in C

A. Student Data Base using Structure

B. Payroll Application using Union

C. Singly Linked List

D. Doubly Linked List

4. File Handling in C

A. File Handling

B. Sequential File Access

C. Random File Access

D. File Copy

5. Operations on a Stack and Queue

A. Stack Array

B. Expression Evaluation Infix to Postfix

C. Expression Evaluation Postfix to infix

D. Linked List Stack

E. Queue Array

F. Linked List Queue

6. Implementation of sorting algorithms

A. Bubble Sort

B. Insertion Sort

C. Selection Sort

D. Quick Sort

E. Merge Sort

F. Shell Sort

7. Implementation of Linear search and Binary Search.

A. Linear Search

B. Binary Search

Page 4: PDS LAB 1 Manual

Conditional Statements

The if-else 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.

If (condition)

TRUE STA TEMENT

else

FALSE STATEMENT

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.

switch (expression)

case 1:

Executable statement;

Break;

case 2:

Executable statement;

Break;

default:

Statement;

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.

while (condition)

{

Executable statement;

}

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.

do

Executable statement;

while (condition)

{

Executable statement;

}

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.

for(initialization; condition; increment/decrement)

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

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.

break;

Page 5: PDS LAB 1 Manual

Ex No:1-A 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

PROGRAM

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

Page 6: PDS LAB 1 Manual

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

}

OUTPUT

RESULT

Thus simple calculator functionality was executed using menu-oriented approach.

Page 7: PDS LAB 1 Manual

Ex No:1-B 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

PROGRAM

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

Page 8: PDS LAB 1 Manual

break;

}

getch();

}

OUTPUT

RESULT

Thus first set of prime numbers is displayed.

Page 9: PDS LAB 1 Manual

Ex No:1-C 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

PROGRAM

#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

RESULT Thus digits of the given number were summed up

Page 10: PDS LAB 1 Manual

Ex No:1-D 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

PROGRAM

#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("%d \t %d",f1,f2);

for(i=3; i<=n; i++)

{

f3 = f1 + f2;

printf("\t %d ",f3);

f1 = f2;

f2 = f3;

}

getch();

}

Page 11: PDS LAB 1 Manual

OUTPUT

RESULT

Thus first ‘n’ terms of Fibonacci series was generated

Page 12: PDS LAB 1 Manual

Ex No:1-E 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"

PROGRAM

#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

RESULT Thus whether a given number is perfect or not is determined.

Page 13: PDS LAB 1 Manual

Arrays, Strings, Pointers and Function

A function is a block of code which is used or to achieve a specific task. Functions facilitate top-down

modular programming and avoid code redundancy. When functions are used in a program, its

prototype must be declared. Prototype specifies return type, function name, number and type of

arguments that the function may take.

Void is used as return type, if the function does not return a value. Parameters can be passed to

function either as value or reference (address). A function that calls itself is called recursive function.

An array is a collection of homogeneous elements i.e., of the same data-type. When an array is

declared a contiguous memory is allocated. Array index always start with zero and the last index is

size-1. Arrays can be either one dimensional or two dimensional. Array can be passed as an

argument to a function only by reference. Memory allocation using arrays are static whereas using

functions such as malloc is dynamic.

One dimensional int a [10]; Two dimensional int a [3][3];

String is a sequence of characters terminated by a null character '\0' . String is declared as character

array. C library provides string handling function under header file <string.h> String variables are not

preceded by a & in a scanf statement. gets function is used to read string with embedded

whitespace. Strlen(); strcpy(); strcat(); strcmp(); strrev();

Structure is a user-defined data type and is a collection of heterogeneous elements, i.e. elements

can have dissimilar types. Elements in a structure are referred as members. Each member within a

structure is assigned its own unique storage area.

Struct student

{

int roll[10];

Char name[10];

Int marks[10];

}

Memory allocation for a structure is sum of memory required for each member. It is generally

obtained using sizeof operator. Members of a structure are accessed using dot (.) 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 a variable is obtained using & (address)

operator. A pointer variable can point to elements of the same type only. A pointer variable can

access value of the variable pointed to by using the *dereference operator. Arguments must be of

pointer type for pass-by- reference. When arguments are passed by reference, changes made within

the function are reflected in the calling function. Pointers can be used to voluminous data by passing

an array (starting address).

Int *a;

Int *b;

Page 14: PDS LAB 1 Manual

Ex No:2-A 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 = 𝜋𝑟2

Return area

Function triangle (b,h)

Compute area = ½bh

Return area

PROGRAM

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

Page 15: PDS LAB 1 Manual

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;

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

Page 16: PDS LAB 1 Manual

}

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

RESULT

Thus areas of various shapes were computed using function.

Page 17: PDS LAB 1 Manual

Ex No:2-B 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)

PROGRAM

#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

RESULT

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

call.

Page 18: PDS LAB 1 Manual

Ex No:2-C 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 A , i = 0,1,2,…n–1

Assume first element A to be max

Compare each array element A with maxi

If max <A then max = Ai

Print maxi

Stop

PROGRAM

#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

RESULT

Thus a C program for finding maximum element of an array was executed and the output

was obtained.

Page 19: PDS LAB 1 Manual

Ex No:2-D MATRIX ADDITION

Date:

AIM:

To write a C Program to perform Matrix Addition using array.

ALGORITHM:

Start

Declare variables

Get the rows and columns of two matrices M, N, O, and P respectively.

Check N is not equal to O, if go to step 10.

Set a loop and get the elements of first matrix A[i][i].

Set a loop and get the elements of second matrix B[i][j].

Initialise C[i][j]=0 & Add the two matrices and store the resultant in C[i][j]= A[i][k]+B[k][j].

Print the resultant matrix C[i][j]

Print the message “Column of first matrix must be same as row of second matrix”.

Stop

PROGRAM

#include<stdio.h>

#include<conio.h>

void main()

{

int a[25][25],b[25][25],c[25][25],i,j,m,n;

clrscr();

printf("\nMATRIX ADDITION");

printf("\nEnter the row n column of 2 matrices:");

scanf("%d%d",&m,&n);

printf("\nEnter the Elements of A matrix");

printf("\n");

for(i=0;i<m;i++)

{

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

scanf("%d",&a[i][j]);

}

printf("\nEnter the Elements of B matrix");

printf("\n");

for(i=0;i<m;i++)

{

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

scanf("%d",&b[i][j]);

}

printf("\nThe elements of A matrix are:");

for(i=0;i<m;i++)

{

printf("\n");

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

printf("\t%d",a[i][j]);

}

printf("\nThe elements of B matrix are:");

Page 20: PDS LAB 1 Manual

for(i=0;i<m;i++)

{

printf("\n");

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

printf("\t%d",b[i][j]);

}

printf("\nThe resultant matrix:");

for(i=0;i<m;i++)

{

printf("\n");

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

{

c[i][j]=a[i][j]+b[i][j];

printf("\t %d",c[i][j]);

} }

getch();

}

OUTPUT

RESULT

Thus a C program for the implementation of matrix addition was executed and the output was

obtained.

Page 21: PDS LAB 1 Manual

Ex No:2-E MATRIX MULTIPLICATION

Date:

AIM:

To write a C Program to perform Matrix multiplication using array.

ALGORITHM:

Start

Declare variables

Get the rows and columns of two matrices M, N, O, and P respectively.

Check N is not equal to O, if go to step 10.

Set a loop and get the elements of first matrix A[i][i].

Set a loop and get the elements of second matrix B[i][j].

Repeat the step 6 until i<m, j<p and k<n.

Initialise C[i][j]=0 and multiply the two matrices and store the resultant in

C[i][j]= C[i][j]+A[i][k]*B[k][j].

Print the resultant matrix C[i][j] and go to step 11.

Print the message “Column of first matrix must be same as row of second matrix”.

Stop

PROGRAM

#include<stdio.h>

#include<conio.h>

void main()

{

int a[10][10],b[10][10],c[10][10],i,j,k,m,n,o,p;

clrscr();

printf("\nMATRIX MULTIPLICATION\n");

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

printf("\nEnter the rows & columns of first matrix: ");

scanf("%d %d",&m,&n);

printf("\nEnter the rows & columns of second matrix: ");

scanf("%d %d",&o,&p);

if(n!=o)

{

printf("Matrix mutiplication is not possible");

printf("\nColumn of first matrix must be same as row of second matrix");

}

else

{

printf("\nEnter the First matrix-->");

for(i=0;i<m;i++)

{

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

{ scanf("%d",&a[i][j]);

} }

printf("\nEnter the Second matrix-->");

for(i=0;i<o;i++)

{ for(j=0;j<p;j++)

{

scanf("%d",&b[i][j]);

Page 22: PDS LAB 1 Manual

} }

printf("\n\nThe First matrix is\n");

for(i=0;i<m;i++)

{

printf("\n");

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

{

printf("%d\t",a[i][j]);

} }

printf("\n\nThe Second matrix is\n");

for(i=0;i<o;i++)

{

printf("\n");

for(j=0;j<p;j++)

{

printf("%d\t",b[i][j]);

} }

for(i=0;i<m;i++) //row of first matrix

{

for(j=0;j<p;j++) //column of second matrix

{

c[i][j]=0;

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

{

c[i][j]= c[i][j]+a[i][k]*b[k][j];

} } }

printf("\n\nThe multiplication of two matrix is\n");

for(i=0;i<m;i++)

{

printf("\n");

for(j=0;j<p;j++)

{

printf("%d\t",c[i][j]);

} }

getch();

}

OUTPUT

RESULT

Thus a C program for the implementation of matrix multiplication was executed and the output was

obtained.

Page 23: PDS LAB 1 Manual

Ex No:2-F PALINDROME

Date:

AIM:

To write a C Program to find whether the given string is Palindrome or not without using

string functions.

ALGORITHM:

Start

Declare variables and character array with necessary size.

Get the string STR

Set a while loop to count the character in the string. WHILE (STR [++J]! ='\0')

Decrement the character position (i.e.) to reach last position by J--;

Set a while loop to check the each character until it reaches the end of the string. If WHILE

(I<J) is fails then go to flag

Check IF (STR [I++]! = STR [J--]), then set flag=1. Else, increment I and decrement J

If two strings are same i.e flag = 0 then print as “Palindrome” else print as “Not Palindrome”.

Stop

PROGRAM

#include<stdio.h>

void main()

{

char str[100];

int i=0,j=-1,flag=0;

clrscr();

printf("\nPRG TO FIND WHETHER THE GIVEN STRING IS PALINDROME OR NOT");

printf("\n\nEnter a string: ");

scanf("%s",str);

while(str[++j]!='\0');

j--;

while(i<j)

{

if(str[i++] != str[j--])

{

flag=1;

break;

} }

if(flag == 0)

printf("\n\nThe string %s is a palindrome.", str);

else

printf("\n\nThe string %s is not a palindrome.", str);

getch();

}

OUTPUT

Enter the string:malayalam

Reversed string is:malayalam

Given string is a palindrome

RESULT

Thus a C Program to find whether the given string is Palindrome or not without using string functions

was executed and the output was obtained.

Page 24: PDS LAB 1 Manual

Ex No:2-G Paragraph Analysis

Date:

AIM

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

White spaces.

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

PROGRAM

#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' :

Page 25: PDS LAB 1 Manual

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:

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

RESULT

Thus statistics of the given paragraph was determined

Page 26: PDS LAB 1 Manual

STRUCTURES AND LINKED LISTS

C supports a constructed (user-defined) data type known as structure, which is a method of packing

related data of different types i.e., heterogeneous elements. A single structure may contain integer,

floating-point, character, arrays and pointer elements. The individual elements are referred as

members. Each member within a structure is assigned its own unique storage area. The amount of

memory required to store structure is sum of storage capacity of all members. Each individual

member of a structure is accessed by means of a member selector (.) operator.

struct student

{ int no;

char name[10],grade;

int m1,m2,m3,m4,m5;

float total,avg;

};

Union is similar to structures. The members that compose a union all share the same storage area.

The amount of memory required is same as that required for its largest member.

union student

{ int no;

char name[10],grade;

int m1,m2,m3,m4,m5;

float total,avg;

};

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

Such structures are very useful in applications involving linked data structures such as list and trees.

A linked list is a set of nodes where each node has two field’s data and a link. The link field points to

the next node by storing address of the next node. Operations on a linked list include insertion and

deletion of a node and traversal of the list. Backward traversal is not possible in a singly linked list.

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.

Page 27: PDS LAB 1 Manual

Ex No:3-A STUDENTS RECORDS USING STRUCTURE

Date:

AIM:

To write a C Program to maintain students records using structure.

ALGORITHM:

Start

Declare the Structure Student with data members such as no, name, m1, m2, m3, m4,

m5, total, avg and grade.

Get the number of students N

Set a for loop up to N to get the student details as input.

Enter the Student details such as Roll no, Name, Mark1, Mark2, Mark3,

Mark4, Mark5.

Calculate Total and Avg, Grade.

Repeat Step 4.1 and 4.2 up to N.

Print Student Roll No, Name, Total, Avg and Grade.

Stop.

PROGRAM:

#include<stdio.h>

#include<conio.h>

struct student

{

int no;

char name[10],grade;

int m1,m2,m3,m4,m5;

float total,avg;

};

struct student s[5];

void main()

{

int n,i;

clrscr();

printf("\nSTUDENTS RECORDS USING STRUCTURE");

printf("\n\nEnter the no. of students:");

scanf("%d",&n);

printf("\nINSERT FIRST RECORD....\n");

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

{

printf("\nRoll No.=");

scanf("%d",&s[i].no);

printf("Name=");

scanf("%s",s[i].name);

printf("Mark1=");

scanf("%d",&s[i].m1);

printf("Mark2=");

scanf("%d",&s[i].m2);

printf("Mark3=");

Page 28: PDS LAB 1 Manual

scanf("%d",&s[i].m3);

printf("Mark4=");

scanf("%d",&s[i].m4);

printf("Mark5=");

scanf("%d",&s[i].m5);

s[i].total=s[i].m1+s[i].m2+s[i].m3+s[i].m4+s[i].m5;

s[i].avg=s[i].total/5;

if(s[i].avg<50)

s[i].grade='D';

else if(s[i].avg<60)

s[i].grade='C';

else if(s[i].avg<80)

s[i].grade='B';

else s[i].grade='A';

if(i!=n)

{

printf("\n\nINSERT NEXT RECORD....\n");

}

else

{

printf("\nRECORD INSERTED SUCCESSFULLY.....\n\n");

} }

printf("\n");

printf("\nSTUDENT RECORD\t\tNO.\tNAME\tTOTAL\tAVG\tGRADE\n");

printf("\n--------------\t\t---\t----\t-----\t---\t-----\n");

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

{

printf("\nSTUDENT RECORD[%d]:\t",i);

printf("%d\t%s\t%.2f\t%.2f\t %c",s[i].no,s[i].name,s[i].total,s[i].avg,s[i].grade);

}

getch();

}

OUTPUT

RESULT

Thus a C program to implement the student records using structure was executed and the

output was obtained.

Page 29: PDS LAB 1 Manual

Ex No:3-B PAYROLL PROCESSING USING UNION

Date:

AIM:

To write a C Program to create payroll processing using union.

ALGORITHM:

Start

Declare the Union Employee with data members such as name, eno, basic, salary, net salary,

gross.

Get the details of an employee.

Enter the employee details such as Name, Emp No and Basic salary.

Copy the emp.ename to Name by using STRCPY(NAME,EMP.ENAME) and assign,

ID=EMP.ENO, BASIC=EMP.BSAL.

Calculate HRA=10%*BASIC, DA=35%*BASIC, and TDS=15%*BASIC

Calculate GROSS=BASIC+HRA+DA and NET SALARY=GROSS-TDS

Print Employee salary details such as Name, Id, Basic, HRA, DA, TDS, GROSS, and NET

SALARY.

Stop.

PROGRAM:

#include<stdio.h>

#include<conio.h>

union employee

{

char ename[30];

int eno;

float bsal;

};

void main()

{

union employee emp;

char name[30];

int id;

float basic,hra,da,tds,net,gross;

clrscr();

printf("\EMPLOYEE PAYROLL PROCESSING\n");

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

printf("\nDETAILS OF THE EMPLOYEE\n\n");

printf("\nEnter the Employee Name: ");

scanf("%s",emp.ename);

strcpy(name,emp.ename);

printf("\nEnter the Employee Id: ");

scanf("%d",&emp.eno);

id=emp.eno;

printf("\nEnter the Basic Salary: ");

scanf("%f",&emp.bsal);

basic=emp.bsal;

hra=basic*.10;

Page 30: PDS LAB 1 Manual

da=basic*.35;

tds=basic*.15;

gross=basic+hra+da;

net=gross-tds;

printf("\n\nSALARY DETAILS FOR THE MONTH\n");

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

printf("\n\nEmployee Name\t: %s",name);

printf("\n\nEmployee No.\t: %d",id);

printf("\n\nBasic salary\t: %.2f",basic);

printf("\n\nHRA\t\t: %.2f",hra);

printf("\n\nDA\t\t: %.2f",da);

printf("\n\nTDS\t\t: %.2f",tds);

printf("\n\nGross Salary\t: %.2f",gross);

printf("\n\nNet Salary\t: %.2f",net);

getch();

}

OUTPUT

RESULT

Thus a C program to implement the payroll processing using union was executed and the output was

obtained.

Page 31: PDS LAB 1 Manual

Ex No:3-C SINGLY LINKED LIST

Date:

AIM

To write a C program for 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

PROGRAM

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct node

{

int data;

struct node *next;

}*head;

void append(int num)

{

struct node *temp,*right;

temp= (struct node *)malloc(sizeof(struct node));

temp->data=num;

right=(struct node *)head;

while(right->next != NULL)

right=right->next;

right->next =temp;

right=temp;

right->next=NULL;

}

void add( int num )

Page 32: PDS LAB 1 Manual

{

struct node *temp;

temp=(struct node *)malloc(sizeof(struct node));

temp->data=num;

if (head== NULL)

{

head=temp;

head->next=NULL;

}

else

{

temp->next=head;

head=temp;

} }

void addafter(int num, int loc)

{

int i;

struct node *temp,*left,*right;

right=head;

for(i=1;i<loc;i++)

{

left=right;

right=right->next;

}

temp=(struct node *)malloc(sizeof(struct node));

temp->data=num;

left->next=temp;

left=temp;

left->next=right;

return;

}

void insert(int num)

{

int c=0;

struct node *temp;

temp=head;

if(temp==NULL)

{

add(num);

}

else

{

while(temp!=NULL)

{

if(temp->data<num)

c++;

temp=temp->next;

}

Page 33: PDS LAB 1 Manual

if(c==0)

add(num);

else if(c<count())

addafter(num,++c);

else

append(num);

} }

int delete(int num)

{

struct node *temp, *prev;

temp=head;

while(temp!=NULL)

{

if(temp->data==num)

{

if(temp==head)

{

head=temp->next;

free(temp);

return 1;

}

else

{

prev->next=temp->next;

free(temp);

return 1;

} }

else

{

prev=temp;

temp= temp->next;

} }

return 0;

}

void display(struct node *r)

{

r=head;

if(r==NULL)

{

return;

}

while(r!=NULL)

{

printf("%d ",r->data);

r=r->next;

}

printf("\n");

}

Page 34: PDS LAB 1 Manual

int count()

{

struct node *n;

int c=0;

n=head;

while(n!=NULL)

{

n=n->next;

c++;

}

return c;

}

int main()

{

int i,num;

clrscr();

struct node *n;

head=NULL;

while(1)

{

printf("\n List Operations \n");

printf("===============\n");

printf("1.Insert\t");

printf("2.Display\t");

printf("3.Size\t");

printf("4.Delete\t");

printf("5.Exit\n");

printf("Enter your choice : ");

if(scanf("%d",&i)<=0){

printf("Enter only an Integer\n");

exit(0);

} else

{

switch(i)

{

case 1:

printf("Enter the number to insert : ");

scanf("%d",&num);

insert(num);

break;

case 2:

if(head==NULL)

{

printf("List is Empty\n");

}

else

{

printf("Element(s) in the list are : ");

Page 35: PDS LAB 1 Manual

}

display(n);

break;

case 3:

printf("Size of the list is %d\n",count());

break;

case 4:

if(head==NULL)

printf("List is Empty\n");

else{

printf("Enter the number to delete : ");

scanf("%d",&num);

if(delete(num))

printf("%d deleted successfully\n",num);

else

printf("%d not found in the list\n",num);

}

break;

case 5:

return 0;

default:

printf("Invalid option\n");

} } }

return 0;

}

OUTPUT

RESULT

Thus operation on single linked list is performed Successfully

Page 36: PDS LAB 1 Manual

Ex No:3-D DOUBLY LINKED LIST

Date:

AIM

To write a C program for singly linked list node and perform operations such as insertions

and deletions dynamically.

PROGRAM

#include <stdio.h>

#include <conio.h>

#include <malloc.h>

struct node

{

struct node *prev;

int info;

struct node *next;

}*start;

main()

{

int choice,n,m,po,i;

start=NULL;

while(1)

{

printf("1.Create List\t");

printf("2.Add at begining\t");

printf("3.Add after\t");

printf("4.Delete\t");

printf("5.Display\t");

printf("6.Count\t");

printf("7.Reverse\t");

printf("8.exit\n");

printf("Enter your choice : ");

scanf("%d",&choice);

switch(choice)

{

case 1:

printf("How many nodes you want : ");

scanf("%d",&n);

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

{

printf("Enter the element : ");

scanf("%d",&m);

create_list(m);

}

break;

case 2:

printf("Enter the element : ");

Page 37: PDS LAB 1 Manual

scanf("%d",&m);

addatbeg(m);

break;

case 3:

printf("Enter the element : ");

scanf("%d",&m);

printf("Enter the position after which this element is inserted : ");

scanf("%d",&po);

addafter(m,po);

break;

case 4:

printf("Enter the element for deletion : ");

scanf("%d",&m);

del(m);

break;

case 5:

display();

break;

case 6:

count();

break;

case 7:

rev();

break;

case 8:

exit();

default:

printf("Wrong choice\n");

}/*End of switch*/

}/*End of while*/

}/*End of main()*/

create_list(int num)

{

struct node *q,*tmp;

tmp= malloc(sizeof(struct node));

tmp->info=num;

tmp->next=NULL;

if(start==NULL)

{

tmp->prev=NULL;

start->prev=tmp;

start=tmp;

}

else

{

q=start;

while(q->next!=NULL)

Page 38: PDS LAB 1 Manual

q=q->next;

q->next=tmp;

tmp->prev=q;

}

}/*End of create_list()*/

addatbeg(int num)

{

struct node *tmp;

tmp=malloc(sizeof(struct node));

tmp->prev=NULL;

tmp->info=num;

tmp->next=start;

start->prev=tmp;

start=tmp;

}/*End of addatbeg()*/

addafter(int num,int c)

{

struct node *tmp,*q;

int i;

q=start;

for(i=0;i<c-1;i++)

{

q=q->next;

if(q==NULL)

{

printf("There are less than %d elements\n",c);

return;

}

}

tmp=malloc(sizeof(struct node) );

tmp->info=num;

q->next->prev=tmp;

tmp->next=q->next;

tmp->prev=q;

q->next=tmp;

}/*End of addafter() */

del(int num)

{

struct node *tmp,*q;

if(start->info==num)

{

tmp=start;

start=start->next; /*first element deleted*/

start->prev = NULL;

free(tmp);

Page 39: PDS LAB 1 Manual

return;

}

q=start;

while(q->next->next!=NULL)

{

if(q->next->info==num) /*Element deleted in between*/

{

tmp=q->next;

q->next=tmp->next;

tmp->next->prev=q;

free(tmp);

return;

}

q=q->next;

}

if(q->next->info==num) /*last element deleted*/

{ tmp=q->next;

free(tmp);

q->next=NULL;

return;

}

printf("Element %d not found\n",num);

}/*End of del()*/

display()

{

struct node *q;

if(start==NULL)

{

printf("List is empty\n");

return;

}

q=start;

printf("List is :\n");

while(q!=NULL)

{

printf("%d ", q->info);

q=q->next;

}

printf("\n");

}/*End of display() */

count()

{ struct node *q=start;

int cnt=0;

while(q!=NULL)

{

q=q->next;

Page 40: PDS LAB 1 Manual

cnt++;

}

printf("Number of elements are %d\n",cnt);

}/*End of count()*/

rev()

{

struct node *p1,*p2;

p1=start;

p2=p1->next;

p1->next=NULL;

p1->prev=p2;

while(p2!=NULL)

{

p2->prev=p2->next;

p2->next=p1;

p1=p2;

p2=p2->prev; /*next of p2 changed to prev */

}

start=p1;

}/*End of rev()*/

OUTPUT

RESULT

Thus operations on doubly linked list is performed successfully.

Page 41: PDS LAB 1 Manual

Ex No:4-A SEQUENTIAL FILE ACCESS

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

PROGRAM

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

Page 42: PDS LAB 1 Manual

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

getch();

}

OUTPUT

RESULT

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

Page 43: PDS LAB 1 Manual

Ex No:4-B RANDOM FILE ACCESS

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

PROGRAM

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

Page 44: PDS LAB 1 Manual

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

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

}

else

printf("\n Incorrect Employee Id \n");

fclose(fd2);

}

OUTPUT

RESULT

Thus random access is performed to directly obtain employee details.

Page 45: PDS LAB 1 Manual

Ex No:4-C 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

PROGRAM #include <stdio.h> #include<conio.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); getch(); }

OUTPUT

mycp hello.c hello1.c

File Copied

RESULT

Thus file is copied using character-based sequential operation.

Page 46: PDS LAB 1 Manual

STACKS AND QUEUES

The stack is a list of elements placed on top of each other. A pointer always points to the topmost

position of a stack called top. The two possible operations on stack is push and pop. It is

implemented either using arrays or linked lists. The top is an indicator where both push and pop

operations are performed. CDs in a disc spindle are an example of stack.

The insertion operation is termed as push. For each insertion the pointer top is incremented so

that it retains the top-most position in the stack. The deletion operation of stack is termed as pop.

Stack follows LIFO (Last In First Out) method i.e., the last inserted element would be the first

element to be deleted. The pointer top is made to point the next element in order.

In a Queue, the set of elements are placed one after another, just like people standing in a queue

at a reservation counter. In a Queue, there are two pointers namely front and rear. 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 at the REAR end the

pointer is updated. Deletion is performed at the FRONT end removing the oldest element and the

pointer is updated.

Stack Queue

Applications of stack include infix to postfix conversion and evaluation of expression in postfix

form. An infix arithmetic expression can be converted into a postfix expression if precedence of

operators is known. Operators are sandwiched between operands in an infix expression whereas

operators appear after operands in postfix form. Expression in postfix form is evaluated by

applying operators on operands to its immediate left.

Page 47: PDS LAB 1 Manual

Ex No:5-A STACK USING 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

PROGRAM

#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

{

Page 48: PDS LAB 1 Manual

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

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:

Page 49: PDS LAB 1 Manual

printf("\n Invalid Choice \n");

}

}

}

OUTPUT

RESULT

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

Page 50: PDS LAB 1 Manual

Ex No:5-B APPLICATION OF STACK: INFIX TO POSTFIX EXPRESSION EVALUATION

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

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.

PROGRAM

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

Page 51: PDS LAB 1 Manual

} } int isoperator(char symbol) { switch(symbol) { case '+': case '-': case '*': case '/': case '^': case '$': case '(': case ')': return 1; break; default: return 0; } } void convertip(char infix[],char postfix[]) { int i,symbol,j = 0; stack[++top] = '#'; for(i=0;i<strlen(infix);i++) { symbol = infix[i]; if(isoperator(symbol) == 0) { 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++; }

Page 52: PDS LAB 1 Manual

push(symbol); } } } } while(stack[top] != '#') { postfix[j] = pop(); 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

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

Page 53: PDS LAB 1 Manual

Ex No:5-C APPLICATION OF STACK: POSTFIX TO INFIX 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.

PROGRAM #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 '+':

Page 54: PDS LAB 1 Manual

d1 = s.a[s.top--]; d2 = s.a[s.top--]; s.a[++s.top] = d1 + d2; break; case '-': d2 = s.a[s.top--]; d1 = s.a[s.top--]; s.a[++s.top] = d1 - d2; break; case '*': d2 = s.a[s.top--]; d1 = s.a[s.top--]; s.a[++s.top] = d1*d2; break; case '/': d2 = s.a[s.top--]; d1 = s.a[s.top--]; s.a[++s.top] = d1 / d2; break; } } printf("\n Expression value is %5.2f", s.a[s.top]); getch(); }

OUTPUT

RESULT:

Thus the given postfix expression was evaluated using stack.

Page 55: PDS LAB 1 Manual

Ex No:5-D STACK USING LINKED LIST

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

PROGRAM

#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 */

Page 56: PDS LAB 1 Manual

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

RESULT:

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

Page 57: PDS LAB 1 Manual

Ex No:5-E QUEUE USING 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

PROGRAM #include<stdio.h> #include<conio.h> void main() { int q[10]={0},i,front=-1,rear=-1,max=10,n,item; printf("\n\tMENU\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n4.EXIT\n"); do { printf("\nEnter your choice\n"); scanf("%d",&n); switch(n) { case 1: if(rear<max-1) { printf("Enter the element\n"); scanf("%d",&item); if(rear==-1) { front=0; rear=0; q[rear]=item; } else q[++rear]=item;

Page 58: PDS LAB 1 Manual

} else printf("Overflow\n"); break; case 2: if(front>=0) { printf("The deleted item =%d",q[front]); if(front==rear) { front=-1; rear=-1; } else front++; } else printf("Underflow\n"); break; case 3: if((front==-1)&&(rear==-1)) printf("The queue is empty\n"); else { printf("The elements of the queue are :"); for(i=front;i<=rear;i++) printf("%d\t",q[i]); } break; case 4: break; default: printf("Invalid choice\n"); break; } } while(n!=4); getch(); }

OUTPUT

RESULT

Thus insert and delete operations of a queue was demonstrated using arrays

Page 59: PDS LAB 1 Manual

Ex No:5-F QUEUE USING LINKED LIST

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

PROGRAM

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

Page 60: PDS LAB 1 Manual

switch(ch)

{

case 1:

temp=(struct node *)(malloc(sizeof(struct node)));

printf("Enter label for new node : ");

scanf("%d", &temp->label);

h = head;

while (h->next != NULL)

h = h->next;

h->next = temp;

temp->next = NULL;

break;

case 2:

h = head->next;

head->next = h->next;

printf("Node deleted \n");

free(h);

break;

case 3:

printf("\n\nHEAD -> ");

h=head;

while (h->next!=NULL)

{

h = h->next;

printf("%d -> ",h->label);

}

printf("NULL \n");

break;

case 4:

exit(0);

} } }

OUTPUT

RESULT

Thus insert and delete operations of a stack was demonstrated using linked list.

Page 61: PDS LAB 1 Manual

Ex No:6-A 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 A and Aj To j+1

If out-of-order then swap the elements

Display array elements after each pass

Display the final sorted list

Stop

PROGRAM

#include <stdio.h>

#include <conio.h>

Void main()

{

int n, t, i, j, k, a[20], p=0;

clrscr();

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

Page 62: PDS LAB 1 Manual

printf("%d ", a[i]);

getch();

}

OUTPUT

RESULT:

Thus the elements have been sorted in array using Bubble sort.

Page 63: PDS LAB 1 Manual

Ex No:6-B 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 vary 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

PROGRAM

#include <stdio.h>

#include <conio.h>

void main()

{

int i, j, k, n, temp, a[20], p=0;

clrscr();

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

getch(); }

OUTPUT

Page 64: PDS LAB 1 Manual

RESULT

Thus the elements have been sorted in array using insertion sort.

Page 65: PDS LAB 1 Manual

Ex No:6-C 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 vary from first to last but one element

Inner index j is used to compare from i+1thelement to last element.

Find the smallest element. Swap ith element and the smallest element

Display the array elements after each pass

Display the sorted array elements.

Stop

PROGRAM

#include <stdio.h>

#include <conio.h>

void main()

{

int n, i, j, k, t, min, a[20], p=0;

clrscr();

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

Page 66: PDS LAB 1 Manual

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

printf("%d ", a[i]);

getch();

}

OUTPUT

RESULT

Thus the elements have been sorted in array using Selection sort.

Page 67: PDS LAB 1 Manual

Ex No:6-D 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:

Recursively quick sort both sets (Ai < x and Ai > x)

Display the sorted array elements

Stop

PROGRAM

#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])

Page 68: PDS LAB 1 Manual

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

}}

OUTPUT

RESULT

Thus the elements have been sorted in array using Quick sort.

Page 69: PDS LAB 1 Manual

Ex No:6-E 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

PROGRAM

#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])

Page 70: PDS LAB 1 Manual

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

}}

OUTPUT

RESULT

Thus the elements have been sorted in array using Merge sort.

Page 71: PDS LAB 1 Manual

Ex No:6-F 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 h to determine how far apart elements are to be sorted t

Sort elements at distance h , then elements at ht....t-1 , etc.

Finally sort the array using insertion sort.

Display the sorted array elements.

Stop

PROGRAM

#include <stdio.h>

#include <conio.h>

void main()

{

int n, i, j, k, temp, x, arr[100];

clrscr();

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("\n After Pass :");

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

printf("%d ", arr[x]);

}

Page 72: PDS LAB 1 Manual

printf("\n Sorted List: ");

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

printf("%d ", arr[i]);

getch();

}

OUTPUT

RESULT

Thus the elements have been sorted in array using shell sort.

Page 73: PDS LAB 1 Manual

SEARCHING

Searching is the process of locating a particular element in an array. The two searching techniques

are: 1.Linear search 2.Binary search

Linear search involves each element to be compared against the key value starting from the first

element. Linear search uses a for structure containing an if structure to compare each element of an

array with a search key. If search key is not found, then value of –1 is returned. If the array being

searched is not in any particular order, then half the elements of an array are likely to compare.

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 sub array or

until the sub array 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.

Page 74: PDS LAB 1 Manual

Ex No:7-A 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 A i, i = 0,1,2,…n–1

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

PROGRAM

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

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)

Page 75: PDS LAB 1 Manual

printf("\n Element not found");

getch();

}

OUTPUT

RESULT

Thus the elements have been found in array using linear search.

Page 76: PDS LAB 1 Manual

Ex No:7-B 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

PROGRAM

#include <stdio.h>

#include <conio.h>

void main()

{

int a[50],i, n, upper, lower, mid, val, found, att=0;

clrscr();

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

scanf("%d", &val);

upper = n;

lower = 0;

found = -1;

while (lower <= upper)

{

mid = (upper + lower)/2;

att++;

if (a[mid] == val)

{

Page 77: PDS LAB 1 Manual

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

getch();

}

OUTPUT

RESULT

Thus the elements have been found in array using Binary search.