Sie sind auf Seite 1von 137

Department of Information Technology

214447: PROGRAMMING LABORATORY

SE IT (2015 Course)

Semester I

Teaching Scheme: - Examination Scheme:


Practical: 4 Hrs/Week Term Work: 25 Marks

Theory: 4 Hr/Week Practical: 50 Marks

LABORATORY MANUAL V 3.7

DEPARTMENT OF INFORMATION TECHNOLOGY


2017-2018

SE (IT) (SEMESTER I) 1 Programming Laboratory (2017-


2018)
Department of Information Technology

VISION

To provide excellent Information Technology education by building strong teaching and research environment.

MISSION

1) To transform the students into innovative, competent and high quality IT professionals to meet the growing global
challenges.
2) To achieve and impart quality education with an emphasis on practical skills and social relevance.
3) To endeavor for continuous up-gradation of technical expertise of students to cater to the needs of the society.
4) To achieve an effective interaction with industry for mutual benefits.

SE (IT) (SEMESTER I) 2 Programming Laboratory (2017-


2018)
Department of Information Technology

PROGRAM EDUCATIONAL OBJECTIVES

The students of Information Technology course after passing out will

1) Graduates of the program will possess strong fundamental concepts in mathematics, science, engineering and
Technology to address technological challenges.

2) Possess knowledge and skills in the field of Computer Science & Engineering and Information Technology for analyzing,
designing and implementing complex engineering problems of any domain with innovative approaches.

3) Possess an attitude and aptitude for research, entrepreneurship and higher studies in the field of Computer Science &
Engineering and Information Technology.

4) Have commitment to ethical practices, societal contributions through communities and life-long learning.

5) Possess better communication, presentation, time management and team work skills leading to responsible & competent
professionals and will be able to address challenges in the field of IT at global level.

SE (IT) (SEMESTER I) 3 Programming Laboratory (2017-


2018)
Department of Information Technology

PROGRAM OUTCOMES

The students in the Information Technology course will attain:

a. an ability to apply knowledge of computing, mathematics including discrete mathematics as well as probability
and statistics, science, and engineering and technology;
b. an ability to define a problem and provide a systematic solution with the help of conducting experiments, as
well as analyzing and interpreting the data;
c. an ability to design, implement, and evaluate a software or a software/hardware system, component, or
process to meet desired needs within realistic constraints;
d. an ability to identify, formulate, and provide systematic solutions to complex engineering problems;
e. an ability to use the techniques, skills, and modern engineering technologies tools, standard processes
necessary for practice as a IT professional;
f. an ability to apply mathematical foundations, algorithmic principles, and computer science theory in the
modeling and design of computer-based systems with necessary constraints and assumptions;
g. an ability to analyze the local and global impact of computing on individuals, organizations and society;
h. an ability to understand professional, ethical, legal, security and social issues and responsibilities;
i. an ability to function effectively as an individual or as a team member to accomplish a desired goal(s);
j. an ability to engage in life-long learning and continuing professional development to cope up with fast
changes in the technologies/tools with the help of electives, professional organizations and extra-curricular
activities;
k. an ability to communicate effectively in engineering community at large by means of effective presentations,
report writing, paper publications, demonstrations;
l. an ability to understand engineering, management, financial aspects, performance, optimizations and time
complexity necessary for professional practice;
m. an ability to apply design and development principles in the construction of software systems of varying
complexity.

SE (IT) (SEMESTER I) 4 Programming Laboratory (2017-


2018)
Department of Information Technology

PREFACE
INTRODUCTION

This laboratory exercises are designed with a dual purpose: (1) to provide the student with “hands-on” experience in
the C Programming concepts through the implementation of several programs and (2) to provide an atmosphere
where the student will be required to communicate, both in written and oral form.

It is the responsibility of the student to perform required preparation for lab work. These labs will require some
preparation prior to arriving in the lab.

Students will submit Term Work in the form of a journal that will include at 11 assignments.

Each programming assignment will consists of pseudo-algorithm, program listing with proper documentation and
printout of the output.

REQUIRED LABORATORY PROCEDURES

1. The implementation required of any program should be completed during the scheduled lab timings.
2. Always come to the lab fully prepared i.e. the topics covered in the classroom.
3. All the students must report to the lab on time.
4. All the students must carry a lab notebook, without which students won’t be allowed to enter lab.
Failure to any of the above three will result in a reduced grade.

SE (IT) (SEMESTER I) 5 Programming Laboratory (2017-


2018)
Department of Information Technology

INDEX

Sr. No. Title Of Assignment

1 Set Operations
2 Matrix Operations
3 String Operations
4 Structure Operations
5 Binary Searching ,Bubble Sort and Selection Sort on Strings
6 Sequential File
7 Quick Sort/ Merge Sort
8 Sparse Matrix
9 Singly Linked List Operations
10 Polynomial Operations using CLL
11 Doubly Linked List Operations
12 Generalized Linked List

SE (IT) (SEMESTER I) 6 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 01

Title Set Operations

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 7 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 01

Title : Operations on Sets

Problem Statement :
Represent sets using one dimensional arrays and implement functions to perform:
➢ Union of two Sets
➢ Intersection of two Sets
➢ Difference of two Sets
➢ Symmetric Difference of two Sets

Problem Definition :
Sets : A Set is a collection of well-defined objects. Sets are usually denoted by capital letters A, B, C,
… etc.
e.g. A = { 1, 5, 8, 10 }

Membership : Objects that form a set are called members or elements of the set. An Object x is a
member of set A, if x is one of the elements of set A. It is denoted by x  A.
Let A = { 1, 5, 8, 10 } then 5  A but 4  A.

Equality of Sets : If two sets A and B have the same elements, they are said to be equal sets. We
write this as A = B.
Let A = { 1, 2 } B = { 1 , 2 }, Then A = B.

Union of Sets :Union of two sets A and B is a set of those elements which belong to A or to B or both
A and B. It is denoted by A  B.
A  B = { x | x  A or x  B or x  both A and B }
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }
A  B = { 1, 3, 5, 8, 10, 12 }

Intersection of Sets : Intersection of two sets A and B is a set of those elements which belong to both
A and B. It is denoted by A  B.
A  B = { x | x  A and x  B }
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }
A  B = { 5, 10 }

Difference of Sets : Difference of two sets A and B is a set of those elements which are present in A
but not in B. It is denoted by A - B.
A – B = { x | x  A and x  B }
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }
A - B = { 1, 8 }

Symmetric Difference : Symmetric Difference of two sets A and B is a set of those elements that are
present in A and B but not in both. It is denoted by A  B.

SE (IT) (SEMESTER I) 8 Programming Laboratory (2017-


2018)
Department of Information Technology

A  B = (A – B)  (B – A)
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }
A  B = { 1, 3 , 8 , 12 }

Array : An array is a collection of variables that are of the same data type. Each item in an array is
called an element. All elements in an array are referenced by the name of the array and are stored in a
set of consecutive memory slots.
Arrays are collection of homogeneous data types. As with most computers arrays provide a common
name to the collection of that data type where each element can be referred to with an index number.

Algorithms :
1. Algorithm for accepting a Set
Algorithm Accept_Array ( A ) where A is the array

1 Start

2 Accept the no. of elements in the Set , say n

3 Initialize i = 0

4 Check if i is less than n , if no go to step no. 8

5 Accept a element from the user and store it in A(i)

6 Increment the value of i

7 Go to step No. 4

8 Return n

9 Stop

2. Algorithm for Displaying a Set


Algorithm Display_Array ( A , n ) where A is the array and n is the no. of elements in array A

1 Start

2 Initialize i = 0

3 Check if i is less than n , if no go to step no. 7

4 Display the element A(i)

5 Increment the value of i

6 Go to step No. 3

7 Stop

SE (IT) (SEMESTER I) 9 Programming Laboratory (2017-


2018)
Department of Information Technology

3. Algorithm for checking Membership operation


Algorithm Membership(int A[],int n)

1 Start

2 Accept the element to be checked for membership

3 Initialize i =0

4 While ( i is less than n)

5 If ( x == A[i] )

6 break;

7 Increment i

8 end if

9 end loop

10 If ( i < n )

11 Display that x is the member of array A

12 Else

13 Display that x is not the member of array A

14 End if

15 Stop

4. Algorithm for checking Equality of two Sets


Algorithm Equality_of_sets(int A[], int na, int B[], int na)

1 Start

2 If ( na != nb )

3 Display the sets are not equal and go to step no 11

4 For i = 0 to na-1 do

5 Check if A[i] is present in the Array B

6 If not present

7 Display the sets are not equal and go to step no. 11

8 End if

9 End for

10 Display the sets are equal

SE (IT) (SEMESTER I) 10 Programming Laboratory (2017-


2018)
Department of Information Technology

11 Stop
5. Algorithm for finding union of two Sets
Algorithm find_union(int A[], int na, int B[], int nb)

1 Start

2 Copy all elements of Array A to resultant Array C.

3 Initialize the no. of elements in Array C , nc = na

4 For i = 0 to nb – 1

5 Check if B[i] is present in the Array A

6 If not present

7 Add B[i] to C[nc]

8 Increment nc

9 End if

10 End for

11 Display the Resultant Array C

12 Stop

6. Algorithm for finding intersection of two Sets


Algorithm find_intersection(int A[], int na, int B[],int nb)

1 Start

2 Let C be a Array in which we will find the intersection set and nc be the no. of elements in Array C

3 Initialize nc = 0

4 For i = 0 to na – 1 do

5 Check if A[i] is present in the Array B

6 If present

7 Add A[i] to C[nc]

8 Increment nc

9 End if

10 End for

11 Display the Resultant Array C

12 Stop

SE (IT) (SEMESTER I) 11 Programming Laboratory (2017-


2018)
Department of Information Technology

7. Algorithm for finding difference of two Sets


Algorithm find_difference(int A[], int na, int B[],int nb)

1 Start

2 Let C be a Array in which we will find the difference set and nc be the no. of elements in Array C

3 Initialize nc = 0

4 For i = 0 to na – 1 do

5 Check if A[i] is present in the Array B

6 If not present

7 Add A[i] to C[nc]

8 Increment nc

9 End if

10 End for

11 Display the Resultant Array C

12 Stop

8. Algorithm for finding symmetric difference of two Sets

Algorithm find_symmetric_difference(int A[], int na, int B[],int nb)

1 Start

2 Let C be a Array in which we will find the symmetric difference set and nc be the no. of elements in Array C

3 Find A U B and store the result in Array P

4 Fine A ∩ B and store the result in Array Q

5 Find P – Q and store the result in Array C

6 Display the Resultant Array C

7 Stop

SE (IT) (SEMESTER I) 12 Programming Laboratory (2017-


2018)
Department of Information Technology

Test Conditions:

1. Input two sets with some elements common.


2. Input two sets with no element common.
3. Input the common elements in same set.

Sample Input Output

MENU

1. Accept a Set
2. Display a Set
3. Membership
4. Equality
5. Union
6. Intersection
7. Difference
8. Symmetric Difference

Accept a Set
Enter the no. of elements in the array : 4
Enter the elements : 1 5 8 10

Display a Set
A = { 1, 5, 8, 10 }

Membership
Enter the element to be searched : 5
Element 5 is a member of set A
Equality
Accept two sets A = { 1, 2 } and B = { 1 , 2 }
The Two sets are equal.
Union
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }
A  B = { 1, 3, 5, 8, 10, 12 }
Intersection
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }
A  B = { 5, 10 }
Difference
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }
A - B = { 1, 8 }
Symmetric Difference
A = { 1, 5, 8, 10 } B = { 3, 5, 10, 12 }

SE (IT) (SEMESTER I) 13 Programming Laboratory (2017-


2018)
Department of Information Technology

A  B = { 1, 3 , 8 , 12 }

SE (IT) (SEMESTER I) 14 Programming Laboratory (2017-


2018)
Department of Information Technology

Oral Questions:

Q1. Why do you need to put comments into your programs?

Q2. Why is the main() function needed in your program?

Q3. What does the #include directive do?

Q4. Why do you need a linker?

Q5. What are %c, %d, and %f?

Q6. Why do you need to use arrays?

Q7. What is the minimum index in an array?

Q8. How do you reference an array by using a pointer?

Q9. What is the main difference between a function declaration and a function definition?

Q10. Why do we need function prototypes?

Q11. Can a function return a pointer?

Q12. What are the disadvantages / limitations of using array?

Conclusion:
Thus we have learnt to declare a single dimensional, read the elements of the array and print the elements
of the array using static method.
We have also implemented the following set operations on the arrays :
1. Membership
2. Equality
3. Union
4. Intersection
5. Difference
6. Symmetric Difference

SE (IT) (SEMESTER I) 15 Programming Laboratory (2017-


2018)
Department of Information Technology

Design Experiments:

1. Perform Set operations for character set using character Arrays


2. Allocate memory Dynamically for creating an Array and perform the operations on sets
using pointers.
3. Implement Abacus Calculator in C.

SE (IT) (SEMESTER I) 16 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 02

Title Matrix Operation

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 17 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 02

Title : Matrix Operations

Problem Statement :
Write a menu driven C program to perform following operations on matrix with and without
pointers
to arrays.
➢ Addition
➢ Multiplication
➢ Transpose
➢ saddle point

Problem Definition :
Matrix : A matrix is an m x n rectangular array of numbers with m rows and n columns.
Or A matrix is an ordered set of numbers listed in rectangular form.
The plural of matrix is matrices. It is of the form.

The (i, j)th element or entry of A is the element aij, that is, the number in the ith row and jth column
of A. A convenient shorthand notation for a matrix is A = [ aij ].

Square matrix : If a matrix A has n rows and n columns then we say it's a square matrix.

SE (IT) (SEMESTER I) 18 Programming Laboratory (2017-


2018)
Department of Information Technology

Diagonal matrix : A diagonal matrix is a square matrix with all the non-diagonal elements as 0.

Row matrix : A matrix with one row is called a row matrix

Column matrix : A matrix with one column is called a column matrix

Null-matrix : When all the elements of a matrix A are 0, we call A as Null matrix or 0-matrix.

An identity matrix I : An identity matrix I is a diagonal matrix with all diagonal element = 1.

Scalar matrix : A scalar matrix S is a diagonal matrix with all diagonal elements alike.

A symmetric matrix : A square matrix is called symmetric if it is equal to its transpose.


Then ai,j = aj,i , for all i and j.

A skew-symmetric matrix : A square matrix is called skew-symmetric if it is equal to the opposite of


its transpose.
Then ai,j = -aj,i , for all i and j.

Operations on Matrices:
1. Equality of matrices:
Two matrices are equal if and only if they have the same number of rows, the same number of
columns, and equal corresponding entries in every position ( aij=bij ).

2. Matrix addition
Addition is defined only for matrices A=[aij] and B=[bij] of the same size.
Let A = [ aij ] and B = [ bij ] be m x n matrices. The sum of A and B is an m x n matrix
C=[cij] such that,

SE (IT) (SEMESTER I) 19 Programming Laboratory (2017-


2018)
Department of Information Technology

3. Matrix Subtraction:
Let A = [ aij ] and B = [ bij ] be m x n matrices. The subtraction of A and B is an m x n matrix C=[cij]
such that.

Matrix being subtracted must have same size.

4. Matrix Multiplication
Let A be an m x k matrix and B be a k x n matrix. The product of the matrices A and B, is an m x n
matrix C

Notice that the number of columns of 1st matrix A must be equal to the number of rows of 2nd
matrix B

5. Matrix Transpose
The n x m matrix A' is the transpose of the m x n matrix A if and only if the ith row of A is equal to
the ith column of A'

The transpose of an m x n matrix A is the n x m matrix


6. Saddle point :

SE (IT) (SEMESTER I) 20 Programming Laboratory (2017-


2018)
Department of Information Technology

To determine whether a matrix has saddle point or not, we have to first find large element from each
row and store it in one dimensional array. Find small element from each column and store it in
another array. Then find smallest element from the largest elements of the rows and the largest
element from the smallest elements from the columns and compare them if they are equal then
matrix has saddle point else matrix has no saddle point

Algorithms :
1 Algorithm for accepting a Matrix
Algorithm Accept_matrix (int A[8][8] )
1 Start

2 Accept the order of the matrix as r & c


3 For i = 0 to r – 1
4 For j = 0 to c – 1
5 Accept the Element Aij
6 End For

7 End For

8 Stop

2. Algorithm for Displaying a Matrix


Algorithm display_matrix (int A[8][8], int r,int c )

1 Start
2 For i = 0 to r – 1
3 Go to new line
4 For j = 0 to c – 1
5 Display the Element Aij
6 End For

7 End For

SE (IT) (SEMESTER I) 21 Programming Laboratory (2017-


2018)
Department of Information Technology

8 Stop

SE (IT) (SEMESTER I) 22 Programming Laboratory (2017-


2018)
Department of Information Technology

3. Algorithm for checking whether two matrices are equal or not.


Algorithm Equality (A,ra,ca,B,rb,cb)

A & B are matrices and ra x ca & rb x cb is the order of matrices A & B


The Algorithm returns 1 if two matrices are equal otherwise 0
1 Start
2 If the order of both matrices are not same directly return 0
3 For i = 0 to ra – 1
4 For j = 0 to ca – 1
5 If Element Aij is not equal to Element Bij then directly return 0 // not equal
6 End For

7 End For
8 Return 1 // Equal

4. Algorithm for Adding two matrices


Algorithm Addition (A,ra,ca,B,rb,cb)

A & B are matrices and ra x ca & rb x cb is the order of matrices A & B


The Algorithm Stores the addition result in matrix C.
1 Start
2 If the order of both matrices are not same directly Display Addition not possible and go to step 9
3 For i = 0 to ra – 1
4 For j = 0 to ca – 1
5 Cij = Aij Bij
+

6 End For

7 End For
8 Display the matrix C
9 Stop

SE (IT) (SEMESTER I) 23 Programming Laboratory (2017-


2018)
Department of Information Technology

5. Algorithm for Subtraction of two matrices


Algorithm Subtraction (A,ra,ca,B,rb,cb)

A & B are matrices and ra x ca & rb x cb is the order of matrices A & B


The Algorithm Stores the Subtraction result in matrix C.
1 Start
2 If the order of both matrices are not same directly Display Subtraction not possible and go to step 9
3 For i = 0 to ra – 1
4 For j = 0 to ca – 1
5 Cij = Aij - Bij
6 End For

7 End For
8 Display the matrix C
9 Stop

6. Algorithm for Multiplication of two matrices

Algorithm Multiplication (A,ra,ca,B,rb,cb)

A & B are matrices and ra x ca & rb x cb is the order of matrices A & B


The Algorithm Stores the multiplication result in matrix C whose order will be ra x cb.
1 Start
2 If the ca ≠ rb Display Multiplication is not possible and go to step 12
3 For i = 0 to ra – 1
4 For j = 0 to cb – 1
5 Cij = 0
6 For k = 0 to ca - 1
7 Cij = Cij + (Aik * Bkj)
8 End For
9 End For

10 End For

SE (IT) (SEMESTER I) 24 Programming Laboratory (2017-


2018)
Department of Information Technology

11 Display the matrix C


12 Stop

7. Algorithm for finding Transpose of matrix

Algorithm Transpose (A,r,c)

A is a matrix whose order is r x c


The Algorithm Stores the result of transpose in matrix T whose order will be c x r.
1 Start
3 For i = 0 to ra – 1
4 For j = 0 to ca – 1
5 Tij = Aji
6 End For

7 End For
8 Display the matrix T
9 Stop

8. Algorithm for finding saddle point in matrix


Algorithm Saddle_Point(A,r,c)

A is a matrix whose order is r x c


1 Start
2 For i = 0 to r – 1
3 Max = Max of Value in row i
4 For j = 0 to ca – 1
5 Min = Minimum value in Column j
6 If Max = Min
7 Display saddle point found at row i and column j.
8 End If
9 End For

SE (IT) (SEMESTER I) 25 Programming Laboratory (2017-


2018)
Department of Information Technology

10 End For

11 Stop

Test Conditions:
1. Input two matrices with same order
2. Input two matrices with different order.
3. Input empty matrix.

Sample Input Output

MENU FOR MATRIX OPERATIONS

1. Accept
2. Display
3. Equality
4. Addition
5. Subtraction
6. multiplication
7. Transpose
8. Saddle point

Input :

1 2 3 1 3 4
A= 3 4 4 B= 1 1 1
2 2 2 2 4 1

Output :

➢ Equality

The matrices A & B are not Equal

SE (IT) (SEMESTER I) 26 Programming Laboratory (2017-


2018)
Department of Information Technology

➢ Addition

2 5 7
A+B = 4 5 5
4 6 3

➢ Subtraction

0 -1 -1
A-B = 2 3 3
0 -2 1

➢ Multiplication

9 17 9
A*B = 14 28 19
8 16 12

➢ Transpose

1 3 2 1 1 2
AT = 2 4 2 BT = 3 1 4
3 4 2 4 1 1

SE (IT) (SEMESTER I) 27 Programming Laboratory (2017-


2018)
Department of Information Technology

➢ Saddle Point

1 2 3
C = 4 5 6
7 8 9

The Saddle point of the matrix is 3 and at location(0,2).

Oral Questions:

1. Why do you need to allocate memory at runtime?


2. What does it mean if the malloc() function returns a null pointer?
3. What are the differences between the calloc() and malloc() functions?

4. Is the free() function necessary?

5. How to allocate memory dynamically for a 2D-Array of order 4 x 5 ?

6. What is the difference between int *M[10] & int (*P)[10] ?


7. How do I know how many elements an array can hold?
8. How to Allocate memory for a 3-D array of size 3 x 4 x 5
9. How does C compiler store elements in a multi-dimensional array?
10. How to find the row and column dimension of a given 2-D array?

Conclusion:

Thus we have learnt to declare a two dimensional array, read the elements of the array and print the
elements of the array using static and dynamic method.
We have also implemented the following matrix operations on the matrices:
1. Equality
2. Addition
3. Subtraction
4. Multiplication
5. Transpose
6. Saddle Point
Design Experiments:
1. Write a C program to find out the determinant of an n x n matrix.
2. Write a C program to find out the inverse of an n x n matrix.
3. Write a C program to implement Gauss elimination method.

SE (IT) (SEMESTER I) 28 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 03

Title String manipulation

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 29 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 03

Title : String Manipulation

Problem Statement :
Write a menu driven C program to Implement following operations on String with / without using
pointers(without using the library functions)
➢ String Length
➢ String Copy
➢ String Reverse
➢ String Palindrome
➢ String Compare
➢ Substring

Problem Definition :
String : A string is a character array terminated by a null character (\0).
In C, the null character can be used to mark the end of a string. A string constant is a series of
characters enclosed by double quotes. The C compiler automatically appends a null character to the
array that has been initialized by a string constant.
char str[7] = "Hello!";

Substring : A string is a substring of a main string if it is a part of the main string.

Palindrome : A string is a palindrome if reverse of the string is equal to the original string.
e.g : nitin

Different string operations are as follows :


1) int strlen( const char *str) -- Calculates string length excluding last null character.
2) char * strcpy( char *dest, const char * src) – Copies string from source to destination
3) char *strcat(char *dest, const char * src ) – Appends source string at the end of destination
and returns pointer to destination
4) int strcmp(const char *str1, const char * str2) – Does unsigned comparison of two strings
character by character and returns difference as integer.
If diff = 0 strings are equal
If diff < 0 string1 is smaller than string2
If diff > 0 string1 is greater than string2

SE (IT) (SEMESTER I) 30 Programming Laboratory (2017-


2018)
Department of Information Technology

5) char * strrev( char *str) – Reverses the input string and returns pointer to reversed
string.
6) char *strstr( char *str1, char *str2) – Checks for string2 in string1 and returns pointer to
location of first occurrence.
7) String palindrome – Checking if reversed string is same as original string.

The strlen() Function


The strlen() function can be used to measure the length of a string. This function does not
count the null character in the last element
The syntax for the strlen() function is
size_t strlen(const char *s);
Here s is a char pointer variable. The return value from the function is the number of bytes. size_t is a
data type defined in the string.h header file. The size of the data type depends on the particular
computer system.

The strcpy() Function


If you want to copy a string from one array to another, you can copy each item of the first array
to the corresponding element in the second array, or you can simply call the C function strcpy() to do
the job for you.
The syntax for the strcpy() function is
char *strcpy(char *dest, const char *src);
Here the content of the string src is copied to the array referenced by dest. The strcpy() function
returns the value of src if it is successful. The header file string.h must be included in your program
before the strcpy() function is called.

The strcat() Function


strcat appends a copy of src to the end of dest. The length of the resulting string is strlen(dest)
+ strlen(src).
The syntax for the strcat() function is
char *strcat(char *dest, const char *src);
strcat returns a pointer to the concatenated strings.

The strrev() Function


Reverses all characters in a string (except for the terminating null)
The syntax for the strrev() function is
char *strrev(char *s);
For example, it would change string\0 to gnirts\0
strrev returns a pointer to the reversed string.

The strcmp() Function

SE (IT) (SEMESTER I) 31 Programming Laboratory (2017-


2018)
Department of Information Technology

Compares two strings. The string comparison starts with the first character in each string and
continues with subsequent characters until the corresponding characters differ or until the end of the
strings is reached.
The syntax for the strcmp() function is
int strcmp(const char *s1, const char*s2);
This function returns an int value that is
< 0 if s1 < s2
== 0 if s1 == s2
> 0 if s1 > s2

The strlwr() Function


Converts uppercase letters (A to Z) in string s to lowercase (a to z).
The syntax for the strlwr() function is
char *strlwr(char *s);
No other characters are changed. Return Value is a pointer to the string s.

The strupr() Function


Converts lowercase letters (a to z) in string s to uppercase (A to Z).
The syntax for the strupr() function is
char *strupr(char *s);
No other characters are changed. Return Value is a pointer to the string s.

The Strstr() Function


Finds the first occurrence of a substring in another string
The syntax for the strupr() function is
char *strstr(const char *s1, const char *s2);
strstr scans s1 for the first occurrence of the substring s2.
Return Value:
On success, strstr returns a pointer to the element in s1 where s2 begins (points to s2 in s1).
On error (if s2 does not occur in s1), strstr returns null.

Algorithms :
1 Algorithm for finding the string length
Algorithm mystrlen (char str[] )
This algorithm reads a Source String character by character and counts characters till end of the string and
returns length of the String.
Pre-condition : String should be accepted
Post-condition :Length of the String should be calculated.
Return :Length of the String.
1 Initialize index = 0

SE (IT) (SEMESTER I) 32 Programming Laboratory (2017-


2018)
Department of Information Technology

2 while( src[index] != ‘\0’ ) repeat step 3 & 4


3 len = len +1
4 index = index + 1
5 end
6 return len

2. Algorithm for String Copy operation


Algorithm mystrcpy (char des[] , char src[] )

This algorithm reads a Source String character by character and copies it to the destination String.
Pre-condition : Source string should be accepted
Post-condition : copy of source should be present in destination String.
Return : reference to Copied String
1 index = 0

2 while (src[index] != ‘\0’ ) repeat step 3 & 4

3 dest[index] = src[index]

4 index = index + 1

5 end

6 dest[index] =‘\0’

7 return reference to the Copied String

3. Algorithm for Sting concatenation Operation


Algorithm mystrcat (char des[] , char src[] )

This algorithm reads the source string character by character and appends each character at the end of the
destination string and returns the reference to the destination String.
Pre-condition : Both the Strings should be accepted
Post-condition : Source String should be appended at the end of destination string
Return : reference to destination String
1 index1 = 0
2 while( not end of the des)
3 index1 = index1 + 1
4 end

SE (IT) (SEMESTER I) 33 Programming Laboratory (2017-


2018)
Department of Information Technology

5 index2 = 0
6 while ( not end of src )
7 des[index1] = src[index2]
8 index1 = index1 +1
9 index2 = index2 + 1
10 End
11 terminate destination string (des) by ‘\0’ character
12 return reference to destination string (des)

4. Algorithm for String Reverse Operation


Algorithm mystrrev (char src[] )

This algorithm reads the source string character by character and adds each character to the source string in
reverse order and returns the reference to the destination String.
Pre-condition : the source String should be accepted
Post-condition : Reverse of the Source String should be present in source String.
Return : reference to source String
1 start_index = 0

2 end_index = 0

3 while ( src [ end_index ] != ‘\0’ )

4 end_index = end_index + 1

5 End

6 end_index = end_index – 1

7 while ( start_index < end_index )

8 Swap src[start_index] & src[end_index]

9 start_index = start_index + 1

10 end_index = end_index – 1

11 End

SE (IT) (SEMESTER I) 34 Programming Laboratory (2017-


2018)
Department of Information Technology

10 return reference to source string

5. Algorithm for Palindrome check


Algorithm mypalindrome (char src[] )

This algorithm reads the String character by character and compares first character to last character, second
to second last and continues till middle character (checks if string is palindrome).
Pre-condition : Source String should be accepted
Post-condition : Result as palindrome or not a palindrome .
Return : Boolean value as a result (1/0)
1 start_index = 0
2 end_index = strlen(src)-1
3 while ( start_index < end_index)
4 if src[start_index] == src[end_index]
5 start_index = start_index + 1
6 end_index = end_index - 1
7 Else
8 goto step 10
9 end
10 if (start_index < end_index )
11 return 0
12 Else

13 return 1

6. Algorithm for String compare operations

Algorithm mystrcmp( char str1[],char str2[])


This algorithm reads both the Strings character by character and compares characters till end of the string
and returns length of the String.
Pre-condition : Both the Strings should be accepted
Post-condition :Equality of the Strings should be checked.
Return :Result of comparison (+ve if str1 > str2, -ve if str1 < str2 , Zero if equal)

SE (IT) (SEMESTER I) 35 Programming Laboratory (2017-


2018)
Department of Information Technology

(ascii difference)
1 index= 0;
2 while( str1[index] != ‘\0’ || str2[index ]!= ‘\0’)
3 if (str1[index] == str2[index])
4 index = index + 1
5 else
6 break;
7 End
8 End
9 diff = str1[index] - str2[index]

return diff
10

7. Algorithm for substring operations

Algorithm SubString (char str1[],char str2[])


This algorithm reads both the Strings character by character and compares characters to check occurrence of
str2 in str1 till end of the string and returns boolean result (true/false).
Pre-condition :- Both the Strings should be accepted
Post-condition :- Check for occurrence of string2 in string1.
Return :- No of occurrence of the substring in the main string
1 L1 = string length of str1
2 L2 = string length of str2
3 If L2 > L1
4 Return 0 // not a substring i.e 0 occurrences
5 End
6 Count = 0 // occurrence count
7 For i = 0 to L1 – L2
8 For j = 0 to L2-1
9 If str1[i+j] is not equal to str2[j]
10 break;

SE (IT) (SEMESTER I) 36 Programming Laboratory (2017-


2018)
Department of Information Technology

11 End if
12 End for
13 If j == L2
14 Increment count // Increment substring count
15 End if
16 End for
17 Return Count

SE (IT) (SEMESTER I) 37 Programming Laboratory (2017-


2018)
Department of Information Technology

Test Conditions:

1 Input two strings with same length.


2 Input two strings without same length.
3 Input such string whose reverse will be equal as original.
4 Input empty strings.

Sample Input Output

MENU FOR STRING OPERATIONS

1. String Length
2. String Copy
3. String Concatenation
4. String Reverse
5. String Palindrome
6. String Compare
7. Substring

Input :
Let String 1 = “ Fundamentals”
String 2 = “ment”
Choose one of the operations to be performed
Output :
1. StringLength (string1 )
Length of string1 i.e 12 will be returned
2. StringCopy (string1,string2)
String 2 will also consist “ Fundamentals”
3. StringConcat (string1,string2)
String2 will get appended to string1
String2 will have “ FundamentalsFundamentals”
4. StringReverse ( string1,string2)
String2 will consist reverse of string1 i.e. “slatnemadnuF”
5. palindrome(string1)
if string1 consists “ Fundamentals”
6. StringCompare ( string1,string2)
String 1 is greater than string 2
7. SubString (string1,string2)
If string1 = “ Fundamentals” and string2 =”ment”

SE (IT) (SEMESTER I) 38 Programming Laboratory (2017-


2018)
Department of Information Technology

String 2 is the substring of string1.

The string is not a pallindrome.

Oral Questions:

1. What is a string? How do you know its length?


2. What are the main differences between a string constant and a character constant?
3. Does the gets() function save the newline character from the standard input stream?
4. What types of data can the scanf() function read?
5. What are the left and right values (lvalue & rvalue)?
6. How can you obtain the address of a variable?
7. What is the concept of indirection in terms of using pointers?
8. Can a null pointer point to valid data?
9. What is the main difference between using scanf & gets for accepting strings ?
10. How do you reference an array by using a pointer?

Conclusion:

Thus the String Handling Functions like :

1. StringCopy ,
2. StringLength,
3. StringCompare ,
4. StringReverse,
5. StringConcat ,
6. SubString
7. Pallindrome

have been implemented (without using standard library routines).

Design Experiments:

a. Simulate the following string library functions with pointers to arrays.

char *strncpy(s,ct,n) Copies at most n characters of string ct


to s Returns s. Pads with '\0's if
t has fewer than n characters.
char *strncat(s,ct,n) Concatenates at most n characters of string
ct to end of string s; terminates s with
'\0'. Returns s.

SE (IT) (SEMESTER I) 39 Programming Laboratory (2017-


2018)
Department of Information Technology

int *strncmp(cs,ct,n) Compares at most n characters of string cs


to string ct.
Returns < 0 if cs < ct
0 if cs= =ct
or > 0 if cs > ct
char *strchr(cs,c) Returns a pointer to the first occurrence
of c in cs or NULL if not present.
char *strrchr(cs,c) Returns a pointer to the last occurrence
of c in cs or NULL if not present.

b. Simulate the following string library functions with pointers to arrays

size_t strspn(cs,ct) Returns length of prefix of cs consisting


of characters in ct.
size_t strcspn(cs,ct) Returns length of prefix of cs consisting
of characters not in ct.
char *strpbrk(cs,ct) Returns pointer to first occurrence in string
cs of any character of string ct, or NULL if
none present.
char *strstr(cs,ct) Returns pointer to first occurrence of string
ct in cs, or NULL if not present.
size_t strlen(cs) Returns the length of string cs.
char *strerror(n) Returns pointer to implementation-defined
string corresponding to error n.
char *strtok(s,ct) strtok searches s for tokens delimited by
characters from ct, NULL if none are found.

c. Implement above assignment by dynamically allocating memory for string and perform
the various operations on strings with pointers to arrays.

SE (IT) (SEMESTER I) 40 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 04

Title Structure manipulation

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 41 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 04

Title : Structure Manipulation

Problem Statement :
Create a Database using array of structures and perform following operations on it:
➢ Create Database
➢ Display Database
➢ Add record
➢ Search a record
➢ Modify a record
➢ Delete a record

Problem Definition :
Structure : Structures are collection of heterogeneous data types. i.e We can group variables of
different types with a data type called a structure. In C, a structure collects different data items in such
a way that they can be referenced as a single unit. Data items in a structure are called fields or
members of the structure.

Declaring Structures :
struct Bankcust
{
char name[15];
char address[20];
float balance;
int accno;
};
Here struct is used to start a structure declaration. Bankcust is the tag name of the structure. In this
example, there are three types of variables, char, int, and float. The variables have their own names,
such as name, address, balance & accno.
Note that a structure tag name, like Bankcust, is a label to a structure. The compiler uses the tag name
to identify the structure labeled by that tag name.

Defining Structure Variables :


After declaring a structure, you can define the structure variables. For instance, the following structure
variables are defined with the structure data type of automobile from the previous section:

struct Bankcust cust1,cust2,cust3;

Here three structure variables, cust1,cust2, cust3, are defined by the structure of Bankcust. All three
structure variables contain the four members of the structure data type of Bankcust.

SE (IT) (SEMESTER I) 42 Programming Laboratory (2017-


2018)
Department of Information Technology

Two ways of structure definition and variable declarations

Without using typedef Using typedef to have shorter name


while declaring variables:
struct Bankcust { typedef struct {
char name[15]; char name[15];
char address[20]; char address[20];
float balance; float balance;
int accno; int accno;
}; } Bankcust;
struct Bankcust cust; // Variable Bankcust cust; // Variable declaration
declaration

Referencing Structure Members with the Dot Operator :


Given the structure data type of Bankcust and the structure of cust, for instance, I can access the
fields in following way:

cust.name , cust.address , cust.balance , cust.accno

Here the structure name and its member's name are separated by the dot (.) operator.

Pointer to Structure:
We can declare a pointer variable which is capable of storing the address of a structure variable as
follows:
struct Bankcust *ptr; or Bankcust *ptr;// if declared using typedef

Suppose if we have structure variable declared as:


Struct Bankcust cust ; or Bankcust cust;// if declared using typedef

Then ptr can store the address of cust by:


ptr = &cust;

Referencing a Structure Member with ->(arrow operator)


Using ptr we can access the fields of cust as follows:
ptr->name or (*ptr).name
Because of its clearness, the -> operator is more frequently used in programs than the dot operator.

Array of Structures:

SE (IT) (SEMESTER I) 43 Programming Laboratory (2017-


2018)
Department of Information Technology

To declare an array of a structures, we first define a structure an then declare


an array variable of that type. To declare an 100 element array of structures of
type student define earlier,
We write,
struct Bankcust cust[100];
This creates 100 sets of variables that are organized as defined in the structure
Bankcust.
To access a specific structure, index the array name. For example, to print the
name of 4th customer, we write
printf( “%s”, cust[3].name);

Nested Structures
A member of a structure can be either a simple variable, such as an int or double, or an aggregate type.
In C, aggregate types are arrays and structures.
When a structure is a member of another structure, it is called a nested structure. For example fname
can be nested inside Student
struct fname
{
char first_name[15];
char mid_name[15];
char last_name[15];
}
struct employee {
struct fname name;
char dept[128];
int age;
int year;
};
struct employee emp_rec; /*Variable of type student */
To access the first name of the student we need to write
Emp_rec.fname.first_name

Passing Structures as Function Arguments to a function


Call by Value Call by reference
void display( struct Bankcust C ) void display( struct Bankcust *C)
{ {
printf(“%s”,C.name); printf(“%s”,C->name);
printf(“%s”,C.address); printf(“%s”,C->address);
printf(“%f”,C.balance); printf(“%f”,C->balance);
printf(“%d”, C.accno); printf(“%d”, C->accno);
}
}
Function call line will be as: Function call line will be as:
display(cust); display(&cust);

SE (IT) (SEMESTER I) 44 Programming Laboratory (2017-


2018)
Department of Information Technology

Algorithms :
1. Algorithm for Creating the database
Algorithm Create_database(struct employee E[] )
1 Start

2 Accept how many records user need to add, say, no of records as n

3 For i = 0 to n – 1
4 Accept the record and store it in E[i]
5 End For
6 Return n

2. Algorithm for Displaying records using pointers to structures

Algorithm Display_database(struct employee *E,int n)


1 Start

2 For i = 0 to n – 1
3 Display the fields E->name, E->empid, E->salary

E = E + 1 // E will point to the next record


4 End For
5 Stop

3. Algorithm for Inserting a record in the data base

Algorithm Insert_database (struct employee E[] ,int n)

1 Start
2 If n < MAX // MAX is the size of array declared
3 Accept the record to be added as X
4 E[n] = X
5 n = n + 1 // no of records will be incremented by 1

SE (IT) (SEMESTER I) 45 Programming Laboratory (2017-


2018)
Department of Information Technology

6 Display Record inserted successfully.


7 Else
8 Display you cannot insert the record !!! Database FULL
9 End if
10 Return n
4 . Algorithm for Searching a particular record

Algorithm Search_database(struct employee E[], int n )

1 Start

2 Accept the emp_id whose record to be searched , say Key

3 For i = 0 to n-1

4 If E[i].empid == Key

5 Display record found and display the information

6 Jump to step 9

7 End if

8 End For

9 If i == n

10 Display Record not present

11 End if

10 Stop

5. Algorithm for Modifying a record

Algorithm Modify_database(struct employee E[], int n )

1 Start

2 Accept the emp_id whose record to be modified , say Key

3 For i = 0 to n-1

SE (IT) (SEMESTER I) 46 Programming Laboratory (2017-


2018)
Department of Information Technology

4 If E[i].empid == Key

5 Accept the modified information and overwrite it on E[i] and display modified successfully

6 Jump to step 9

7 End if

8 End For

9 If i == n

10 Display Record to be modified not present

11 End if

12 Stop

6. Algorithm for Deleting a record

Algorithm Delete_from_database(struct employee E[], int n)


1 Start

2 Accept the emp_id whose record to be modified , say Key

3 For i = 0 to n-1

4 If E[i].empid == Key

5 Display Record found and deleted successfully

6 Shift all records from i+1 to n-1 , one position back i.e E[j] = E[j+1] where j varies from i to n-2

7 Decrement n by 1 // No of records will be reduced by one

8 Jump to step 11

9 End if

10 End For

11 If i == n

12 Display Record to be deleted not present

13 End if

14 Return n

SE (IT) (SEMESTER I) 47 Programming Laboratory (2017-


2018)
Department of Information Technology

Testing
Input :
Add records to the Employee database
Select Operation to be performed.
Output :
Perform operations like Insert, search, modify, delete, display list, display
record depending on the operation selected and manipulate the
database when required.

Sample Input Output

MENU
CHOICE NO 1 : CREATE DATABASE
CHOICE NO 2 : DISPLAY
CHOICE NO 3 : INSERT
CHOICE NO 4 : SEARCH
CHOICE NO 5 : MODIFY
CHOICE NO 6 : DELETE
CHOICE NO 7 : EXIT

Enter the choice : 1


Enter the no of records to be added : 3
Enter the Employee_id Name & Salary : 11 sachin 10000
Enter the Employee_id Name & Salary : 22 mukesh 20000
Enter the Employee_id Name & Salary : 33 suresh 30000

Enter your choice : 2


Record No EMP_ID NAME SALARY
1 11 sachin 10000
2 15 yogesh 15000
3 22 mukesh 20000

Enter your choice : 3


Enter the Employee_id Name & Salary to be inserted : 33 suresh 30000
Record inserted successfully at the end.

Enter the your choice : 2


Record No EMP_ID NAME SALARY

SE (IT) (SEMESTER I) 48 Programming Laboratory (2017-


2018)
Department of Information Technology

1 11 sachin 10000
2 15 yogesh 15000
3 22 mukesh 20000
4 33 suresh 30000
Enter your choice : 4
Enter the emp_id to be searched : 15
Record found at position 2
EMP_ID : 15
NAME : yogesh
SALARY : 15000

Enter your choice : 4


Enter the emp_id to be searched : 35
Record not found

Enter your choice : 4


Enter the emp_id whose record to be modified : 15
Enter the modified Employee_id Name & Salary : 15 Jeetu 25000
Record modified successfully

Enter the your choice : 2


Record No EMP_ID NAME SALARY
1 11 sachin 10000
2 15 Jeetu 25000
3 22 mukesh 20000
4 33 suresh 30000

Enter your choice : 6


Enter the emp_id whose record to be deleted : 22
Record found and deleted successfully

Enter the your choice : 2


Record No EMP_ID NAME SALARY
1 11 sachin 10000
2 15 Jeetu 25000
3 33 suresh 30000

Enter your choice : 6


Enter the emp_id whose record to be deleted : 72
Record to be deleted not present

Enter your choice : 7


Thank you for using the program !! Have a good day

SE (IT) (SEMESTER I) 49 Programming Laboratory (2017-


2018)
Department of Information Technology

Oral Questions:
1. 1 Why do you need structures?
2. Can you declare a structure and define a structure variable in a single statement?
3. How do you reference a structure member?
4. Why is it more efficient to pass a pointer that refers to a structure to a function?
5. What are the differences between a union and a structure?
6. What will happen if you initialize all members of a union together?
7. How do you reference a union member?
8. Can you access the same memory location with different union members?
9. Is there a way to compare structures automatically?
10. How are structure passing and returning implemented?

Conclusion:
Thus we have implemented structure with and without pointers and performed Structure
manipulation for employee database with operations like add, search, modify, delete, display list,
display record
For large database implementation using pointer is more efficient than without pointer.

Design Experiments:
a. Create a Bank database with fields as name, address, account no, balance using array of
structures and perform operations like add, search, display , delete, modify with pointer to
structure.
b. Create a student database which will be useful for admission procedure for First year
Engineering. The data base should have minimum following fields :
CET No,
Name with three fields
Date of birth
Marks scored in PCM (Out of 100)
CET Score
Display the students in descending order of marks of PCM and CET.
c. Accept student databases using array of pointers to structures and display them. Allocate
memory dynamically for storing each record. The data base should have fields like name,
rollno, marks, fees paid( y / n).
Sort the database on alphabetical ordering of name. and display the list of students who have
not yet paid the fees.

SE (IT) (SEMESTER I) 50 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 05

Title Searching & Sorting

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 51 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 05

Title : Bubble sort, Selection Sort, & Binary Search

Problem Statement :
➢ Sort the set of strings in ascending order using bubble sort and descending order by using
selection sort or Insertion sort(Display pass by pass output).
➢ Search for a particular string Using Binary search(With and without recursion).

Problem Definition :

Searching : It is a process of retrieving or locating a record with a particular key value.

Binary Search :
This is a very efficient searching method used for linear / sequential data. In this search, Data has to
be in the sorted order either ascending or descending. Sorting has to be done based on the key
values.
In this method, the required key is compared with the key of the middle record. If a match is found,
the search terminates. If the key is less than the record key, the search proceeds in the left half of the
table. If the key is greater than record key, search proceeds in the same way in the right half of the
table. The process continues till no more partitions are possible. Thus every time a match is not
found, the remaining table size to be searched reduces to half.
If we compare the target with the element that is in the middle of a sorted list, we have three
possible results: the target matches, the target is less than the element, or the target is greater than
the element. In the first and best case, we are done. In the other two cases, we learn that half of the
list can be eliminated from consideration.
When the target is less than the middle element, we know that if the target is in this ordered list, it
must be in the list before the middle element. When the target is greater than the middle element,
we know that if the target is in this ordered list, it must be in the list after the middle element. These
facts allow this one comparison to eliminate one-half of the list from consideration. As the process
continues, we will eliminate from consideration, one-half of what is left of the list with each
comparison. This technique is called as binary search.

SE (IT) (SEMESTER I) 52 Programming Laboratory (2017-


2018)
Department of Information Technology

Advantage : Time complexity is O(logn) which is very efficient.


Disadvantage : Data has to be in sorted manner.

Analysis:
After 0 comaparisons  Remaining file size = n
After 1 comaparisons  Remaining file size = n / 2 = n / 21
After 2 comaparisons  Remaining file size = n / 4 = n / 22
After 3 comaparisons  Remaining file size = n / 8 = n / 23
……
After k comaparisons  Remaining file size = n / 2k

The process terminates when no more partitions are possible i.e. remaining file size = 1
n / 2k = 1
k = log2n
Thus, the time complexity is O(log2n). which is very efficient.
Sorting : It is the process of arranging or ordering information in the ascending or descending order
of the key values.

Bubble Sort :
This is one of the simplest and most popular sorting methods. The basic idea is to pass
through the array sequentially several times. In each pass we compare successive pairs of elements (
A[i] with A[i+1] ) and interchange the two if they are not in the required order. One element is placed
in its correct position in each pass. In the first pass, the largest element will sink to the bottom,
second largest in the second pass and so on. Thus, a total of n-1 passes are required to sort ‘n’ keys.

Advantages:
It is a simple sorting method.
No additional data structure is required.

SE (IT) (SEMESTER I) 53 Programming Laboratory (2017-


2018)
Department of Information Technology

Disadvantage:
It is very inefficient method – O(n2)
Even if the elements are in the sorted order, all n-1 passes will be done.

Analysis :
In this sort, n-1 comparisons takes place in 1st pass , n-2 in 2nd pass , n-3 in 3rd pass , and so on.
Therefore total number of comparisons will be
(n-1) + (n-2) + (n-3) + ……. + 3 + 2 + 1
This is an Arithmetic series in decreasing order
Sum = n/2 [2a + (n-1)d]
Where, n = no. of elements in series , a = first element in the series
d = difference between second element and first element.
Sum = (n-1) / 2 [ 2 * 1 + ((n-1) - 1) * 1 ]
= n(n-1) / 2
which is of order n2 i.e O(n2)

The main advantage is simplicity of algorithm and it behaves as O(n) for sorted array of element.
Additional space requirement is only one temporary variable.

Example : (Bubble sort)


0 1 2 3 4 5

25 37 12 48 57 33

Pass 1: Compare two consecutive elements, if first element is greater than second then interchange
the elements else no change

SE (IT) (SEMESTER I) 54 Programming Laboratory (2017-


2018)
Department of Information Technology

0 1 2 3 4 5

25 37 12 48 57 33

No Change

0 1 2 3 4 5

25 37 12 48 57 33

Interchange

0 1 2 3 4 5

25 12 37 48 57 33

No change
0 1 2 3 4 5

25 12 37 48 57 33

No change

0 1 2 3 4 5

25 12 37 48 57 33

SE (IT) (SEMESTER I) 55 Programming Laboratory (2017-


2018)
Department of Information Technology

Interchange
Array after Pass 1 :
0 1 2 3 4 5

25 12 37 48 33 57

Pass 2 : Now we will show all the comparisons with the final array

0 1 2 3 4 5

25 12 37 48 33 57

Array After Pass 2


0 1 2 3 4 5

12 25 37 33 48 57

Pass 3 :

0 1 2 3 4 5

12 25 37 33 48 57

SE (IT) (SEMESTER I) 56 Programming Laboratory (2017-


2018)
Department of Information Technology

Array After Pass 3


0 1 2 3 4 5

12 25 33 37 48 57

Pass 4 :

0 1 2 3 4 5

12 25 33 37 48 57

Array After Pass 4


0 1 2 3 4 5

12 25 33 37 48 57

Pass 5 :

0 1 2 3 4 5

12 25 33 37 48 57

Array After Pass 5


0 1 2 3 4 5

SE (IT) (SEMESTER I) 57 Programming Laboratory (2017-


2018)
Department of Information Technology

12 25 33 37 48 57

Final Sorted Array using Bubble sort


0 1 2 3 4 5

12 25 33 37 48 57

Selection Sort: In this sorting technique, we will select the position and find the value at that
position. In case of ascending order, position 0 should contain smallest number, hence the smallest
number from 0 to (n-1) positions, which is at say position j and swap value at position 0 with value at
position j. The next position selected is position 1 and we find smallest from 1 to (n-1) positions and
swap it with position 1. In general, to find number at position i (the numbers at position 0 to i-1 are
already placed, i.e. in ascending order) find the smallest from i to n-1, say position j and swap it with
position i.
Example :
0 1 2 3 4 5 6 7 8 9

12 30 10 8 15 100 2 33 67 5

1. Position under consideration is 0


Smallest from position 0 to 9 is at position 6, hence swap the numbers at position
0 & 6.
0 1 2 3 4 5 6 7 8 9

2 30 10 8 15 100 12 33 67 5

2. Position under consideration is 1


Smallest from position 1 to 9 is at position 9, hence swap the numbers at position
1 & 9.
0 1 2 3 4 5 6 7 8 9

2 5 10 8 15 100 12 33 67 30

3. Position under consideration is 2

SE (IT) (SEMESTER I) 58 Programming Laboratory (2017-


2018)
Department of Information Technology

Smallest from position 2 to 9 is at position 3, hence swap the numbers at position


2 & 3.
0 1 2 3 4 5 6 7 8 9

2 5 8 10 15 100 12 33 67 30

4. Position under consideration is 3


Smallest from position 3 to 9 is at position 3, hence swap the numbers at position
3 & 3.
0 1 2 3 4 5 6 7 8 9

2 5 8 10 15 100 12 33 67 30

5. Position under consideration is 4


Smallest from position 4 to 9 is at position 6, hence swap the numbers at position
4 & 6.
0 1 2 3 4 5 6 7 8 9

2 5 8 10 12 100 15 33 67 30

6. Position under consideration is 5


Smallest from position 5 to 9 is at position 6, hence swap the numbers at position
5 & 6.
0 1 2 3 4 5 6 7 8 9

2 5 8 10 12 15 100 33 67 30

7. Position under consideration is 6


Smallest from position 6 to 9 is at position 9, hence swap the numbers at position
6 & 9.

SE (IT) (SEMESTER I) 59 Programming Laboratory (2017-


2018)
Department of Information Technology

0 1 2 3 4 5 6 7 8 9

2 5 8 10 12 15 30 33 67 100

8. Position under consideration is 7


Smallest from position 7 to 9 is at position 7, hence swap the numbers at position
7 & 7.
0 1 2 3 4 5 6 7 8 9

2 5 8 10 12 15 30 33 67 100

9. Position under consideration is 8


Smallest from position 8 to 9 is at position 8, hence swap the numbers at position
8 & 8.
0 1 2 3 4 5 6 7 8 9

2 5 8 10 12 15 30 33 67 100

Hence the sorted Array is :


0 1 2 3 4 5 6 7 8 9

2 5 8 10 12 15 30 33 67 100

Analysis
In Selection sort, we search the smallest element in the array and then that element will be at proper
position. So, in first round, we will require n-1 comparisons, in second round, n-2 comparisons
because first element is already at proper position.
Therefore total number of comparisons will be
(n-1) + (n-2) + (n-3) + ……. + 3 + 2 + 1
= (n-1) / 2 [ 2 * 1 + ((n-1) - 1) * 1 ]
= n(n-1) / 2

SE (IT) (SEMESTER I) 60 Programming Laboratory (2017-


2018)
Department of Information Technology

which is of order n2 i.e O(n2)

It is little more efficient than bubble sort, because we do very less swapping process as compared to bubble
sort

Algorithm for Binary search (Iterative)


Algorithm Binary_Search (A, n , Key ) Where A is an 2D character array , n is the no of records,
and key is element to be searched

1 Start
2 Set b = 0 & e = n-1

3 While b ≤ e

4 mid = (b + e ) / 2

5 If A[mid] == key (compare two strings for equality)

6 Return 1 // Found
7 Else

8 If key < A[mid]

9 e = mid – 1

10 Else

11 b = mid + 1

12 End if

13 End if

14 End while

15 Return 0 // Not found

Algorithm for Binary search (Recursive)


Algorithm Binary_Search (A, b , e, Key ) Where A is an 2D character array , b is the index of
starting element and e is the index of last element in the array and key is element to be searched
1 If b > e

2 Return 0 // Not Found

3 Else
4 mid = (b + e ) / 2

SE (IT) (SEMESTER I) 61 Programming Laboratory (2017-


2018)
Department of Information Technology

5 If A[mid] == key (Compare two strings for equality)

6 Return 1 // Found

7 Else

8 If key < A[mid]

9 Recursively call Binary_search(A, b,mid – 1, key) and return the returned value

10 Else

11 Recursively call Binary_search(A, mid + 1, e,key) and return the returned value

12 End if

13 End if
14 End if

Algorithm for Bubble Sort


Algorithm Bubble_Sort (A,n) Where A is an 2D character array , n is the total number of strings to
sort

1 Start

2 For Pass = 1 to n-1

3 For i = 0 to (n – pass – 1)

4 If A[i] < A[i+1] (Check is A[i] string is less than A[i+1] string)

5 Swap (A[i], A[i+1])


6 End if

7 End for
8 End For

9 Stop

Algorithm for Selection Sort (Descending order)


Algorithm Selection_Sort (A,n) // Where A is an 2D character array , n is the total number of strings
to sort

1 Start

SE (IT) (SEMESTER I) 62 Programming Laboratory (2017-


2018)
Department of Information Technology

2 For pos = 0 to n – 2

3 max_index = pos

4 For i = pos + 1 to n – 1
5 If A[i] > A [max_index] (check is A[i] string is greater than A[max_index] string)

6 max_index = i

7 End if

8 End for

9 Swap(A[pos] , A[min_index])

10 End for

11 Stop

Testing

Input :Enter the group of strings


Select Searching and sorting options to be performed.
Output : Display Result of search
Display the sorted strings

Sample Input Output

MENU

1. Accept
2. Display
3. Bubble Sort
4. Selection Sort
5. Search

Choice 1 :
Accept the total no. of strings : 7
Enter the strings : SANGEETA PRASHANT YOGESH SANDEEP POOJA ASHISH MANGESH

Choice 2 :
Array entered is : SANGEETA PRASHANT YOGESH SANDEEP POOJA ASHISH MANGESH

SE (IT) (SEMESTER I) 63 Programming Laboratory (2017-


2018)
Department of Information Technology

Choice 3 :
Array before sorting using Bubble sort
SANGEETA PRASHANT YOGESH SANDEEP POOJA ASHISH MANGESH

Array after sorting using Bubble sort


ASHISH MANGESH POOJA PRASHANT SANDEEP SANGEETA YOGESH

Choice 4 :
Array before sorting using Selection sort
SANGEETA PRASHANT YOGESH SANDEEP POOJA ASHISH MANGESH

Array after sorting using Selection sort


YOGESH SANGEETA SANDEEP PRASHANT POOJA MANGESH ASHISH

Choice 5 :
Input Array
ASHISH MANGESH POOJA PRASHANT SANDEEP SANGEETA YOGESH

Enter the string to be searched : MANGESH


Found at 2 Position

Enter the string to be searched : MUKESH


Not Found

Oral Questions:
1. List the advantages and disadvantages of Binary Search?
2. Explain the analysis of Binary Search with respect to best case, worst case & Average case?
3. 3.What is In-place & Stable Features of Sorting Algorithms?
4. Explain what you mean by Internal & External Sorting.
5. Explain the advantages and disadvantages of bubble sort
6. Analyze Bubble sort with respect to Time complexity?
7. How to improve the efficiency of Bubble sort if the array gets sorted before the n-1 passes?
8. What is sorting stability?
9. Explain the analysis of Selection Sort?
10. Give applications of Binary Search?

Conclusion:

Thus we have implemented bubble sort, selection sort and binary search technique and analyzed the
results for best, worst and average cases.

Design Experiments:

SE (IT) (SEMESTER I) 64 Programming Laboratory (2017-


2018)
Department of Information Technology

1. Implement the above assignment using Fibonacci Search and Bucket sort Technique.
2. Create bank database and perform searching and sorting process on it.

Display the database on sorted basis of account no.

Display the database on sorted basis of balance.

Display the list of account holders whose balance is less than minimum balance.

3. Implement the above assignment using external searching and sorting technique.

Records will be stored on a secondary storage device.

SE (IT) (SEMESTER I) 65 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 07

Title Quick sort

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 66 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 07

Title : Quick sort/ Merge Sort

Problem Statement :
Implement Quick Sort to sort the given list of numbers/records. Display corresponding list in
each pass(with and without recursion).

Problem Definition :

Quick Sort also known as partition exchange sort. Original algorithm was developed by C.A.R. Hoare
in 1962.Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.It
is one of the fastest sorting algorithms available. QuickSort is especially convenient with large arrays
that contain elements in random order.

The steps are:

1. Pick an element, called a pivot, from the list.


2. Reorder the list so that all elements which are less than the pivot, come before the pivot and
all elements greater than the pivot come, after it (equal values can go either way). After this
partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively sort the sub-list of smaller elements and the sub-list of greater elements.

numbers less p numbers greater than or


thanp equal top

Thus quicksort is an recursive sorting algorithm which chooses an element of the list, called the pivot
element, and then rearranges the list so that all of the elements smaller than the pivot are moved
before it and all of the elements larger than the pivot are moved after it.

SE (IT) (SEMESTER I) 67 Programming Laboratory (2017-


2018)
Department of Information Technology

Advantage:
➢ Efficient sorting technique
➢ Time complexity is O(nlogn)

Disadvantage:
➢ Worst case time complexity is O(n2)
➢ Time requirement depends on the position of the pivot in the list.

Analysis of Quicksort:
Time requirement of Quicksort depends on the position of pivot in the list, how pivot is dividing list
into sublists. It may be equal division of list or maybe it will not divide also.

Best case:
In Best case, we assume that list is equally divided means, list1 is equally divided in two sublists,
these two sublists in four sublists, and so on. So the total no. of elements at particular level (l) will be 2l-1 so
total number of steps will be log2n. The no. of comparison at any level will be maximum n. so we say run
time of Quicksort will be Ω(nlog2n).

Worst Case:
Suppose list of elements are already in sorted order. When we find the pivot then it will be first element. So
here it produces only 1 sublist which is on right side of first element and starts from second element.
Similarly other sublists will be created only at right side. The no. of comparisons for first element is n, second
element requires n-1 comparisons and so on.. So the total no. of comparisons will be n + n-1 + …. 2 + 1
= n (n-1) / 2 = O(n2).

Average Case :

The average case performance of QuickSort is Θ(nlogn)

Example:

SE (IT) (SEMESTER I) 68 Programming Laboratory (2017-


2018)
Department of Information Technology

Step by Step Process for QS (A, 0, 6)

SE (IT) (SEMESTER I) 69 Programming Laboratory (2017-


2018)
Department of Information Technology

SE (IT) (SEMESTER I) 70 Programming Laboratory (2017-


2018)
Department of Information Technology

Algorithms :
Algorithm for Quicksort
Algorithm Quicksort ( int A[], int s, int l ) where A is the array , s is the index of starting element
and l is the index of last element.

1 Start

2 Select A[s] as the pivot element

3 Set b = s + 1

4 Set e = l

5 While b ≤ e

6 Increment b till A[b] ≤ pivot element

7 Decrement e till A[e] > pivot element


8 If b < e

9 Swap(A[b], A[e])
10 End if

11 End while

12 Swap( A[s] , A[e]) // Place the pivot element at index e

13 If s < e-1

14 Recursively call Quicksort(A,s,e-1)

15 End if

16 If e+1 < l

17 Recursively call Quicksort(A,e+1,l)

18 End if

19 Stop

SE (IT) (SEMESTER I) 71 Programming Laboratory (2017-


2018)
Department of Information Technology

Testing
Input :
ENTER THE NO. OF ELEMENTS : 10
ENTER ARRAY ELEMENTS : 56-90126324571000-18340

ENTERED ARRAY IS
56 -90 12 632 457 1000 -1 8 340

QuickSort Pivot and PASSes :


PASS 1 PIVOT 56
-1 -90 12 0 34 8 56 1000 457632

PASS 2 PIVOT -1
-90 -1 12 0 34 8 56 1000 457632

PASS 3 PIVOT 12
-90 -1 8 0 12 34 56 1000 457632

PASS 4 PIVOT 8
-90 -1 0 8 12 34 56 1000 457632

PASS 5 PIVOT 1000


-90 -1 0 8 12 34 56 632 4571000

PASS 6 PIVOT 632


-90 -1 0 8 12 34 56 457 632 1000

SE (IT) (SEMESTER I) 72 Programming Laboratory (2017-


2018)
Department of Information Technology

SORTED ARRAY IS :
-90 -1 0 8 12 34 56 457 632 1000

Output :
SORTED ARRAY IS :
-90 -1 0 8 12 34 56 457 6321000
Oral Questions:

1. Explain the importance of sorting and searching in computer applications?


2. What is pivot element?
3. What are the ways for choosing the pivot element.?
4. In its worst case QuickSort behaves like:
1. Bubble sort b) Selection sort c) Insertion sort d) Bin sort?
5. Determine the running time of QuickSort for Sorted input, reverse ordered input, random input, When
all the elements are equal.?
6. Suppose we always choose the middle element as the pivot .Does this make it unlikely that QuickSort
will require quadratic time?
7. What is the worst-case behavior (number of comparisons) for quick sort?
8. In selecting the pivot for QuickSort, which is the best choice for optimal partitioning:
1. The first element of the array
2. The last element of the array
3. The middle element of the array
4. The largest element of the array
5. The median of the array
6. Any of the above?
9. Who is the founder of Quicksort technique?
10. Comment on stability of Quicksort?
Conclusion:

Thus we have implemented QuickSort recursively on a list (array) containing random elements.

Design Experiments:

a. Using Quicksort technique sorts the Bank database in descending order of Account
balance.
b. Using Quicksort technique sort the mobile database in ascending order of Mobile
number.
c. Using Quicksort non-recursive technique sorts the student database on the basis of
date of birth.

SE (IT) (SEMESTER I) 73 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 08

Title Sparse Matrix

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 74 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 08

Title : Sparse Matrix

Problem Statement :
Accept conventional matrix and convert it into sparse matrix using structure and perform addition
simple and fast transpose.

Problem Definition :
Definition of Sparse Matrix : A Sparse matrix is a matrix having very few non-zero elements and a
large number of elements are Zero.
Example

10 0 0 0 -5 0 0 0
0 0 1 0 0 0 0 0
M= 0 0 0 0 -4 0 0 0
7 0 0 0 0 0 0 0
0 9 0 0 0 0 0 0

In this example 6 of the 40 elements are non-zero. Hence it can be called a sparse matrix. Such a
matrix does not utilize memory efficiently. Hence, a different representation and handling is
developed for sparse matrix.

A Sparse matrix can be stored as a list of tuples storing only the non-zero elements and their row and
column number. Thus the above matrix will be stored as:

SE (IT) (SEMESTER I) 75 Programming Laboratory (2017-


2018)
Department of Information Technology

Row Column
Value
No No

5 8 6

0 0 10

0 4 -5

1 2 1
2 4 -4

3 0 7
4 1 9

The first tuple gives the information about the matrix namely number of rows, number of columns
and the number of non-zero elements. The remaining give information about each non-zero value.
Matrices play a very important role for solving many problems in scientific applications. Therefore,
they have to be efficiently represented such that the operations on matrices like addition,
multiplication, inverse, transpose etc. can be carried out with minimum time and space
requirements.

Addition of Sparse Matrix


Two sparse matrices can be added only if their orders are same.
Elements in the same position (having same row and column number) are to be added and stored in
the resultant matrix. Otherwise both elements have to be separately copied in the resultant matrix.
Row Column Row Column
No No Value No No Value

5 8 6 5 8 5

0 0 10 0 1 2

0 4 -5 0 4 7

2
2

4
1

-4
+ 1

1
1

2
3

SE (IT) (SEMESTER I) 76 Programming Laboratory (2017-


2018)
Department of Information Technology

3 0 7 3 0 4

4 1 9

Addition Result
Row Column
Value
No No

5 8 8

0 0 10

0 1 2

0 4 2
1 1 3

1 2 3
2 4 -4

3 0 11

4 1 9

Simple Transpose of a Sparse Matrix


A transpose of a matrix is a matrix which contains the i, jth element of the original matrix in the j, ith
position of the transpose i.e T[i][j] = A[j][i] .
Sparse Matrix A
Row Column
Value
No No

5 8 6

0 0 10

0 4 -5

1 2 1

2 4 -4

3 0 7

SE (IT) (SEMESTER I) 77 Programming Laboratory (2017-


2018)
Department of Information Technology

4 1 9

For the above sparse matrix, its transpose will be

Transpose Matrix
Row Column
Value
No No

5 8 6

0 0 10
0 3 7

1 4 9

2 1 1

4 0 -5

4 2 -4

If we simply interchange the row and column numbers, the elements will not be in the proper order
i.e. the element A (row,col,value) will be at T(col, row,value) but we do not know where to put the
element.
If we store them consecutively, we will have to move tuples every time a new tuple has to be
inserted to maintain the sequence.
This can be avoided by finding all elements in column i of A and put them in row i of T for all 0 ≤ i <
num – cols.
i.e. for all columns j in matrix A do
for all elements in matrix A do
place A(i , j, value) in T(j,i, value)

Analysis:

SE (IT) (SEMESTER I) 78 Programming Laboratory (2017-


2018)
Department of Information Technology

If there are n columns in matrix A of order m x n and the number of non-zero terms is t, the
computing time is O(nt).
If t is the order of nm, the time for this algorithm becomes O(n2m) which is far worse than O(nm)
time for transpose of normal matrices.

Fast Transpose
This method achieves the transpose of a sparse matrix in O(n+t) time and hence is much faster than
the simple transpose method. This method is as follows
▪ Find the number of elements in each column of A
▪ This gives the number of elements in each row of T
▪ Using this, calculate the starting point of each row of T.
▪ Move each element of A one by one to its correct position in T.
Example :
Sparse Matrix A
Row Column
Value
No No

5 8 6

0 0 10

0 4 -5

1 2 1
2 4 -4

3 0 7

4 1 9

Number of elements in each column of A


0 1 2 3 4 5 6 7
Count 2 1 1 0 2 0 0 0

The starting positions of each row in T.


0 1 2 3 4 5 6 7

SE (IT) (SEMESTER I) 79 Programming Laboratory (2017-


2018)
Department of Information Technology

Position 0 2 3 4 4 6 6 6

Sparse Matrix A Transpose


Row Column Row Column
No No Value No No Value

5 8 6 5 8 6

0 0 10 0 0 10

0 4 -5 0 3 7

1 2 1 1 4 9

2 4 -4 2 1 1

3 0 7 4 0 -5

4 1 9 4 2 -4

Analysis of Fast Transpose :


▪ The steps taken to find number of elements in each column of A=n [Assuming a m x n matrix]
▪ The steps taken to compute the starting positions of each row in T = n -1
▪ The elements of A are copied to T in t steps
Therefore, Total no. of steps = n + n – 1 + t
Which is of the order O(n+t).
If t is of the order nm, this method becomes O(nm) which is same for two dimensional arrays.
Algorithms :
1. Algorithm for Sparse Matrix addition
Algorithm Addition_Sparse_Matrix ( A , B ) where A & B are sparse matrix to be added and stored
in C Matrix

1 Start

2 If orders of A and B are not the same , display addition not possible and go to step 8

3 Let t1 & t2 be the no. of non-zero terms in Matrix A & B

4 Store the number of rows and columns in 0th row of resultant matrix C

SE (IT) (SEMESTER I) 80 Programming Laboratory (2017-


2018)
Department of Information Technology

5 Initialize i = j = k = 1 // where i,j,k are row index for Matrix A, B, C

6 While i ≤ t1 AND j ≤ t2

7 if ith row number of A == jth row number of B

8 if ith column number of A == jth column number of B

9 add the elements of the matrices A and B and store in C

10 increment i, j and k
11 Else

12 if ith column number of A < jth column number of B

13 copy element from matrices A to C

14 increment i and k
15 Else

16 copy element from matrices B to C

17 increment j and k
18 End if

19 Endif

20 Else

21 if ith row number of A < jth row number of B

22 copy element from matrices A to C

23 increment i and k
24 Else

25 copy element from matrices B to C

26 increment j and k
27 End if

28 Endif

29 End While

30 While i ≤ t1

SE (IT) (SEMESTER I) 81 Programming Laboratory (2017-


2018)
Department of Information Technology

31 copy element from matrices A to C

32 increment i and k
33 End while

34 While j ≤ t2

35 copy element from matrices B to C

36 increment j and k
37 End while

38 Display Matrix C having k non zero terms

39 Stop

2. Algorithm for Simple Transpose

Algorithm Simple_Transpose ( A ) where A is the sparse matrix whose transpose to be found

1 Start
2 Let ‘n’ be the no. of cols in Matrix A and ‘t’ be the no. of non zero terms i.e n = A[0].col & t = A[0].val

3 Intialize k to 1

4 For c = 0 to n -1
5 For i = 1 to t

6 If A[i].col == c
7 T[k].row = A[i].col

8 T[k].col = A[i].row

9 T[k].val = A[i].val

10 Increment k

11 End if

12 End for

13 End for

14 T[0].row = A[0].col
15 T[0].col = A[0].row

SE (IT) (SEMESTER I) 82 Programming Laboratory (2017-


2018)
Department of Information Technology

16 T[0].val = A[0].val

17 Display Matrix T

18 Stop

SE (IT) (SEMESTER I) 83 Programming Laboratory (2017-


2018)
Department of Information Technology

3. Algorithm for Fast Transpose

Algorithm Fast_transpose(A) where A is the sparse matrix whose transpose to be found

1 Start
2 Let ‘n’ be the no. of cols in Matrix A and ‘t’ be the no. of non zero terms i.e n = A[0].col & t = A[0].val

3 T[0].row = A[0].col
4 T[0].col = A[0].row

5 T[0].val = A[0].val

6 For i = 1 to t

7 Increment ( Count [ A[i].col ] ) by 1

8 End for
9 Pos[0] = 1

10 For i = 1 to n – 1
11 Pos[i] = Pos[i-1] + Count[i-1]

12 End if

13 For i = 1 to t

14 T[Pos[A[i].col]].row = A[i].col

15 T[Pos[A[i].col]].col = A[i].row

16 T[Pos[A[i].col]].val = A[i].val

17 Pos[s[i].col]++
18 End For

19 Display Matrix T

20 Stop

SE (IT) (SEMESTER I) 84 Programming Laboratory (2017-


2018)
Department of Information Technology

Testing
Sample Input Output:
MENU
1. Accept the matrix and convert it into sparse Matrix Representation
2. Simple Transpose
3. Fast Transpose
4. Addition of two Sparse matrix

Input :Enter the order of Matrix : 5 8


Enter the Matrix

10 0 0 0 -5 0 0 0
0 0 1 0 0 0 0 0
M= 0 0 0 0 -4 0 0 0
7 0 0 0 0 0 0 0
0 9 0 0 0 0 0 0

Output :
Sparse Matrix Representation :
Row Column
Value
No No

5 8 6

0 0 10

0 4 -5

1 2 1

2 4 -4

3 0 7

4 1 9

SE (IT) (SEMESTER I) 85 Programming Laboratory (2017-


2018)
Department of Information Technology

Simple Transpose:
Sparse Matrix A Transpose
Row Column Row Column
No No Value No No Value

5 8 6 5 8 6

0 0 10 0 0 10

0 4 -5 0 3 7

1 2 1 1 4 9

2 4 -4 2 1 1

3 0 7 4 0 -5

4 1 9 4 2 -4

SE (IT) (SEMESTER I) 86 Programming Laboratory (2017-


2018)
Department of Information Technology

Fast Transpose :

Sparse Matrix A Transpose


Row Column Row Column
No No Value No No Value

5 8 6 5 8 6

0 0 10 0 0 10

0 4 -5 0 3 7

1 2 1 1 4 9

2 4 -4 2 1 1

3 0 7 4 0 -5

4 1 9 4 2 -4

Addition:
Sparse Matrix A Sparse Matrix B
Row Column Row Column
No No Value No No Value

5 8 6 5 8 5

0 0 10 0 1 2

0 4 -5 0 4 7

2
2

4
1

-4
+ 1

1
1

2
3

3 0 7 3 0 4

4 1 9

Addition Result
Row Column
Value
No No

5 8 8

SE (IT) (SEMESTER I) 87 Programming Laboratory (2017-


2018)
Department of Information Technology

0 0 10

0 1 2
0 4 2

1 1 3

1 2 3

2 4 -4

3 0 11

4 1 9

Oral Questions:

i. What is a sparse matrix?


ii. What is the advantage of sparse matrix?
iii. Explain the analysis of Simple Transpose?
iv. Explain the analysis of Fast Transpose?
v. How sparse matrix can be represented using a 2 D array?
vi. How sparse matrix can be represented using structures?
vii. What are the applications of Sparse Matrix?
viii. How to represent sparse matrix using link list?
ix. Compare the time complexity of Matrix addition using normal matrices and
Sparse Matrix representation?
x. What is the time complexity for constructing a sparse matrix ?

Conclusion:

Thus we have represented Sparse matrix using array and performed matrix addition, simple and fast
transpose

Design Experiments:

a. Perform the above assignment by dynamically allocating memory for sparse


matrix representation and using pointers perform the operations like addition,
simple and fast transpose.
b. Perform multiplication of two sparse matrix
c. Represent a polynomial using Sparse Matrix representation and perform
addition, multiplication and evaluation operations.

SE (IT) (SEMESTER I) 88 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 09

Title Singly link list

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 89 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 09

Title : Operations on Singly Link List

Problem Statement :
Write a menu driven C program to perform following operations on Singly link list :
➢ Create
➢ Insertion of a node at any location
➢ Display a list
➢ Deletion of a node from any location
➢ Display in reverse
➢ Revert the list without using additional data structure.
Problem Definition :

Linked List : A linked list is an ordered collection of data elements where the order is given by
means of links i.e. each item is connected or ‘linked’ to another item.
Basically a linked list consists of “nodes”. Each node contains an item field and a link. The item field
may contain a data item or a link.

Start

node 1 node 2 node 3 node 4

A linked list may be implemented in two ways:


Static Representation :
An array is used to store the elements of the list. The elements may not be stored in a sequential
order. The correct order can be stored in another array called “Link”. The values in this array are
pointers to elements in the data array.
DATA LINK

START 0 BLUE 4

3 1 RED -1

SE (IT) (SEMESTER I) 90 Programming Laboratory (2017-


2018)
Department of Information Technology

3 VIOLET 0

4 GREEN 6

6 ORANGE 1

Dynamic representation
The static representation uses arrays, which is a static data structure and has its own limitations.
Another way of storing a list in memory is by dynamically allocating memory for each node and
linking them by means of pointers since each node will be at random memory locations. We will need
a pointer to store the address of the first node.
Each node contains two parts, data and link. The data part may contain a single data item or a
composite one like an entire record or it may be a link. The link or next part contains the address of
the next node in the list. The last node contains a special value called “NULL” which indicates end of
the list.
Since each node in the list contains only one pointer pointing to the next node, the list is called Singly
Linked List. Start is an external pointer, which stores the address of the first node of the list.
Advantages:
1. Since memory is dynamically allocated during run-time, memory is efficiently utilized.
2. There is no limitation on the number of nodes; except for the available memory.
3. Insertion, deletion and traversal can be easily done.
4. Memory can be freed when nodes to be deleted.

Primitive Operations:
Following are the primitive operations on the list data structure
1. Create List
2. Traverse the List
3. Insert a node
4. Delete a node
5. Searching a node
6. Updating a node
7. Printing a node
8. Counting the length
9. Reverse the list
10. Sort the list using data exchange
11. Sort the list using pointer manipulation

SE (IT) (SEMESTER I) 91 Programming Laboratory (2017-


2018)
Department of Information Technology

12. Concatenates two list


13. Merge two-sorted list into third sorted list.

Dynamic memory allocation functions:


malloc () function :malloc allocates a block of size bytes from the memory heap. It allows a
program to allocate memory explicitly, as it's needed, and in the exact amounts needed.
The heap is used for dynamic allocation of variable-sized blocks of memory. Many data structures,
such as trees and lists, naturally employ heap memory allocation. All the space between the end of the
data segment and the top of the program stack is available for use in the small data models, except for
a small margin immediately before the top of the stack. This margin is intended to allow the
application some room to make the stack larger, in addition to a small amount needed by DOS.
In the large data models, all the space beyond the program stack to the end of available memory is
available for the heap.

Return Value:
1. On success, malloc returns a pointer to the newly allocated block of memory.
2. On error (if not enough space exists for the new block), malloc returns null. The contents of the
block are left unchanged.
3. If the argument size == 0, malloc returns null.

free () function:free frees allocated blocks


farfree releases a block of memory previously allocated from the far heap. A tiny model program
can't use farfree. free deallocates a memory block allocated by a previous call to calloc, malloc, or
realloc.
In the small and medium memory models,
1. Blocks allocated by farmalloc can't be freed with free.
2. Blocks allocated with malloc can't be freed with farfree.

Types of linked list:


1. Singly Linear linked list
2. Doubly Linear linked list
3. Singly circular linked list
4. Doubly circular linked list

1. Singly Linear linked list

SE (IT) (SEMESTER I) 92 Programming Laboratory (2017-


2018)
Department of Information Technology

It is called singly because this list consists of only one link, to point to the next node or element.
This is also called as linear because the last element points to nothing it is linear in nature. The
link field of the last node is NULL, which means that there is no further list. The very first node
is called as head or first.
10 20 30 40
Start NULL

node 1 node 2 node 3 node 4

2. Singly circular linked list


It is called singly because this list consists of only one link, to point to the next node or element.
This is also called as circular because the last elements link field points to the first node. The link
field of the last node is not NULL

10 20 30 40
Start

node 1 node 2 node 3 node 4

3. Doubly linear linked list:


It is called doubly each node has two pointers (previous and next pointer). The previous pointer
points to the previous node and next pointer points to the next node. Only in case of head node
the previous pointer and in case of last node the next pointer is null.

4. Doubly circular linked list:


In circular doubly linked list the previous pointer of first node and the next pointer of the last
node is pointed to head node. Head node is a special node which may have any dummy data or
it may have some useful information such as total number of nodes in the list which may be
used to simplify the algorithms carrying various operation on the list

SE (IT) (SEMESTER I) 93 Programming Laboratory (2017-


2018)
Department of Information Technology

Singly-linked list: Internal representation


Every node of a singly-linked list contains following information:
• a value (user's data);
• a link to the next element (auxiliary data).
Sketchy, it can be shown like this:

First node called head and no other node points to it. Link to the head is usually stored it the class,
which provides an interface to the resulting data structure. For empty list, head is set to NULL.
Also, it makes sense to store a link to the last node, called tail.

Though no node in the list can be accessed from the tail (because we can move forward only), it
can accelerate an add operation, when adding to the end of the list. When list is big, it reduces
add operation complexity essentially, while memory overhead is insignificant. Below you can see
another picture, which shows the whole singly-linked list internal representation:

SE (IT) (SEMESTER I) 94 Programming Laboratory (2017-


2018)
Department of Information Technology

Singly-linked list: Insertion operation


Insertion into a singly-linked list has two special cases. It's insertion a new node before the head
(to the very beginning of the list) and after the tail (to the very end of the list). In any other case,
new node is inserted in the middle of the list and so, has a predecessor and successor in the list.
There is a description of all these cases below.

Empty list case


When list is empty, which is indicated by (head == NULL) condition, the insertion is quite simple.
Algorithm sets both head and tail to point to the new node.

Add first
In this case, new node is inserted right before the current head node.

It can be done in two steps:


1. Update the next link of a new node, to point to the current head node.

SE (IT) (SEMESTER I) 95 Programming Laboratory (2017-


2018)
Department of Information Technology

2. Update head link to point to the new node.

Add last
In this case, new node is inserted right after the current tail node.

It can be done in two steps:


1. Update the next link of the current tail node, to point to the new node.

SE (IT) (SEMESTER I) 96 Programming Laboratory (2017-


2018)
Department of Information Technology

2. Update tail link to point to the new node.

General case
In general case, new node is always inserted between two nodes, which are already in the list.
Head and tail links are not updated in this case.

Such an insert can be done in two steps:


1. Update link of the "previous" node, to point to the new node.

SE (IT) (SEMESTER I) 97 Programming Laboratory (2017-


2018)
Department of Information Technology

2. Update link of the new node, to point to the "next" node.

Singly-linked list: Deletion operation


There are four cases, which can occur while removing the node. These cases are similar to the
cases in add operation. We have the same four situations, but the order of algorithm actions is
opposite. Notice, that removal algorithm includes the disposal of the deleted node, which may be
unnecessary in languages with automatic garbage collection (i.e., Java).
List has only one node
When list has only one node, which is indicated by the condition, that the head points to the same
node as the tail, the removal is quite simple. Algorithm disposes the node, pointed by head (or
tail) and sets both head and tail to NULL.

SE (IT) (SEMESTER I) 98 Programming Laboratory (2017-


2018)
Department of Information Technology

Remove first
In this case, first node (current head node) is removed from the list.

It can be done in two steps:


1. Update head link to point to the node, next to the head.

2. Dispose removed node.

SE (IT) (SEMESTER I) 99 Programming Laboratory (2017-


2018)
Department of Information Technology

Remove last
In this case, last node (current tail node) is removed from the list. This operation is a bit more
tricky, than removing the first node, because algorithm should find a node, which is previous to
the tail first.

It can be done in three steps:


1. Update tail link to point to the node, before the tail. In order to find it, list should be traversed
first, beginning from the head.

2. Set next link of the new tail to NULL.

SE (IT) (SEMESTER I) 100 Programming Laboratory (2017-


2018)
Department of Information Technology

3. Dispose removed node.

General case
In general case, node to be removed is always located between two list nodes. Head and tail links
are not updated in this case.

Such a removal can be done in two steps:


1. Update next link of the previous node, to point to the next node, relative to the removed
node.

SE (IT) (SEMESTER I) 101 Programming Laboratory (2017-


2018)
Department of Information Technology

2. Dispose removed node.

Algorithms :

1. Algorithm for Creating the SLL


Algorithm Create_SLL()
1 Start

2 Accept how many elements user need to add, say, no of elements as n

3 For i = 0 to n-1
4 Create a new node by allocating memory dynamically say, node
5 Accept the element from the user and store it in node->data field
6 Initialize node->next = NULL
7 If i == 0
8 head = node
9 last = node;
10 Else

SE (IT) (SEMESTER I) 102 Programming Laboratory (2017-


2018)
Department of Information Technology

11 last->next = node;
12 last = node;
13 End if
14 End For
15 Return head

2. Algorithm for Displaying elements of SLL

Algorithm Display_SLL(sll *head)


1 Start

2 Initialize temp = head


3 While temp != NULL
4 Display node address temp, temp->data , temp->next field
5 temp = temp->next
6 End while
7 Stop

3. Algorithm for Inserting a node in the SLL

Algorithm Insert_SLL (sll *head)

1 Start
2 Accept the element to be added as x and at which position ,say pos
3 Allocate memory dynamically for the node to be inserted and store its address in node
4 node->data = x
5 If pos == 1 // first case
6 node->next = head
7 head = node
8 Else // for last and in between case

SE (IT) (SEMESTER I) 103 Programming Laboratory (2017-


2018)
Department of Information Technology

9 Initialize temp = head


10 Move temp so that temp points to node numbered (pos – 1) by traversing the list
11 node->next = temp->next
12 temp->next = node
13 End if
14 Return head

4. Algorithm for Reverting the SLL

Algorithm Revert_SLL(sll *head)


1 Start

2 Initialize cur_node = head , prev_node = NULL, curnext_node = NULL

3 While cur_node != NULL

4 curnext_node = cur->next

5 cur->next = prev_node

6 prev_node = cur_node

7 cur_node = curnext_node

8 return(p);

9 End while

10 Return prev_node

5. Algorithm for Display reverse

Algorithm Display_reverse(sll *temp )

1 Start

2 If temp != NULL

3 Recursively call Dsiplay_reverse (temp->next)

4 Display temp->data

SE (IT) (SEMESTER I) 104 Programming Laboratory (2017-


2018)
Department of Information Technology

5 End if

6 Stop

6. Algorithm for Deleting a node from SLL

Algorithm Delete_SLL(sll *head)

1 Start
2 Accept the element to be deleted as x
3 Initialize temp = head, pnode = NULL // pnode is the previous node to temp
4 While temp != NULL
5 If temp->data == x
6 Go out of the loop
7 Else
8 pnode = temp
9 temp = temp->next
10 Endif
11 End while
12 If temp != NULL
13 If temp == head // first case
14 head = head->next
15 Else // for last and in-between case
16 pnode->next = temp->next
17 End if
18 Free temp // deallocate the memory of the deleted node
19 Else
20 Display element to be deleted not present in the SLL

SE (IT) (SEMESTER I) 105 Programming Laboratory (2017-


2018)
Department of Information Technology

21 End if

22 Return head

Test Conditions:

Input a valid list and also empty list and perform necessary operations.

Sample Input Output


MENU
1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. PRINT REVERSE
6. REVERT
1. Create
Enter how many nodes to create : 4
Enter the data : 11
Enter the data : 13
Enter the data : 15
Enter the data : 17
SLL created successfully!!!!!!!!!

2. Display
NODE ADDRESS NODE->DATA NODE->NEXT
4502 11 4510
4510 13 4518
4518 15 4526
4526 17 0

3. Insert : First case


Enter the data to be inserted & at what position : 10 1
Record inserted successfully
NODE ADDRESS NODE->DATA NODE->NEXT
4542 10 4502
4502 11 4510
4510 13 4518
4518 15 4526
4526 17 0
Last Case:

SE (IT) (SEMESTER I) 106 Programming Laboratory (2017-


2018)
Department of Information Technology

Enter the data to be inserted & at what position : 20 6


Record inserted successfully
NODE ADDRESS NODE->DATA NODE->NEXT
4542 10 4502
4502 11 4510
4510 13 4518
4518 15 4526
4526 17 4550
4550 20 0
Middle case
Enter the data to be inserted & at what position : 12 4
Record inserted successfully
NODE ADDRESS NODE->DATA NODE->NEXT
4542 10 4502
4502 11 4510
4510 13 4558
4558 12 4518
4518 15 4526
4526 17 4550
4550 20 0

4. Delete
First case :
Enter the data to be deleted : 10
Node deleted successfully
NODE ADDRESS NODE->DATA NODE->NEXT
4502 11 4510
4510 13 4558
4558 12 4518
4518 15 4526
4526 17 4550
4550 20 0

Last case:
Enter the data to be deleted : 20
Node deleted successfully
NODE ADDRESS NODE->DATA NODE->NEXT
4502 11 4510
4510 13 4558
4558 12 4518
4518 15 4526
4526 17 0

Middle case
Enter the data to be deleted : 12

SE (IT) (SEMESTER I) 107 Programming Laboratory (2017-


2018)
Department of Information Technology

Node deleted successfully


NODE ADDRESS NODE->DATA NODE->NEXT
4502 11 4510
4510 13 4518
4518 15 4526
4526 17 0

Not present case


Node to be deleted is not present in the link list

5. Print Reverse

Reverse SLL is : 17 15 13 11
6. Revert
SLL Reverted successfully
NODE ADDRESS NODE->DATA NODE->NEXT
4526 17 4518
4518 15 4510
4510 13 4502
4502 11 0

SE (IT) (SEMESTER I) 108 Programming Laboratory (2017-


2018)
Department of Information Technology

Oral Questions:

1. What are the limitations of arrays?


2. What is dynamic data structure? List the advantages of linked lists?
3. Compare the linked and sequential organization of data structure?
4. What is circular link list?
5. Give the node structure for representing a polynomial using SLL?
6. Explain the parameters and return value of malloc function?
7. What is the use of free function?
8. What is skip list?
9. What is the need for dynamic storage management?
10. What is dangling pointer?

Conclusion:

Thus we have learnt how to create singly linked list and we implemented singly linked list with
following options: Insert (at front, at end, in the middle) , Delete (at front, at end, in the middle),
Display , Display Reverse , Revert the SLL.

Design Experiments:

a. Represent polynomial as a singly linked list and write a menu driven


program to perform addition multiplication and evaluation.
b. Create two singly sort one after creation & one while creation using pointer
manipulation. Merge these two lists into one list without creating a new
node(do not swap data).
c. Implement Merge Sort using SLL.

SE (IT) (SEMESTER I) 109 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No 10

Title Polynomial Using CLL

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 110 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 10

Title: Polynomials using CLL

Problem Statement :
Implement polynomial using CLL and perform

➢ Addition of Polynomial
➢ Multiplication of Polynomial
➢ Evaluation of Polynomial

Problem Definition :

Circular list :
Circular lists are like singly linked lists, except that the last node contains a pointer back to the first
node rather than the null pointer. From any point in such a list, it is possible to reach any other point
in the list. If we begin at a given node and travel the entire list, we ultimately end up at the starting
point.
Note that a circular list does not have a natural "first or "last" node. We must therefore, establish a
first and last node by convention - let external pointer point to the last node, and the following node
be the first node.

A circular linked list


Circular Singly Linked List
In circular doubly linked list the previous pointer of first node and the next pointer of the last node is
pointed to head node.

SE (IT) (SEMESTER I) 111 Programming Laboratory (2017-


2018)
Department of Information Technology

Circular Doubly Linked List


In circular doubly linked list the previous pointer of first node and the next pointer of the last node is
pointed to head node.

The node structure for CDLL:

struct CDLL
{
struct CDLL *prev;
int data;
struct CDLL *next;
};

Advantages:
➢ If we are at a node, then we can go to any node. But in linear linked list it is not possible to go
to previous node.
➢ It saves time when we have to go to the first node from the last node. It can be done in single
step because there is no need to traverse the in between nodes. But in double linked list, we
will have to go through in between nodes.
Disadvantages:
➢ It is not easy to reverse the linked list.
➢ If proper care is not taken, then the problem of infinite loop can occur.

SE (IT) (SEMESTER I) 112 Programming Laboratory (2017-


2018)
Department of Information Technology

➢ If we at a node and go back to the previous node, then we cannot do it in single step. Instead
we have to complete the entire circle by going through the in between nodes and then we will
reach the required node.

Poynomial representation using CDLL

struct poly_node

struct poly_node *next;

int coef;

int expon;

struct poly_node *next;

};

typedef struct poly_node mypoly;

Example :

F(x) = 3X4 + 4X2 + 2

Algorithms :

1. Algorithm for Accepting the polynomial


Algorithm Create_poly()
1 Start

2 Accept how many terms are present in your polynomial as n

SE (IT) (SEMESTER I) 113 Programming Laboratory (2017-


2018)
Department of Information Technology

3 For i = 0 to n-1
4 Create a new node by allocating memory dynamically say, node
5 Accept the coefficient and exponent of each term and store it in node->coef & node->exp
6 Initialize node->next = node node->prev = node
7 If i == 0
8 head = node
9 last = node;
10 Else
11 last->next = node;
12 node->prev = last
13 node->next = head;
14 head->prev = node;
15 last = node;
16 End if
17 End For
18 Return head

2. Algorithm for Displaying the polynomial


Algorithm Display_poly(mypoly *head)
1 Start

2 Initialize temp = head


3 Do
4 Display temp->coeff , temp->exp
5 temp = temp->next
6 While ( temp != head)
7 Stop

SE (IT) (SEMESTER I) 114 Programming Laboratory (2017-


2018)
Department of Information Technology

3. Algorithm for adding two polynomials

Algorithm Add_poly(P1,P2)

1 Start

2 Scan the terms of polynomial P1 and P2 one by one

3 Compare the exponent of the terms of P1 and P2

4 If one term of a polynomial has higher exponent than another term then add information of the higher
exponent term to the resultant polynomial and scan the next term in higher exponent polynomial.
5 If exponents are same, then add the coefficients and add the result to the resultant polynomial and
scan the next terms in both the polynomials.
6 Repeat from step 3 until terms in one of the polynomials are finished.

7 Add the remaining terms of another unfinished polynomial to the resultant polynomial.

8 Stop.

4. Algorithm for Multiplying two polynomials


Algorithm Multiply_poly(P1, P2)

1 Start

2 set p to the first node of one polynomial P1

3 initialize a linked list R for a zero polynomial

4 while all terms of first polynomial are scanned

5 Copy the second polynomial P2 to a new list P3

6 Multiply the term pointed by p to each term of t of P3 polynomial by

7 t->exp += p->exp

8 t->coeff *= p->coeff

SE (IT) (SEMESTER I) 115 Programming Laboratory (2017-


2018)
Department of Information Technology

9 Add polynomial P3 to polynomial R (then discard P3)

10 Advance p

11 end while

12 return R

13 Stop

5. Algorithm for Evaluation of polynomial


Algorithm Evalulate_poly(mypoly *head, int X)
1 Start

2 Initialize temp = head, sum = 0


3 Do
4 Sum = sum + temp->coef * Xtemp->exp
5 temp = temp->next
6 While ( temp != head)
7 Display sum

8 Stop

Test Conditions:

Input a valid polynomial

Sample Input Output

MENU

1. Enter first polynomial


2. Enter second polynomial
3. Addition
4. Multiplication
5. Display

Enter input:

SE (IT) (SEMESTER I) 116 Programming Laboratory (2017-


2018)
Department of Information Technology

Enter the no. of terms in the first polynomial : 3


Enter the coefficient & exponent of 1 term : 6 4
Enter the coefficient & exponent of 2 term : 2 3
Enter the coefficient & exponent of 3 term : 4 1

Enter the no. of terms in the second polynomial : 3


Enter the coefficient & exponent of 1 term : 7 3
Enter the coefficient & exponent of 2 term : 3 2
Enter the coefficient & exponent of 3 term : 9 0

Sample Output:

First polynomial = 6X^4 + 2X^3 + 4X^1


Second polynomial = 7X^3 + 3X^2 + 9X^0

Addition Result polynomial = 6X^4 + 9X^3 + 3X^2 + 4X^1 + 9X^0

Multiplication Result polynomial = 42X^7 + 32X^6 + 6X^5 + 82X^4 + 30X^3 + 36X

Evaluation : Enter the value of X = 1

First polynomial = 12
Second polynomial = 19

Oral Questions:

1.Explain briefly how to represent polynomials using singly linked lists?


2.What is the advantage of storing the last node address in head pointer for circular linked list?
3.Representation diagrammatically following polynomials using Singly linked lists?
4.p1(x) = 23x9 + 18x7 + 41x6 + 163x4 + 3 p2(x) = 4x6 + 10x4 + 12x + 8
5.What is the memory size requirement for one node of a CLL?
6.Give the Node structure for generalized list?
7.Give the node structure for representing a multivariable polynomial using GLL?
8.Representation diagrammatically the polynomials using Generalized list?
9.F(x,z) = 9x5 + 7xy4 + 10xz
10. What is the time complexity for inserting a node into a circular CLL at the end?
11. What is time complexity for deleting a node from a CLL?
12. Give the example of a Generalized recursive list?
Conclusion:

Thus we have learnt how to create circular linked list and we have also implemented the following
operations on the Polynomial like addition, multiplication and evaluation.

SE (IT) (SEMESTER I) 117 Programming Laboratory (2017-


2018)
Department of Information Technology

Design Experiments:

a. Represent polynomial as a singly linked list and write a menu driven program to perform
addition multiplication and evaluation.
b. Represent polynomial as a doubly linked list and write a menu driven program to perform
addition multiplication and evaluation.
c. Represent polynomial as a singly Circular linked list and write a menu driven program to
perform addition multiplication and evaluation.

Assignment No 11

Title Doubly link list

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 118 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 11

Title : Operations on Doubly Link List

Problem Statement :
Implement any database using doubly linked list with following options

➢ Insert a record
➢ Delete a record
➢ Modify a record
➢ Display list forward
➢ Display list backward

Problem Definition :

Definition: A variant of a linked list in which each item has a link to the previous item as well as the
next. This allows easily accessing list items backward as well as forward and deleting any item in
constant time. A doubly linked list is a linked list in which each node has a pointer to both its
successor and its predecessor. There is a link to the beginning of the list called first. The last node
links to nothing i.e., there are no nodes after it. Also, there are no nodes before the first node. The
pointer ``before'’ of the first node and the pointer ``after'’ of the last node are set to NULL.

In a doubly-linked list, each node contains, besides the next-node link, a second link field pointing to
the previous node in the sequence. The two links may be called forward(s) and backwards. Linked
lists that lack such pointers are said to be simply linked, or simple linked lists.

A doubly-linked list whose nodes contain three fields: an integer value, the link forward to the next
node, and the link backward to the previous node

Double-linked lists require more space per node (unless one uses xor-linking), and their elementary
operations are more expensive; but they are often easier to manipulate because they allow

SE (IT) (SEMESTER I) 119 Programming Laboratory (2017-


2018)
Department of Information Technology

sequential access to the list in both directions. In particular, one can insert or delete a node in a
constant number of operations given only that node's address.

The node structure for DLL:

struct DLL
{
struct DLL *prev;
int data;
struct DLL *next;
};

Disadvantage of Singly Linked List:


In singly linked list we can very easily move in one direction i.e. along the link. If for some reason we
wish to find a node’s predecessor node then we may have to start all the way from beginning of the
list. This may be a time consuming process when large number of nodes are present in the list and
we are moving in the upper half of the list. More precisely in the deletion process that it is essential
to find the preceding node of a node being deleted. This makes the algorithm little bit inefficient. To
overcome this problem we make use of another data structure, ‘Doubly Linked List’. A ‘Doubly Linked
List’ is data structure with three fields
➢ An information field
➢ Two link fields. One link is used to link the node in the forward direction and second link is
used to link the node in the backward direction.

Inserting a node in a DLL

SE (IT) (SEMESTER I) 120 Programming Laboratory (2017-


2018)
Department of Information Technology

Deleting a node from a DLL

Algorithms :

Algorithm for Creating the DLL


Algorithm Create_DLL()
1 Start

2 Accept the string say str

3 For i = 0 to n-1 // n is the no of records


4 Create a new node by allocating memory dynamically say, node
5 Accept node->data
6 Initialize node->next = NULL , node->prev = NULL
7 If i == 0
8 head = node
9 last = node
10 Else
11 last->next = node
12 node->prev = last
13 last = node

SE (IT) (SEMESTER I) 121 Programming Laboratory (2017-


2018)
Department of Information Technology

14 End if
15 End For
16 Return head

Algorithm for Displaying backward

Algorithm Display_backward_DLL(dll *head)


1 Start

2 Initialize temp = head

3 While temp->next != NULL // go to the last node

4 temp = temp->next;

5 End while

6 While temp != NULL


7 Display node address temp, temp->prev, temp->data , temp->next field
8 temp = temp->prev
9 End while
10 Stop

Algorithm for Inserting a node in the DLL

Algorithm Insert_DLL (dll *head)

1 Start
2 Accept the record to be added as x and at which position ,say pos
3 Allocate memory dynamically for the node to be inserted and store its address in node
4 Initialize node->data = x , node->prev = NULL, node->next = NULL
5 If pos == 1 // first case
6 node->next = head
7 head->prev = node;

SE (IT) (SEMESTER I) 122 Programming Laboratory (2017-


2018)
Department of Information Technology

8 head = node
9 Else // for last and in-between case
10 Initialize temp = head
11 Move temp so that temp points to node numbered (pos – 1) by traversing the list
12 If temp->next == NULL // last case
13 temp->next = node
14 node->prev = temp
15 Else // inbetween case
16 Node->prev = temp
17 Node->next = temp->next
18 node->next->prev = node
19 temp->next = node
20 Endif
21 End if
22 Return head

Algorithm for Displaying elements of DLL

Algorithm Display_DLL_forward(dll *head)


1 Start

2 Initialize temp = head


3 While temp != NULL
4 Display node address temp, temp->prev, temp->data , temp->next field
5 temp = temp->next
6 End while
7 Stop

SE (IT) (SEMESTER I) 123 Programming Laboratory (2017-


2018)
Department of Information Technology

Algorithm for Deleting a node from DLL

Algorithm Delete_DLL(dll *head)

1 Start
2 Accept the element to be deleted as x
3 Initialize temp = head
4 While temp != NULL
5 If temp->data == x
6 Go out of the loop
7 Else
8 temp = temp->next
9 Endif
10 End while
11 If temp != NULL // temp is the node to be deleted
12 If temp == head // first case
13 head = head->next
14 head->prev = NULL
15 Else
16 If temp->next == NULL // last case
17 temp->prev->next = NULL
18 Else // inbetween case
19 temp->prev->next = temp->next
20 temp->next->prev = temp->prev
21 Endif
22 End if
23 Free temp // deallocate the memory of the deleted node

SE (IT) (SEMESTER I) 124 Programming Laboratory (2017-


2018)
Department of Information Technology

24 Else
25 Display element to be deleted not present in the SLL

26 End if

27 Return head

Test Conditions:

Input a valid dll also input empty dll and perform operations on it.

Sample Input Output

MENU

1. Input
2. Display forward
3. Display Backward
4. Insert
5. Delete

1 Input
Enter the no. of records : 4
Enter the information(roll name marks) of 1 record : 1 bb 10
Enter the information(roll name marks) of 1 record : 2 dd 20
Enter the information(roll name marks) of 1 record : 3 ee 30
Enter the information(roll name marks) of 1 record : 4 ff 40

DLL created successfully!!!!!!!!!

2 Display Forward
NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT
4502 0 11 bb 10 4510
4510 4502 22 dd 20 4518
4518 4510 33 ee 30 4526
4526 4518 44 ff 40 0
3. Display Backward
NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT
4526 4518 44 ff 40 0
4518 4510 33 ee 30 4526
4510 4502 22 dd 20 4518

SE (IT) (SEMESTER I) 125 Programming Laboratory (2017-


2018)
Department of Information Technology

4502 0 11 bb10 4510


4. Insert :
First case : Enter the data to be inserted & at what position : 10 aa 11 1
Record inserted successfully

NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT


4542 0 10 aa 11 4502
4502 4542 11 bb 10 4510
4510 4502 22 dd 20 4518
4518 4510 33 ee 30 4526
4526 4518 44 ff 40 0
Last Case:Enter the data to be inserted & at what position : 55 gg 55 6
Record inserted successfully
NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT
4542 0 10 aa 11 4502
4502 4542 11 bb 10 4510
4510 4502 22 dd 20 4518
4518 4510 33 ee 30 4526
4526 4518 44 ff 40 4550
4550 4526 55 gg 55 0
Middle case : Enter the data to be inserted & at what position : 15 c 15 3
Record inserted successfully
NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT
4542 0 10 aa 11 4502
4502 4542 11 bb 10 4558
4558 4502 15 cc 15 4510
4510 4558 22 dd 20 4518
4518 4510 33 ee 30 4526
4526 4518 44 ff 40 4550
4550 4526 55 gg 55 0

5. Delete
First case : Enter the data to be deleted : aa
Node deleted successfully
NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT
4502 0 11 bb 10 4558
4558 4502 15 cc 15 4510
4510 4558 22 dd 20 4518
4518 4510 33 ee 30 4526
4526 4518 44 ff 40 4550
4550 4526 55 gg 55 0

Last case:Enter the data to be deleted : gg


Node deleted successfully
NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT

SE (IT) (SEMESTER I) 126 Programming Laboratory (2017-


2018)
Department of Information Technology

4502 0 11 bb 10 4558
4558 4502 15 cc 15 4510
4510 4558 22 dd 20 4518
4518 4510 33 ee 30 4526
4526 4518 44 ff 40 0

Middle case : Enter the data to be deleted : cc


Node deleted successfully
NODE ADDRESS NODE->PREV NODE->DATA NODE->NEXT
4502 0 11 bb 10 4510
4510 4502 22 dd 20 4518
4518 4510 33 ee 30 4526
4526 4518 44 ff 40 0

Not present case


Enter the data to be deleted : zz
Node to be deleted is not present in the link list

Oral Questions:
a. What are the differences between SLL and DLL?
b. Why is Generalized link list?
c. List the different types of link list?
d. What is the memory size requirement for one node of a DLL?
e. What is the use of calloc?
f. What is the use of realloc?
g. What is a generic pointer?
h. What is the time complexity for inserting a node into a circular DLL at the end?
i. What is time complexity for deleting a node from a DLL?
j. what is NULL?

Conclusion:

Thus we have learnt how to create doubly linked list and we have also implemented the following
operations on the doubly linked list like constructing a Doubly Linked List, Insert, Delete ,Display
forward and Display backward operations.

Design Experiments:

a. Write a program to accept binary numbers in doubly linked list & perform addition of
them store the result in another list and revert the result.

SE (IT) (SEMESTER I) 127 Programming Laboratory (2017-


2018)
Department of Information Technology

b. Create two circular doubly linked lists sort one after creation & one while creation
using pointer manipulation. Merge these two lists into one list without creating a new
node(do not swap data).
c. Represent polynomial as a Generalized linked list and write a menu driven program to
perform addition multiplication and evaluation.

Assignment No 12

Title Generalized linked list

Roll No

Date of performance

Date of completion

Marks out of 10

Signature of staff

SE (IT) (SEMESTER I) 128 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No : 12

Title : Generalized Linked List

Problem Statement :

Implement Generalized Linked List to create and display the book index.

Definition:

A linear list , we define as finite sequence of n-elements a1,a2…..an. we represent as


A=(a1,a2…..an). Here we noticed that each elements a belongs to A has a unique structural property
having single position i.e. ai+1 succeeds a1 and each ai is an atom. To facilitate this we go in
generalized linked list .

Elements of the linear list can be addressed by its index.

A=() An empty or null list.

B=(a,b,c) A list of three elements with B(1) =a ,B(2) =b and B(3)= C

A generalized linked list “ A” is a finite sequence of ‘n’ elements where ai may be either atoms or
list . The elements ai which are not atoms are called sublist of ‘A’.

In generalized linked list ,each element ai is either an atom or a list itself.

C=(a(b,c),d) // A list of three elements .

First element ‘a’ is atomic. Second element (b,c) is a list. Third element ‘d’ is atomic .

Thus ,a generalized linked list ,A is finite sequence of n>0 elements a1,a2…an.

Where each ai is either an atom or list. A1 is said to be the head of A. (a2…an) is called the tail of A.

Note that the elements if all are atoms then it turns out to be a simple list.

The node sequence for generalized link list is as shown.

SE (IT) (SEMESTER I) 129 Programming Laboratory (2017-


2018)
Department of Information Technology

Tag=true/false Data/Link Link

Tag indicates whether an element is atom or sublist.


Let us assume that if tag=0 ,element is atom.
If tag=1 ,element is sublist.

The link field is used as pointer to the list, while the “Data/link” field can hold an atom in case head
(A) is an atom or be a pointer to the list representation of head(A) is case it is a list. The ‘tag’ will
denote link or data.

Polynomial representation using GLL

Suppose if we are having a polynomial with three variables then we may think of representation it by
using simple list, we might think of having node structure is :

Coeff,ExpX,ExpY,ExpZ,Link

But this would mean that polynomial in different number of variable would need a different number
sequential representation . Thus, nodes would have to vary in size depending on the number of
variable .It makes storage management difficult .Hence, we make use of GLL to represent the
polynomial. The general idea is to factorize the given polynomial so that each element of polynomial
either becomes an atom or an list.

ALGORITHM FOR GLL

enum field {ATOM, DOWN};


enum boolean {FALSE,TRUE};
Abstract Data Type Stack:
Define structure GLL
integer Flag;
Define Structure for Tag (Atom, Declare 'Down' Pointer to struct tag);
Declare pointer 'Next' to structure GLL;

Create GLL:
string is character array which contains list;
Declare static int i=0;
node is pointer object of structure GLL;
This function returns Head of list;
create(string)
Step 1: if string[i]=='\0'

SE (IT) (SEMESTER I) 130 Programming Laboratory (2017-


2018)
Department of Information Technology

return NULL;
Step 2: Do i++ while string[i]==',' || string[i]==' ';
Step 3: Create new Node of GLL ;
Step 4: if string[i]=='('
Node->flag = DOWN;
i++;
Node->Tag.Down = create(string);
if string[i] != '\0'
Node->Next = create(string);
else i = 0;
Step 4: else
if isalpha(string[i])
Node->Flag = ATOM;
Node->Tag.Atom = string[i++];
Node->Next = create(string);
else if string[i] == ')'
i++;
free(Node);
return NULL;
Step 5: return Node;

Create GLL:
Head is pointer object of structure GLL;
Display(GLL Head)
Step 1: if Head == NULL;
Step 2: else
Step 3: if Head->Flag == DOWN
Display(Head->Tag.Down);
if Head->Next!=NULL
Display(Head->Next);
Step 4: else
print Head->Tag.Atom;
Display(Head->Next);
Step 5: Stop.

SE (IT) (SEMESTER I) 131 Programming Laboratory (2017-


2018)
Department of Information Technology

Assignment No. 6

Title Sequential File Operations

Roll No.

Date of performance

Date of completion

Signature of staff

SE (IT) (SEMESTER I) 1 Programming Laboratory (2016-2017)


Department of Information Technology

Assignment No.: 6

Title: Sequential File Operations

Objective:
• To understand FILE structure
• To understand the concept of sequential files
• To know different modes to access file
• To understand the primitive operations such as create, write, read, close, etc. on the sequential file.

Problem Statement:
Implement all primitive operations on Sequential file in C.

Example : Bank account processing:


1. Account number (numeric max length 10)
2. Name (alphanumeric max length 20)
3. Balance (numeric max length less than Rs. 10,00,000)
4. Overdrawn Flag

Theory:
1. Temporary & permanent file storage
2. Definition of File, File Structure, File pointer.
3. Differentiate between File formats (Text, Binary).
4. Different modes of opening a file.
5. Different functions for files with an example for each
a. Open ,Close
b. Formatted and Unformatted I/O
c. Read, Write (character)
d. Read, write (Strings and records)
e. fseek()
f. fflush()
g. ftell()

SE (IT) (SEMESTER I) 2 Programming Laboratory (2016-2017)


Department of Information Technology

H. Rewinding

I. Rename

J. Remove

K. End Of File

6. Primitive operations on files. (Crate, Modify, Delete, Search, Display, Append, Pack)
7. Advantages and Disadvantages of Sequential files.

Applications:

Sequential Datasets are good to use when:


1. You are in a batch environment.
2. The database does not contain a huge amount of data.
3. You are not keeping the data over an extended period of time
4. You don’t want to pay the money to purchase, install and maintain some of the bigger database systems
(like DB2).

Algorithms:
[1] Algorithm CREATE()

1. accept the file name


2. open file in write mode
3. accept number of records- n
4. accept record from user and write it into file
5. repeat the procedure for n records
6. close file
[2] Algorithm READ_ALL()

1. accept the file name


2. open file in read mode
3. n=find total no. of records in the file
4. while n>0 do

SE (IT) (SEMESTER I) 3 Programming Laboratory (2016-2017)


Department of Information Technology

5. read one record


6. if (deleted flag of the record not equal to one)
7. display record
8. end if
9. n- -
10. end while
11. close file
12. end
[3] Algorithm WRITE_REC()

1. accept the file name


2. open file in append mode
3. accept data to be written to the file from user
4. write data into the file
5. close file
6. end
[4] Algorithm FIND( key)

Returns Location of the record if the key is matched otherwise returns -1 if key not found

1. accept the file name


2. open file in read mode
3. set location to 0
4. set found flag to -1
5. read the record
6. location++
7. compare the key field with the key
8. if the key is matched then
9. set found flag to 1
10. display the record
11. go to step 14
12. end if
13. repeat steps 5 through12 till all records are checked

SE (IT) (SEMESTER I) 4 Programming Laboratory (2016-2017)


Department of Information Technology

14. Close file.


15. if not found location = -1
16. return location
[5] Algorithm MODIFY()

1. Accept the file name


2. open file in read-write mode
3. accept key of record to be found
4. location= Find(key)
5. if location!=-1 then
6. seek the record at found location
7. read the record
8. make required modifications
9. write it back at the given location
10. end if
11. Close file.
12. End

[6] Algorithm DELETE()

1. accept the file name


2. open file in write mode
3. accept key of record to be found
4. location= Find(key)
5. if location!=-1 then
6. seek the record at found location
7. read the record
8. set the deleted flag to 1
9. write it back at the given location
10. end if
11. Close file.

SE (IT) (SEMESTER I) 5 Programming Laboratory (2016-2017)


Department of Information Technology

Testing:
Input:
Create a sequential file and use it as an input to perform various operations.

Output:
Updated File after performing read records, write record, modify, search, delete operations on it.

Analysis:
The worst case complexity of Sequential file is O(N) for N records in the file.
Advantages:
1. Extremely easy to program
2. Requires simplest of file structures.

Disadvantage:
1. Sequential searching is just too expensive for most serious retrieval situations.
2. Not suitable for files with large no of records.

Conclusion:
Thus we have implemented sequential file.

SE (IT) (SEMESTER I) 6 Programming Laboratory (2016-2017)

Das könnte Ihnen auch gefallen