You are on page 1of 99

Programming Lab Manual

PL Lab Manual Work Load Theory 4 Hrs. 4 Hrs. Term Work 50 Index Practical Practical 50 Oral Time Span (No. of weeks) 1

Sr. No. 1 2

Name of Assignment Implement set operations using arrays and perform union, intersection, difference, symmetric difference. Implement following Matrix operations: a. Addition with pointers to arrays, b. Multiplication without pointers to arrays, c. Transpose with pointers to arrays, d. Saddle point without pointers to arrays String manipulations like substring, palindrome, compare etc. with and without pointers to arrays (without using built in functions) Structure manipulation (for any database like Employee or Bank database) with and without pointers to structures. Accept student information (e.g. Roll No, Name, Percentage etc.). a. Display the data in descending order of Percentage (Bubble Sort) b. Display data for Roll No specified by user (Linear Search) c. Display the number of passes and comparisons for different test cases (Worst, Average, Best case). Accept Mobile user information (e.g. Mobile No, Name, Bill Amount etc.). a.. Display the data in descending order of Mobile No. (insertion Sort) b. Display the data in ascending order of Name (Selection Sort) c. Display details for Mobile No specified by user (Binary Search) d. Display the number of passes and comparisons for different test cases (Worst, Average, Best case).

1.5

1.5

4 5

1.5

1.5

Programming Lab Manual

7 8 9

Implement Quick Sort recursively of the following set of numbers such as 56, - 90, 80, 78, 234, 654, 432, 12, 0, -11 Implement Sparse matrix and perform following operations on it: Addition, Simple Transpose and Fast Transpose. Create a singly linked list with options: a).Insert (at front, at end, in the middle), b). Delete (at front, at end, in the middle), c). Display, d). Display Reverse, e).Revert the SLL. Accept input as a string and construct a Doubly Linked List for the input string with each node contains, as a data one character from the string and perform: a). Insert, b). Delete, c). Display forward, d). Display backward.

1 1.5

1.5

10

1.5

Note: Objectives and pre-requisite will be discussed in Presentation.

Programming Lab Manual

Assignment No. 1
Title of Assignment : Implement set operations using arrays and perform union, intersection, difference, symmetric difference. Relevant Theory / Literature Survey: Arrays Array types in C are always one-dimensional and, traditionally, of a fixed, static size specified at compile time. (The more recent "C99" standard also allows a form of variable-length arrays.) However, it is also possible to allocate a block of memory (of arbitrary size) at runtime, using the standard library's malloc function, and treat it as an array. C's unification of arrays and pointers (see below) means that true arrays and these dynamically-allocated, simulated arrays are virtually interchangeable. Since arrays are always accessed (in effect) via pointers, array accesses are typically not checked against the underlying array size, although the compiler may provide bounds checking as an option. Array bounds violations are therefore possible and rather common in carelessly written code and can lead to various repercussions: illegal memory accesses, corruption of data, buffer overrun, run-time exceptions, etc. C does not have a special provision for declaring multidimensional arrays, but rather relies on recursion within the type system to declare arrays of arrays, which effectively accomplishes the same thing. The index values of the resulting "multidimensional array" can be thought of as increasing in row-major order.

Arraypointer interchangeability
A distinctive (but potentially confusing) feature of C is its treatment of arrays and pointers. The array-subscript notation x[i] can also be used when x is a pointer; the interpretation (using pointer arithmetic) is to access the (i+1)th of several adjacent data objects pointed to by x, counting the object that x points to (which is x[0]) as the first element

Programming Lab Manual

of the array. Formally, x[i] is equivalent to *(x + i). Since the type of the pointer involved is known to the compiler at compile time, the address that x + i points to is not the address pointed to by x incremented by i bytes, but rather incremented by i multiplied by the size of an element that x points to. The size of these elements can be determined with the operator sizeof by applying it to any dereferenced element of x, as in n = sizeof *x or n = sizeof x[0]. Furthermore, in most expression contexts (a notable exception is sizeof array), the name of an array is automatically converted to a pointer to the array's first element; this implies that an array is never copied as a whole when named as an argument to a function, but rather only the address of its first element is passed. Therefore, although C's function calls use pass-by-value semantics, arrays are in effect passed by reference. The number of elements in a declared array a can be determined as sizeof a / sizeof a[0]. An interesting demonstration of the interchangeability of pointers and arrays is shown below. The four assignments are equivalent and each is valid C code. Note how the last line contains the strange code i[x] = 1;, which has the index variable i apparently interchanged with the array variable x. This last line might be found in obfuscated (Unclear) C code.
/* x designates an array */ x[i] = 1; *(x + i) = 1; *(i + x) = 1; i[x] = 1; /* strange, but correct: i[x] is equivalent to *(i + x) */

However, there is a distinction to be made between arrays and pointer variables. Even though the name of an array is in most expression

Programming Lab Manual

contexts converted to a pointer (to its first element), this pointer does not itself occupy any storage. Consequently, you cannot change what an array "points to", and it is impossible to assign to an array.

Memory management
One of the most important functions of a programming language is to provide facilities for managing memory and the objects that are stored in memory. C provides three distinct ways to allocate memory for objects:

Static memory allocation: space for the object is provided in the binary at compile-time; these objects have an extent (or lifetime) as long as the binary which contains them is loaded into memory Automatic memory allocation: temporary objects can be stored on the stack, and this space is automatically freed and reusable after the block in which they are declared is exited Dynamic memory allocation: blocks of memory of arbitrary size can be requested at run-time using library functions such as malloc from a region of memory called the heap; these blocks can be subsequently freed for reuse by calling the library function free

These three approaches are appropriate in different situations and have various tradeoffs. For example, static memory allocation has no allocation overhead, automatic allocation has a small amount of overhead during initialization, and dynamic memory allocation can potentially have a great deal of overhead for both allocation and deallocation. On the other hand, stack space is typically much more limited and transient than either static memory or heap space, and dynamic memory allocation allows allocation of objects whose size is known only at run-time. Most C programs make extensive use of all three. Where possible, automatic or static allocation is usually preferred because the storage is managed by the compiler, freeing the programmer of the potentially error-prone hassle of manually allocating and releasing storage. Unfortunately, many data structures can grow in size at runtime; since automatic and static allocations must have a fixed size at compile-time, there are many situations in

Programming Lab Manual

which dynamic allocation must be used. Variable-sized arrays are a common example of this . Set Operations: 1. Union: A B = { x| x A or x B} 2. Intersection A B = {x| x A and x B} 3. Difference A B = {x| x A and x B} 4. Symmetric Difference A B = (A-B) (B-A) = {x| x A Band x A B} Design Analysis / Implementation Logic: Pseudocode #define MAX 10 /* Maximum size of arrays*/ /* Prototype Declaration of functions used */ void initialize(int r[],int); void read_array ( int p[], int); void write_array ( int p[], int); void union_array ( int p[],int q[],int r[], int, int); void intersect_array( int p[],int q[], int r[],int, int ); void diff_array( int p[],int q[], int r[],int, int); void sym_diff_array( int p[],int q[], int r[],int, int ); void print_result( int p[],int q[], int r[],int x, int y, int z); int check_presence(int p[],int,int); /* main() begins here */ main() { /* Declare arrays (A[] & B[] of size MAX &C[] of size 2* MAX)

Programming Lab Manual

*/ /* Declare Local variables; */ /* Accept the size of Array A and Array B in m and n respectively; */ Accept the m elements of array A and n elements of B Call read_array(A,m); read_array(B,n); /* Display Menu and allow user to choose operation to be*/ /* performed until the user wants to exit explicitly*/ while(1) { Display the Title (Program for Demonstration of Set Operation using Arrays); Provide options to select the Operation to be performed 1.Union 2.Intersection 3.Difference 4.Symmetric Difference 5.Exit\n"); Accept(Choice ) switch(choice) { case 1 :Call union_array (A,B,C,m,n); break; case 2 : Call intersect_array(A,B,C,m,n); break; case 3 : Call diff_array(A,B,C,m,n); break; case 4 : Call sym_diff_array(A,B,C,m,n); break;

Programming Lab Manual

case 5 : Call exit(0); break; default : printf("Choose correct option"); } /* End of Switch Case */ } /* End of While (1) */ } /* End of main() */ /* Definition of Functions */ void initialize(int r[],int s) { /* Declaration of local variables */ for(i to s) r[i]=0; } void read_array ( int p[], int s) { /* Declaration of local variables */ for(i=0 to i<s) do Read elements for the array } void write_array ( int p[], int s) { /* Declaration of local variables */ for(i=0 to i<s) do Print elements for the array } /* Definition of function for Union of two sets */ void union_array ( int p[],int q[],int r[], int x, int y ) { /* Declaration of local variables */

Programming Lab Manual

/* Initialize resultant array call initialize(r,2*MAX); i = j = pos=0;

to 0 */

/* j is Array index for resultant array*/ /*pos to hold the size of the resultant array */ r[j] = p[i]; j = 1; pos = j; /* Check if the element in array p is already present in the resultant array r */ for(i = 1; i<x;i++) { /* Flag to check if the element is already present in the resultant array */ present_in_r =check_presence(r,pos,p[i]); if (not present_in_r) { insert p[i] into r[] j++; pos=j; } } /* Check if the element in array q is already present in the resultant array r */ for(i = 0; i<y;i++) { /* Flag to check if the element is already present in the resultant array */ present_in_r =check_presence(r,pos,q[i]); if ( not present_in_r ) /* Copy first element of First array to the resultant array */

Programming Lab Manual

{ insert q[i] into r[] j++; pos=j; } } /* Print the result of Union */ printf(" The Union of Array A and Array B is :\n"); print_result(p,q,r,x,y,pos); } /* Definition of function for Intersection of two sets */ void intersect_array( int p[],int q[],int r[], int x, int y) { /* Declaration of local variables */ /* Initialize resultant array call initialize(r,2*MAX); i = 0; j = 0; pos = 0; /* Array index for resultant array*/ /* To hold the size of the resultant array */ to 0 */

/* Check if the element in array p is already present in the resultant array r*/ for(i = 0;i<x;i++) { /* Flag to check if the element is already present in the resultant array */ present_in_r =check_presence(r,pos,p[i]); /*If not present in resultant array r, Check if it is present in q */ if (not present_in_r) { present_in_q=check_presence(q,y,p[i]);

Programming Lab Manual

if(present_in_q) { insert p[i] into r[] j++; pos=j; } } } /* Print the result of Intersection */ printf("The Intersection of Array A and Array B is :\n"); print_result(p,q,r,x,y,pos); } /* Definition of function for Difference of two sets */ void diff_array( int p[],int q[],int r[],int x, int y) { /* Declaration of local variables */ /* Initialize resultant array call initialize(r,2*MAX); i = 0; j = 0; pos = 0; /* Array index for resultant array*/ /* To hold the size of the resultant array */ to 0 */

/* Check if the element in array p is already present in the resultant array r*/ for(i = 0;i<x;i++) { /* Flag to check if the element is already present in the resultant array */ present_in_r =check_presence(r,pos,p[i]); /*If not present in resultant array r, Check if it is present in q */

Programming Lab Manual

if (not present_in_r) { present_in_q=check_presence(q,x,p[i]); if(not present_in_q) /* if Present in q*/ { insert p[i] into r[] j++; pos=j; } } } /*Print the result of Difference*/ printf("The Differnce of Array A and Array B is :\n"); print_result(p,q,r,x,y,pos); } /* Definition of function for Symmetric Difference of two sets */ void sym_diff_array( int p[],int q[],int r[],int x, int y) { /* Declaration of local variables */ /* Initialize resultant array call initialize(r,2*MAX); i = 0; j = 0; pos = 0; /* Array index for resultant array*/ /* To hold the size of the resultant array */ to 0 */

/* Check if the element in array p is already present in the resultant array r*/ for(i = 0;i<x;i++) { /* Flag to check if the element is already present in the resultant array */ present_in_r =check_presence(r,pos,p[i]);

Programming Lab Manual

/*If not present in resultant array r, Check if it is present in q */ if ( not present_in_r) { present_in_q=check_presence(q,y,p[i]); if(not present_in_q==0) { insert p[i] into r[] j++; pos=j; } } } for(i=0;i<y;i++) { /* Flag to check if the element q[i] is present in the p[] */ present_in_p=check_presence(p,x,q[i]); /* Flag to check if the element is already present in the resultant array */ present_in_r=check_presence(r,pos,q[i]); if(!present_in_p && !present_in_r) { insert q[i] into r[] j++; pos=j; } } /* Print the result of Difference */ printf("The Symmetric Differnce of Array A and Array B is :\n"); print_result(p,q,r,x,y,pos);

Programming Lab Manual

} /* Function to Print A,B and the Result */ void print_result( int p[],int q[], int r[],int x, int y, int z ) { printf("\nArray A is :\n\n"); call write_array(p,x); printf("\nArray B is :\n\n"); call write_array(q,y); if (z!=0) { printf("\n Resultant Array C is :\n\n"); call write_array(r,z); } else printf("\nArray C is :\n\nEmpty Set\n"); } int check_presence(int p[],int x,int qi) { int i,present=0; for(i=0;i<x;i++) { if(p[i]==qi) { present=1; break; } } return(present); }

Programming Lab Manual

Testing: Input : m = 5 /* Size of array A*/ n = 5 /* Size of array B*/ A = {1,2,3,4,5} B = {3,4,5,6,7} Output : 1. Union of A = {1,2,3,4,5} & B = {3,4,5,6,7} is B = {3,4,5,6,7} is B = {3,4,5,6,7} is B = {3,4,5,6,7} C = {1,2,3,4,5,6,7} 2. Intersection of C = {3,4,5} 3. Difference of C = {1,2} 4. Symmetric Difference of is C = {1,2,6,7} 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. Union 2. Intersection 3. Difference 4. Symmetric Difference A = {1,2,3,4,5} & A = {1,2,3,4,5} & A = {1,2,3,4,5} &

Programming Lab Manual

Assignment No. 2 Title of Assignment : Implement following Matrix operations: a. Addition with pointers to arrays, b. Multiplication without pointers to arrays, c. Transpose with pointers to arrays, d. Saddle point without pointers to arrays Relevant Theory / Literature Survey: Statically creating Multidimensional Arrays Two Dimensional arrays can be thought of as a table consisting of rows and columns int a[3][4], declares an integer array of three rows and four columns. Row index will start from 0 and will go upto 2 Similarly, column index will start from 0 and will go upto 3. Col 1 a[0] [0] a[1] [0] a[2] [0] Row 0 Row 1 Row 2 a[0] [1] a[1] [1] a[2] [1] Col 2 a[0] [2] a[1] [2] a[2] [3] Col 3 a[0] [3] a[1] [3] a[2] [3] Col 4

Passing an array to the Function


void read_array( int a[][10],int m, int n) { for (I=0;I<m;I++) for(j=0;j<n;j++) scanf(%d,&a[I][j]); } main()

Programming Lab Manual

{ int m=3,n=3; read_array(a,m,n); } Dynamically Allocating Multidimensional Arrays If we don't know how many columns the array will have, we'll clearly allocate memory for each row (as many columns wide as we like) by calling malloc, and each row will therefore be represented by a pointer. How will we keep track of those pointers? There are, after all, many of them, one for each row. So we want to simulate an array of pointers, but we don't know how many rows there will be, either, so we'll have to simulate that array (of pointers) with another pointer, and this will be a pointer to a pointer. This is best illustrated with an example: #include <stdlib.h> int **array; array = malloc(nrows * sizeof(int *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); exit or return } for(i = 0; i < nrows; i++) { array[i] = malloc(ncolumns * sizeof(int)); if(array[i] == NULL) { printf( "out of memory\n"); exit or return }

Programming Lab Manual

} is a pointer-to-pointer-to-int: at the first level, it points to a block of pointers, one for each row. That first-level pointer is the first one we allocate; it has nrows elements, with each element big enough to hold a pointer-to-int, or int *. If we successfully allocate it, we then fill in the pointers (all nrows of them) with a pointer (also obtained from malloc) to ncolumns number of ints, the storage for that row of the array. If this isn't quite making sense, a picture should make everything clear:
array

Once we've done this, we can (just as for the one-dimensional case) use array-like syntax to access our simulated multidimensional array. If we write array[i][j] we're asking for the i'th pointer pointed to by array, and then for the j'th int pointed to by that inner pointer. Dynamically-allocated twodimensional ``array'' can still be accessed just as if it were an array of arrays, i.e. with the same pair of bracketed subscripts.) If a program uses simulated, dynamically allocated multidimensional arrays, it becomes possible to write ``heterogeneous'' functions which don't have to know (at compile time) how big the ``arrays'' are. In other words, one function can operate on ``arrays'' of various sizes and shapes. The function will look something like func2(int **array, int nrows, int ncolumns) { } This function does accept a pointer-to-pointer-to-int, on the assumption that we'll only be calling it with simulated, dynamically allocated multidimensional arrays. The function also accepts the dimensions of the arrays as parameters, so that it will know how many ``rows'' and ``columns'' there are, so that it can iterate over them correctly. Here is a function which zeros out a pointer-to-pointer, two-dimensional ``array'':

Programming Lab Manual

void initialize(int **array, int nrows, int ncolumns) { int i, j; for(i = 0; i < nrows; i++) { for(j = 0; j < ncolumns; j++) array[i][j] = 0; } } Finally, when it comes time to free one of these dynamically allocated multidimensional ``arrays,'' we must remember to free each of the chunks of memory that we've allocated. (Just freeing the top-level pointer, array, wouldn't cut it; if we did, all the second-level pointers would be lost but not freed, and would waste memory.) Here's what the code might look like: for(i = 0; i < nrows; i++) free(array[i]); free(array); Pointers and Arrays Basic Pointer Arithmatic

Integers always refer to increments of the base type Adding an integer to a pointer works like [] operator Subtracting 2 pointers give you integer difference

Example 1: int main() { int x[10], *xp, *yp, diff; xp = &x[5]; yp = x+5; // Now xp == yp xp = &yp[-5]; // Now xp == x; // Subtraction of one pointer from another diff = yp - x; // Now diff == 5 }

Example 2:
Addition of a Number to a pointer

Programming Lab Manual

int i=4,*j,*k; j = &i; j=j+1; j= j+9; k=j+3; Subtraction of a number from a pointer int i=4,*j,*k; j = &i; j=j-2; j=j-5; k=j-6; Never ever work out the following operation on pointers 1. Addition of two pointers 2. Multiplication of a pointer with a constant 3. Division of a pointer with a constant Two facts about Arrays: 1. Array elements are always stored in contiguous memory location 2. A pointer when incremented always points to an immediately next location of its type. Operations on Matrices Addition of two Matrices A and B with i rows and k columns

Multiplication of two matrices A(i,j) and B(k,i)

Saddle point

An M N matrix is said to have a saddle point if some entry a[i][j] is the smallest in row i and the largest in column j. In the following example matrix, 7 is the saddle point. |123| a=|456|

Programming Lab Manual

Design Analysis / Implementation Logic: Algorithms of Functions to be used (I) Algorithm accept (int m[][]) :- Nil :- Matrix should be accepted :- Nil

Precondition Postcondition Return 1. 2. 3. 4. 5. 6. 7. 8.

Read rows Read columns Enter the matrix elements for ( i=0;i<r;i++) for (j=0;j<c;j++) read element at m1[i][j] as no end end

(II) Algorithm addition( int m1[][], int m2[][], int m3[][],int r1,int c1, int r2, int c2) Precondition Postcondition Return :- Two matrices should be accepted. :- Result of addition of two matrices :- Nil

1. if (r1 == r2 && c1 == c2) 2. for ( i=0;i<r2;i++) 3. for(j=0;j<c2;j++) 4. m3[i][j] = m1[i][j] + m2[i][j] 5. end 6. end 7. else 8. Display Addition not possible 9. endif (III) Algorithm multiplication ( int m1[][], int m2[][], int m3[] [],int r1,int c1, int r2, int c2) Precondition Postcondition Return 1. if( c2==r2) :- Two matrices should be accepted. :- Result of multiplication of two matrices :- Nil

Programming Lab Manual

2. Loop ( i=0;i<r2;i++) 3. loop (j=0;j<c2;j++) 4. loop(k=0;k<r2;k++) 5. m3[i][j] += m1[i][k] *b[k][j] 6. end loop 7. end loop 8. end loop 9. else 10. display Multiplication cannot be performed (IV) Algorithm display (int m[][], int r1,int c1) Precondition Postcondition Return :- Matrix should be accepted. :- display the matirx :- Nil

1. for (i=0;i<r1;i++) 2. for(j=0;j<c1;j++) 3. display matrix[i][j] 4. end 5. end (V) Algorithm initialize(int r[][],int m,int n) Precondition Postcondition Return :- Matrix should be accepted. :- All the matrix elements are zero :- Nil

1. loop (i=0 to i<m) 2. loop (j=0 to j<n) 3. r[i][j]=0; 4. End loop 5. End loop (VI) Algorithm print_result( int p[][],int q[][], int r[][],int m, int n, int o, int p ) Precondition Postcondition Return :- Matrices should be accepted with number of rows and columns :- All the matrices are displayed :- Nil

Programming Lab Manual

1. printf("\nMatrix A is :\n\n"); 2. call display(p,m,n); 3.printf("\nMatrix B is :\n\n"); 4. call display(q,o,p); 5.printf("\n Resultant Matric C is :\n\n"); 6. call display(r,m,p); (VII) Algorithm Saddle_point(int m[][],int M,int N) Precondition Postcondition displayed Return :- Matrix should be accepted. :- Sadlle point of the matrix and its location is :- Nil

1. for i=0 to M-1 2. min = minimum value in row i. 3. for j=0 to N-1 // findMin().

4. max = maximum value in column j. // findMax(). 5. if (min == max) 6. print "saddle found at row ", i, "and column ", j. 7. end loop 8. end loop 9. End int findMin( int a[][N], int row ) { /* find min value in row of a and return the value.*/ } int findMax( int a[][N], int col ) { /* find max val in col of a and return the value. */ }

Programming Lab Manual

Testing: 1. Addition Input : A= 1 2 3 334 222 Output : C= A+B = 2 5 7 445 463 2. Multiplication Input : A= 1 2 3 334 222 Output : C= A+B = 9 17 9 14 28 19 8 16 12 3. Transpose Input : A= 1 2 3 456 789 Output: B= 1 4 7 258 369 4.Saddle point Input : A= 1 2 3 B= 1 3 4 111 241 B= 1 3 4 111 241

Programming Lab Manual

456 789 Output: The Saddle point of the matrix is 7 and at location(2,0).

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 set operations on the matrices: 1. Addition 2. Multiplication 3. Transpose 4. Saddle Point

Programming Lab Manual

Assignment No. 3 Title of Assignment : String manipulations like 1. StringCopy , 2. StringLength, 3. StringCompare , 4. StringReverse, 5. StringConcat , 6. SubString 7. Pallindrome with and without pointers to arrays (without using built in functions) Relevant Theory / Literature Survey: Theory : A string is a list (or string) of characters stored contiguously with a marker to indicate the end of the string. We can easily implement a string by using an array of characters if we keep track of the number of elements stored in the array. Every String is terminated by a NULL character i.e. \0. For example, the string "Hello" is stored in a character array, msg[], as follows:
char msg[SIZE];

msg[0] = 'H'; msg[1] = 'e'; msg[2] = 'l'; msg[3] = 'l'; msg[4] = 'o'; msg[5] = '\0'; String is stored and retrieved starting from Index 0 onwards. string constants, such as "Hello" is automatically terminated by NULL by the compiler. 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

Programming Lab Manual

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 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. Design Analysis / Implementation Logic: Pseudocode (I)Algorithm StringCopy ( char src[] , char dest[] ) This algorithm reads a Source String character by character and copies it to the destination String. Pre-condition Post-condition Return :- Source string should be accepted :- copy of source should be present in destination String. :- reference to Copied String

1 index = 0 2 while ( src[index] != \0 ) 3 dest[index] = src[index] 4 index = index + 1 5 end 6 dest[index] =\0 7 return reference to the Copied String (II) Algorithm StringLength (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

Programming Lab Manual

Post-condition :- Length of the String should be calculated. Return :- Length of the String. 2 1 index =0 while ( src[index] != \0 ) 3 len = len +1 4 index = index + 1 5 end 6 return len

(III) Algorithm StringCompare ( 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 Post-condition Return :- Both the Strings should be accepted :- Equality of the Strings should be checked. :- Result of comparison (1/0)

1 index= 0; 2 while( str1[index] != \0 and 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] 10 return diff (IV) Algorithm StringConcat ( char str1[],char str2[]) 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 Post-condition Return :- Both the Strings should be accepted :- Source String should be appended at the end of destination string :- reference to destination String 1 index1 = 0 while( not end of the str1) 3 index1 = index1 + 1

Programming Lab Manual

4 end 5 index2 = 0 6 while ( not end of str2 ) 7 str1[index1] = str2[index2] 8 index1 = index1 +1 9 index2 = index2 + 1 10 end 11 terminate destination string (str1) by \0 character 12 return reference to destination string (str1) (V) Algorithm StringReverse ( char str1[],char str2[]) This algorithm reads the source string character by character and adds each character to the destination string in reverse order and returns the reference to the destination String. Pre-condition Post-condition Return :- the source String should be accepted :- Reverse of the Source String should be present in destination String. :- reference to destination String

1 length = 0 2 while ( not end of the str1) 3 length = length + 1 4 end 5 index = 0 6 while ( length>=0 ) 7 str2[index] = str1[length] 8 index = index+1 9 length = length - 1 10 end 11 terminate destination string (str2) by \0 character 12 return reference to destination string (str2) (VI) 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 Post-condition Return :- Both the Strings should be accepted :- Check for occurrence of string2 in string1. :- Boolean value as a result of comparison (1/0)

Programming Lab Manual

6 8

1 index1 = 0 2 index2 = 0 3 while (not end of str1) 4 index2 = 0 5 while (not end of str2) if str1[index1] is equal to str2[index2] 7 index1 = index1 + 1 index2 = index2 + 1 9 else 10 goto step 12 11 end 12 end loop 13 if (end of str2[index2] ) 14 flag =1 15 goto step 19 16 else 17 index1 = index1 + 1 18 endif 19 end loop 20 if flag =1 21 return 1 22 else 23 return 0 (VI) Algorithm Palindrome (char str1[])

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 index1 = 0 2 index2 = strlen(str1)-1 while ( index1 is not equal to index2) 4 if str1[index1] == str2[index2] 5 index1 = index1 + 1 6 index2 = index2 - 1 7 else 8 goto step 10 9 end 10 if (str1[index1] = str1[index2]) 11 return 1

Programming Lab Manual

12 13 Testing: Input : Let String 1 = Fundamentals String 2 = ment

else return 0

Choose one of the operations to be performed Output : 1. StringCopy (string1,string2) String 2 will also consist Fundamentals 2. StringLength (string1 ) Length of string1 i.e 12 will be returned 3. StringCompare ( string1,string2) String 1 is greater than string 2 4. StringReverse ( string1,string2) String2 will consist reverse of string1 i.e. slatnemadnuF 5. StringConcat (string1,string2) String2 will get appended to string1 String2 will have FundamentalsFundamentals 6. SubString (string1,string2) If string1 = Fundamentals and string2 =ment String 2 is the substring of string1. 7. palindrome(string1) if string1 consists Fundamentals The string is not a pallindrome. Conclusion: Thus the String Handling Functions like : 1. StringCopy , 2. StringLength, 3. StringCompare , 4. StringReverse, 5. StringConcat , 6. SubString Palindrome have been implemented (without using standard library routines). Assignment No. 4 Title of Assignment :

Programming Lab Manual

Structure manipulation (for any database like Employee or Bank database) with and without pointers to structures. Relevant Theory / Literature Survey: Theory : Defining a Structure A structure type is usually defined near to the start of a file using a typedef statement. typedef defines and names a new type, allowing its use throughout the program. typedefs usually occur just after the #define and #include statements in a file. Here are examples of structure definition.
1) Without using typedef struct Bankcust { char name[15]; char address[20]; int balance; int acno; }; In this case the variables are declared as follows: struct Bankcust cust; 2) Using typedef to have shorter name while declaring variables: typedef struct { char name[15]; char address[20]; int balance; int acno; } Bankcust;

This defines a new type cust variables of type Bankcust can be declared as follows.

Programming Lab Manual

Bankcust cust;

Notice how similar this is to declaring an int or float. The variable name is cust, it has members called name, address, balance and acno. Accessing Members of a Structure Each member of a structure can be used just like a normal variable, but its name will be a bit longer. To return to the examples above, member name of structure cust will behave just like a normal array of char, however we refer to it by the name
cust.name

Here the dot is an operator which selects a member from a structure. Where we have a pointer to a structure we could dereference the pointer and then use dot as a member selector. This method is a little clumsy to type. Since selecting a member from a structure pointer happens frequently, it has its own operator -> which acts as follows. Assume that st_ptr is a pointer to a structure of type Bankcust We would refer to the name member as
st_ptr -> name Arrays of Structures 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); When you want to refer to a specific structure within an array of structures, index the structure array name. When you want to index a specific element of a structure, index the element. Thus, the following statement assigns X to the first character of name in the 3rd structure of cust. cust[2].name[0]=X;

Programming Lab Manual

Structures as Function Arguments A structure can be passed as a function argument just like any other variable. Where we wish to modify the value of members of the structure, we must pass a pointer to that structure. This is just like passing a pointer to an int type argument whose value we wish to change. struct Bankcust cust; struct Bankcust * c; c=& cust; read_struct(s); /* Call to function read_struct() by passing the structure address*/ void read_struct(struct Bankcust * cust) { printf(Enter the name : ); scanf(%s,cust->name); } If we are only interested in one member of a structure, it is probably simpler to just pass that member. This will make for a simpler function, which is easier to re-use. display(cust.name); /*Passes the name field of structure cust*/ display(cust.name[2]); /* Passes the third character of the name field of structure cust*/ Of course if we wish to change the value of that member, we should pass a pointer to it. search(&cust.acno); When a structure is passed as an argument, each member of the structure is copied. display(cust); void display(struct Bankcust cust)

Programming Lab Manual

Design Analysis / Implementation Logic: (I) Algorithm init_list (struct Bankcust cust[]) Precondition : Accept array of Structures. Postcondition : All acnos are initialized to 0 Return : Nil. 1. 2. 3. 4. (II) for(t=0 to t< MAX) set cust[t].acno=0; End loop End

Algorithm add (struct Bankcust cust[]) Precondition : Accept array of Structures. Postcondition : Add new record to the array. Return : Nil. 1. 2. 3. 4. 5. 6. 7. pos = find_free(cust); if (pos=-1) display list full goto 7 End if Accept details and add in the array at location pos End.

(III) Algorithm find_free (struct Bankcust cust[]) Precondition : Accept array of Structures. Postcondition : Free Location is found in the array. Return : Location of free space if any else -1. 1. 2. 3. 4. 5. 6. 7. 8. for(t=0;t<MAX;t++) if (cust[t].acno==0) goto 7 End loop if (t=MAX) return 1 return t End

(IV) Algorithm delete (struct Bankcust cust[], int acno) Precondition Postcondition : Accept array of Structures and employee id. : Corresponding acno is set to 0

Programming Lab Manual

Return 1. 2. 3. 4. 5. 6. 7. 8. 9. (V)

: Nil

found=search(cust, acno) if (found=-1) display- record not found goto 9 else loc=found modify the contents of record at cust[loc].acno=0 End if End

Algorithm display_list (struct Bankcust cust[]) Precondition : Accept array of Structures Postcondition : All records that exist are displayed Return : Nil 1. 2. 3. 4. 5. 6. for(t=0; t<MAX;t++) if (cust[t].acno not equal to 0 ) display contents of the customer record. End if End loop End

(VI) Algorithm search (struct Bankcust cust[], int ano) Precondition Postcondition Return 1. 2. 3. 4. 5. 6. 7. : Accept array of Structures and account no. : Record with corresponding acno is found and displayed : If record found, return index of the record else return 1

for(t=0; t<MAX;t++) if (cust[t].acno= ano) return t End if End loop return -1 End

(VII) Algorithm modify (struct Bankcust cust[], int ano) Precondition Postcondition : Accept array of Structures and customer ano. : Record with corresponding acno is modified

Programming Lab Manual

Return 1. 2. 3. 4. 5. 6. 7. 8. 9.

: Nil

found=search(cust, ano) if (found=-1) display- record not found goto 9 else loc=found modify the contents of record at cust[loc] End if End

(VIII) Algorithm display_record(struct Bankcust cust[], int ano) Precondition : Accept array of Structures and ano. Postcondition : Record with corresponding acno is displayed Return : Nil 1. 2. 3. 4. 5. 6. 7. 8. 9. Testing: Input : Add records to the Bank database Select Operation to be performed. Output : Perform operations like add, search, modify, delete, display list, display record depending on the operation selected and manipulate the database when required. found=search(cust, ano) if (found=-1) display- record not found goto 9 else loc=found display the contents of record at cust[loc] End if End

Programming Lab Manual

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

Programming Lab Manual

Assignment No. 5 Title of Assignment: Accept student information (e.g. RollNo, Name, Percentage etc.). a. Display the data in descending order of Percentage (Bubble Sort) b. Display data for Rollno specified by user (Linear Search) c. Display the number of passes and comparisons for different test cases (Worst, Average, Best case). Relevant Theory / Literature Survey: Theory: Sorting and searching are among the most common ingredients of programming systems. Sorting is a process of arranging items in some sequence. Efficient sorting is important to optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly. Searching techniques or algorithms are used to speed up the retrieval process. In this assignment we are going to study bubble sort and linear search algorithms. Both of these algorithms are applied on a student database and the results are analyzed for all the three cases (best, average and worst). 1. Bubble Sort: Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is also known as comparison sort. Analysis of Bubble Sort: Bubble sort has best-case complexity (n). When a list is already sorted, bubble sort will pass through the list once, and find that it does not need to swap any elements. Thus bubble sort will make only n comparisons and

Programming Lab Manual

determine that list is completely sorted. It will also use considerably less time than (n) if the elements in the unsorted list are not too far from their sorted places. The worst case complexity is O (n2). Efficiency: For each pass the number of elements scanned for comparisons reduces by 1. Number of comparisons in the first pass =(n-1) Number of comparisons in the Second pass =(n-2) Number of comparisons in the last pass =1 Thus the total number of comparisons at the end of the algorithm would have been (n-1) + (n-2) +(n-3)++2+1= n(n-1)/2 =n2 /2 +O(n) = O(n2) Hence the order of the bubble sort algorithm is O(n2) in worst case. Stability Bubble sort is stable, i.e. the relative order of equal keys is not changed, provided that you are careful about scanning the sorted region from right to left. Pros : Simplicity and ease of implementation. Cons : Inefficient for large number of elements. Design Analysis / Implementation Logic: Algorithm BubbleSort (int A[] ) Precondition Post condition Return : Accept the array which is to be sorted : The array is sorted. : Nil.

procedure bubbleSort( A : list of sortable items ) do swapped := false for each i in 0 to length(A) - 2 inclusive do:

Programming Lab Manual

if A[i] > A[i+1] then swap( A[i], A[i+1] ) swapped := true end if end for
while swapped

end procedure Step-by-step execution: Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared. First Pass: ( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them. ( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass: (14258)(14258) (14258)(12458) (12458)(12458) (12458)(12458) Now, the array is already sorted, but our algorithm does not know if it is completed. Algorithm needs one whole pass without any swap to know it is sorted.

Programming Lab Manual

Third Pass: (12458)(12458) (12458)(12458) (12458)(12458) (12458)(12458) Finally, the array is sorted, and the algorithm can terminate. 2. Linear Search: Linear search is a search algorithm, also known as sequential search, which is suitable for searching a list of data for a particular value. It operates by checking every element of a list one at a time in sequence until a match is found. It is the simplest search algorithm. Analysis of Linear Search: The way in which big O is determined for a particular algorithm is algorithm analysis. Take for example the simple linear search algorithm that we mentioned previously and apply it to the value 3 and the ordered set . Sequentially the algorithm would start from the index of the set, 0, and then look at each next value until it finds the value 3, thus making four comparisons. But what about all of the other infinite number of integers that we could have looked for? Let's try the value 6. The algorithm will first check 6 against 0, 1, 2, 3, 4, and 5 until it halts without finding the value and thus makes six comparisons. From this we can draw that the algorithm will make a number of comparisons equal to the input size, n, and thus is .

Pros : Simplicity and ease of implementation. Cons : Inefficient for large number of elements. Design Analysis / Implementation Logic: Algorithm: Linearsearch(int A[], int x);

Programming Lab Manual

for i:=N:1:-1 do if A[i] = x then QuitLoop i; next i; Return(i); Conclusion: Thus we have studied bubble sort and linear search technique on the student database and analyze the results for best, worst and average cases.

Programming Lab Manual

Assignment No. 6 Title of Assignment: Accept Mobile user information (e.g. MobileNo, Name, BillAmount etc.). a.. Display the data in descending order of MobileNo. (insertion Sort) b. Display the data in ascending order of Name (Selection Sort) c. Display details for Mobileno specified by user (Binary Search) d. Display the number of passes and comparisons for different test cases (Worst, Average, Best case). Relevant Theory / Literature Survey: Theory: In this assignment we are going to study insertion sort, selection sort and binary search algorithms. All of these algorithms are applied on a mobile user database and the results are analyzed for all the three cases (best, average and worst). 1. Insertion Sort: Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time. The insertion sort works just like its name suggests - it inserts each item into its proper place in the final list. The simplest implementation of this requires two list structures - the source list and the list into which sorted items are inserted. To save memory, most implementations use an in-place sort that works by moving the current item past the already sorted items and repeatedly swapping it with the preceding item until it is in place. The idea of the insertion sort algorithm is like holding cards in one hand, and for each unsorted card, finds where it belongs in the sorted cards, and inserts it.

Programming Lab Manual

Analysis of Insertion Sort: The best case input is an array that is already sorted. In this case insertion sort has a linear running time (i.e., O(n)). During each iteration, the first remaining element of the input is only compared with the right-most element of the sorted subsection of the array. The worst case input is an array sorted in reverse order. In this case every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next element. For this case insertion sort has a quadratic running time (i.e., O(n2)). The average case is also quadratic, which makes insertion sort impractical for sorting large arrays. However, insertion sort is one of the fastest algorithms for sorting arrays containing fewer than ten elements. Stability Insertion sort is stable, i.e. the relative order of equal keys is not changed, provided that you are careful about scanning the sorted region from right to left. Pros : Cons : Relatively simple and easy to implement.

Inefficient for large lists.

Design Analysis / Implementation Logic: Algorithm: insertionSort(array A) begin for i := 1 to length[A]-1 do begin

Programming Lab Manual

value := A[i]; j := i-1; while j >= 0 and A[j] > value do begin A[j + 1] := A[j]; j := j-1; end; A[j+1] := value; end; end;

Step-by-step execution: Array to be sorted Array A= {20,10,8,6,4,2,1} Pass 1 2 3 4 5 6 2. Selection Sort: Selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. The selection sort has a complexity of O(n2). Analysis of Selection Sort: Selection sort is not difficult to analyze compared to other sorting algorithms since none of the loops depend on the data in the array. Selecting the lowest 10 8 6 4 2 1 Elements 20 8 6 4 2 10 20 6 4 2 8 10 20 4 2 6 8 10 20 2 4 6 8 10 20 2 4 6 8 10 1 1 1 1 1 20

Programming Lab Manual

element requires scanning all n elements (this takes n 1 comparisons) and then swapping it into the first position. Finding the next lowest element requires scanning the remaining n 1 elements and so on, for (n 1) + (n 2) + ... + 2 + 1 = n(n 1) / 2 (n2) comparisons. Each of these scans requires one swap for n 1 elements (the final element is already in place).

Efficiency: Number of comparisons in the first pass =(n-1) Number of comparisons in the Second pass =(n-2) Number of comparisons in the last pass =1 Thus the total number of comparisons at the end of the algorithm would have been (n-1) + (n-2) +(n-3)++2+1= n(n-1)/2 =n2 /2 +O(n) = O(n2) Hence the order of the Selection sort algorithm is O(n2) in worst case. Stability Selection sort is stable, i.e. the relative order of equal keys is not changed, provided that you are careful about scanning the sorted region from right to left. Pros : Cons : Simple and easy to Inefficient for large lists implement.

Design Analysis / Implementation Logic: Algorithm:


void selectionSort(int[] a) { for (int i = 0; i < a.length - 1; i++) { int min = i; for (int j = i + 1; j < a.length; j++) {

Programming Lab Manual

if (a[j] < a[min]) { min = j; } } if (i != min) { int swap = a[i]; a[i] = a[min]; a[min] = swap; } } }

Step-by-step execution: Let the array A{64,25,12,22,11} to be sorted.

Pass 1:

64 25 12 22 11

Pass 2:

11 25 12 22 64

Pass 3: 3. Binary Search:

11 12 22 25 64

A binary search algorithm (or binary chop) is a technique for finding a particular value in a sorted list. A binary search finds the median element in a list, compares its value to the one you are searching for, and determines if its greater than, less than, or equal to the one you want. A guess that turns out to be too high becomes the new top of the list, and one too low the new bottom of

Programming Lab Manual

the list. The binary search's next guess is halfway between the new list's top and bottom The binary search begins by comparing the sought value X to the value in the middle of the list; because the values are sorted, it is clear whether the sought value would belong before or after that middle value, and the search then continues through the correct half in the same way. Analysis of Binary Search: The binary search algorithm is more efficient than the previously mentioned linear search algorithm, but harder to analyze. Let's take the same set as we did last time . This time we will

search for the value 1. The binary search algorithm divided the set into two equally-sized set, or almost equally-sized if the set has an odd number of elements, and by looking to the left of the centre (even sized), or the centre value (odd sized) determined which set to look further into. So, in our case, the binary search algorithm divides the set into the subsets and

. The centre of set S was between the end of S1 and S2, so we have to compare our value to the end of S1, 2. 1 < 2, so if 1 exists in our ordered set S it must be contained in S1. We then compare one to the centre of S1 and get that it is equal to it, and therefore exists in S. That was only two comparisons, but what if we again take and search for a value which does not exists in S, 6? We would compare to 2, and then to 4, and finally to 5, without successfully finding 6. This would give us a total of 3 comparisons.The pattern that is shown here is that the greatest number of comparisons for a particular input is equal to , or the greatest integer

function of the binary logarithm of the input size. Generalized for very large input sizes, and assuming that search algorithm is . refers to , we get that the binary

Programming Lab Manual

Applications:
1. Searching Telephone number of a particular person in Telephone book. 2. Finding information of a particular student in a large Student Database. 3. Simple Number Guessing game. Design Analysis / Implementation Logic: Algorithm: Precondition : Accept the value and the array in which it is to be searched. Post condition : The value is either found or not. Return : Index of the element if found else return 1.

BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else

Programming Lab Manual

return mid } return not_found } Conclusion: Thus we have studied the insertion sort, selection sort and binary search algorithms on the mobile user database and analyze the results for best, average and worst cases.

Programming Lab Manual

Assignment No. 07 Title of Assignment: Implement Quick Sort recursively of the following set of numbers such as 56, - 90, 80, 78, 234, 654, 432, 12, 0, -11

Relevant Theory / Literature Survey: Theory: 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 so that 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 than p

numbers greater than or equal to p

Efficiency/Complexity:

Programming Lab Manual

The worst-case performance of Quicksort is (n2). The best cases are when the array is split half and half.The best case running time is (nlogn)

The average case performance of QuickSort is (nlogn).


Design Analysis / Implementation Logic: To sort the subarray A[p . . r]: Divide: Partition A[p . . r], into two subarrays A[p . . q 1] and A[q + 1 . . r], such that each element in the first subarray A[p . . q 1] is _ A[q] and A[q] is _ each element in the second subarray A[q + 1 . . r]. Conquer: Sort the two subarrays by recursive calls to Quicksort. Combine: No work is needed to combine the subarrays, because they are sorted in place. Perform the divide step by a procedure Partition, which returns the index j that marks the position separating the subarrays. [I] Algorithm QuickSort(int a[], int p, int q, int n) Precondition : Accept the Array to be sorted Postcondition : Sorted array Return : Nil 1. int pass=0; 2. if(p<q) 3. j=partition(a,p,q); 4. pass++; 5. QuickSort(a,p,j-1,n); 6. QuickSort(a,j+1,q,n); 7. End if [II] Algorithm Partition(int a[], int p, int q) 1. 2. 3. 4. 5. 6. 7. 8. 9. v=a[p]; i=p; j=q+1; do { do { i++; }while(a[i]<v && i<=q);

Programming Lab Manual

10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23.

do { j--; }while(a[j]>v); if(i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } }while(i<j); a[p]=a[j]; a[j]=v; return(j);

Testing: Input : ENTER THE NO. OF ELEMENTS 10 ENTER ARRAY ELEMENTS 56 -90 12 632 457 1000 -1 8 34 0

ENTERED ARRAY IS 56 -90 12 632 0 QuickSort Pivot PASS 1 PIVOT 56 -1 -90 12 632 PASS 2 PIVOT -1 -90 -1 12 632 PASS 3 PIVOT 12 -90 -1 8 632

457

1000

-1

34

and PASSes : 0 0 0 34 34 12 8 8 34 56 56 56 1000 1000 1000 457 457 457

Programming Lab Manual

PASS 4 PIVOT 8 -90 -1 0 8 632 PASS 5 PIVOT 1000 -90 -1 0 8 1000 PASS 6 PIVOT 632 -90 -1 0 8 1000 SORTED ARRAY IS : -90 -1 0 8 1000 Output : SORTED ARRAY IS : -90 -1 0 8 1000

12 12 12 12

34 34 34 34

56 56 56 56

1000 632 457 457

457 457 632 632

12

34

56

457

632

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

Programming Lab Manual

Assignment No. 08 Title of Assignment: Representation Sparse matrix using array and perform matrix addition, simple and fast transpose. Relevant Theory / Literature Survey: Theory: Matrices are represented using 2-dimensional array. Array with m rows and n cols has order of m x n. Space requirement is m x n x s, where s is space required in bytes. Time complexity is O(n2), because the operations that are carried out on matrices need to scan the matrices one row at a time and accessing individual columns in that row results in use of two nested loops Sparse Matrix : Sparse Matrix is that matrix which has a very few non-zero elements as compared to the size m x n of the matrix. For example: If in Matrix of size 100x100, there are only 10 non-zero elements then for accessing these elements we have to scan the matrix 10,000 times. Also the space required will be 100x100x2 = 20,000 bytes. So the concept of Sparse matrix requires space only to store non-zero elements of the matrix and still carry out the operations quite efficiently. Representation of Sparse matrix: Representation of Sparse matrix will be a triplet only. In the sense we will consider only non-zero values along with their positions. In a rowwise representation of sparse matrix 0th row will store total rows ,total columns and total number of non-zero values in the matrix. e.g. Index Row No. Col No. Value 0 6 7 8 1 0 6 -10 2 1 0 55 3 2 5 -23 4 3 1 67 5 3 6 88 6 4 3 14 7 4 4 -28 8 5 0 99 In Normal matrix representation 6x7x2 = 84 bytes are required for storage.

Programming Lab Manual

In Sparse matrix (Triplet) representation (8+1)x3x2 = 54 bytes are required for storage. Matrix A

Index Row No. Col No. Value 0 6 7 8 1 0 6 -10 2 1 0 55 3 2 5 -23 4 3 1 67 Analysis of Simple and Fast Transpose: Fast Transpose is really a fast algorithm as compared to Simple Transpose. For transposing the elements we need two nested for loops in case of Simple transpose. Where as in case of Fast Transpose in a single for loop we are adjusting jth position with the help of rpos array. And thus we save extra time required for the nested loop. And so the time complexity of Simple Transpose is O(n*m) O(n2) The Time complexity of Fast Transpose is O(n)+O(n)+O(m) Where n is total non-zero values and m is total number of columns. So ultimately it is O(n) Design Analysis / Implementation Logic: Algorithms: #define SIZE 50 Struct Sparse{ int row, int col,int val}; Sparse A[SIZE+1], B[SIZE+1], C[SIZE+1] [I] Algorithm Create (sparse S[]) Precondition : Accept the matrix to be created Postcondition : Sparse matrix is created Return : Nil 1. 2. 3. 4. 5. 6. Accept number of rows, columns of a matrix Accept the no. of non-zero terms If no. of terms greater than the size of the matrix display error S[0].row=m, S[0].col=n, S[0].val=terms for( i=1 to i<=terms) Accept (row, col,val)

Programming Lab Manual

7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17.

if (row>m) Display error message exit(0) End if if (col>n) Display error message exit(0) End if S[i].row=row S[i].col=col, S[i].val=val End for End

[II] Algorithm Add (sparse S1[],sparse S2[],sparse S3[]) 1. Accept first matrix A 2. Accept Second matrix B 3. if(A[0].row!=B[0].row && A[0].col!=B[0].col) 4. { 5. Addition not possible........ 6. return; 7. } 8. else 9. { 10. if(A[0].row==B[0].row && A[0].col==B[0].col) 11. { 12. C[0].row=A[0].row; 13. C[0].col=A[0].col; 14. } 15. else 16. { 17. if(A[0].row==B[0].row) 18. { 19. C[0].row=A[0].row; 20. if(A[0].col<B[0].col) 21. { 22. C[0].col=B[0].col; 23. } 24. else 25. { 26. C[0].col=A[0].col; 27. } 28. } 29. if(A[0].col==B[0].col) 30. { 31. C[0].col=A[0].col; 32. if(A[0].row<B[0].row) 33. {

Programming Lab Manual

34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79.

C[0].row=B[0].row; } else { C[0].row=A[0].row; } } } i=1;j=1;k=1; while(i<=A[0].val && j<=B[0].val) { if(A[i].row==B[j].row && A[i].col==B[j].col) { C[k].row=A[i].row; C[k].col=A[i].col; C[k].val=A[i].val + B[j].val; i++;j++;k++; } else { if(A[i].row==B[j].row) { if(A[i].col<B[j].col) { C[k].row=A[i].row ; C[k].col=A[i].col ; C[k].val=A[i].val; i++;k++; } else { C[k].row=B[j].row; C[k].col=B[j].col ; C[k].val=B[j].val ; j++;k++; } } else { if(A[i].row<B[j].row) { C[k].row=A[i].row; C[k].col=A[i].col; C[k].val=A[i].val; i++;k++ ; }

Programming Lab Manual

80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113.

else { C[k].row=B[j].row; C[k].col=B[j].col ; C[k].val=B[j].val ; j++;k++; } } } while(i<=A[0].val) { C[k].row=A[i].row; C[k].col=A[i].col ; C[k].val=A[i].val ; i++;k++ ; } while(j<=B[0].val) { C[k].row=B[j].row ; C[k].col=B[j]. col ; C[k].val=B[j]. val; j++; k++; } } C[0].val=k-1; } printf("Addition of the two matrices is: \n"); printf("\nArray A :\n"); write_array(A); printf("\nArray B :\n"); write_array(B); printf("\nArray C :\n"); write_array(C); }

[II] Algorithm Simple_Transpose(sparse S1[]) 1. S2[0].row=S1[0].col; 2. S2[0].col=S1[0].row;

Programming Lab Manual

3. S2[0].val=S1[0].val; 4. if(n>0) 5. k=1 6. for (col=0 to col< S1[0].col) 7. for(term=1 to term<= S1[0].val) 8. if(S1[term].col==col) 9. S2[k].row=S1[term].col 10. S2[k].col = S1[term]. row 11. S2[k].val =S1[term].val 12. K++ 13. End if 14. End for 15. End for 16. End [III] Algorithm Fast_Transpose(sparse S1[],sparse S2[]) 1. int rterm[MAX], rpos[MAX] 2. row=S1[0].row, col=S1[0].col, term= S1.val 3. S2[0].row=col,S2[0].col=row , S2.val=term 4. if(term>0) 5. for (i=0 to i<col) 6. rterm[i]=0; 7. End for 8. for (i=1 to i<=term) 9. rterm[S1[i].col]++ /*elements in row S2*/ 10. End for 11. rpos[0]=1 /*Setting rowwise position*/ 12. for (i=1 to i<col) /*Starting position of row I in S2*/ 13. rpos[i]=rpos[i-1]+rterm[(i-1)] 14. End for 15. for (i=1 to i<=term) 16. j=rpos[S1[i].col]; 17. S2[j].row=S1[i].col 18. S2[j].col = S1[i]. Row 19. S2[j].val =S1[i].val 20. rpos[S1[i].col]=j+1 /*increase row j to next spot*/ 21. End for 22. End if 23. End [IV] Algorithm write_array(sparse A[SIZE]) 1. printf("\nIndex\tRow\tCol\tValue\n"); 2. for( i=0;i<=A[0].val;i++) 3. printf("\n%d\t%d\t%d\t%d",i,A[i].row,A[i].col,A[i].val);

Programming Lab Manual

4. End for 5. End Testing: Input : Addition : Matrix A

Index Row No. Col No. Value 0 2 3 2 1 0 1 5 2 1 2 6 Matrix B Index Row No. Col No. Value 0 4 3 4 1 0 1 8 2 1 2 5 3 2 1 6 4 3 1 7

Output : Matrix C Index Row No. Col No. Value 0 4 3 4 1 0 1 13 2 1 2 11 3 2 1 6 4 3 1 7 Conclusion: Thus we have represented Sparse matrix using array and performed matrix addition, simple and fast transpose

Programming Lab Manual

Assignment No. 9
Title of Assignment : Create a singly linked list with options: a) Insert (at front, at end, in the middle) b) Delete (at front, at end, in the middle) c) Display d) Display Reverse e) Revert the SLL. Relevant Theory / Literature Survey: In computer science, a linked list is data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence.

A linked list whose nodes contain two fields: an integer value and a link to the next node

Linked lists are among the simplest and most common data structures, and are used to implement many important abstract data structures, such as stacks, queues, hash tables, symbolic expressions, skip lists, and many more. The principal benefit of a linked list over a conventional array is that the order of the linked items may be different from the order that the data items are stored in memory or on disk. For that reason, linked lists allow insertion and removal of nodes at any point in the list, with a constant number of operations. On the other hand, linked lists by themselves do not allow random access to the data, or any form of efficient indexing. Thus, many basic operations such as obtaining the last node of the list, or finding a node that contains a given data, or locating the place where a new

Programming Lab Manual

node should be inserted may require scanning most of the list elements.

Singly-linked list
Linked list is a very important dynamic data structure. Basically, there are two types of linked list, singly-linked list and doubly-linked list. In a singly-linked list every element contains some data and a link to the next element, which allows to keep the structure. On the other hand, every node in a doubly-linked list also contains a link to the previous node. Linked list can be an underlying data structure to implement stack, queue or sorted list.

Example
Sketchy, singly-linked list can be shown like this:

Each cell is called a node of a singly-linked list. First node is called head and it's a dedicated node. By knowing it, we can access every other node in the list. Sometimes, last node, called tail, is also stored in order to speed up add operation .

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

Programming Lab Manual

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:

Programming Lab Manual

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.

Programming Lab Manual

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.

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

Programming Lab Manual

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.

Programming Lab Manual

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.

Programming Lab Manual

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

Programming Lab Manual

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.

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.

Programming Lab Manual

2. Dispose removed node.

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.

Programming Lab Manual

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.

Programming Lab Manual

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.

Programming Lab Manual

2. Dispose removed node.

Design Analysis / Implementation Logic: Pseudo code How to Define Node: A node will have data assigned to it and a pointer to its successor. Newnode is the name of the node.

New node pointer

Programming Lab Manual

Next

Data New node New node structure

struct LinkedList { int data; struct LinkedList * next;//*next is a pointer to next node this type of definition }; typedef node 1) Insert operation: void insert(nodeptr *head) // insert in list pointed by head { nodeptr *temp,*prev; int val,x,ch; if(list_crt==0) { printf("LIST NOT CREATED"); return; } printf("Enter data to be inserted"); // is called self referential structure. struct LinkedList node;//we will be able to use short name

Programming Lab Manual

scanf("%d",&val); // allocate new node temp=(nodeptr *) malloc(sizeof(nodeptr)); temp->data=val; temp->link=NULL; printf("where u want to insert ? \n"); printf("1.At Front \n2.At End \n3.In Middle \n"); scanf("%d",&ch); switch(ch) { case 1: temp->link = head->link; head->link = temp; break; case 2: prev = head; while (prev->link !=NULL) // go to end of list { prev = prev->link; } prev->link=temp; break; case 3: printf("Enter the data of node after which to be inserted"); scanf("%d",&x); prev = head->link; while (prev->link !=NULL && prev->data != x) { prev = prev->link; } //assign at end

Programming Lab Manual

temp->link=prev->link; prev->link=temp; break; default : printf("Invalid Choice"); } // switch } // insert } 2) Delete operation: void delete(nodeptr *head) { nodeptr *temp,*prev,*curr; int ch,x; if(list_crt==0) { printf("LIST NOT CREATED"); return; } if(head->link==NULL) printf("List is EMPTY.\n"); else { printf("which u want to delete ? \n"); printf("1.At Front \n2.At End \n3.In Middle \n"); scanf("%d",&ch); switch(ch) { case 1: temp = head->link; head->link = head->link->link; free(temp);

Programming Lab Manual

break; case 2: prev = head; while (prev->link->link !=NULL) // go to second last { prev = prev->link; } temp=prev->link; prev->link=NULL; free(temp); break; case 3: printf("Enter the data of node to be deleted"); scanf("%d",&x); prev = head; curr=head->link; while (curr->link !=NULL && curr->data != x) { prev=curr; curr = curr->link; } if(curr->data == x) { temp=curr; prev->link=temp->link; free(temp); } else printf("Node with given data does not exist:"); break; default : printf("Invalid Choice");

Programming Lab Manual

} // switch } // else } //delete

3) Display: void DisplayList (node *front) { node * cur; cur = front;//cur is the node for traversal if (!cur) printf(\n the list is empty\n); else { printf(\n the list is ---\n0; While (cur) { Printf(%d,cur->data); if (cur->next);//next node exits printf(->); cur =cur->next;// go to next node } } }//end of Display List 4) Reverse List:

Programming Lab Manual

void ReverseList (node ** front) { node *cur,*prev,*temp;//declare three pointers cur=*front; prev=NULL; while (cur!=NULL) { temp=prev; prev=cur; cur=cur->next; prev->next=temp; } *front=prev; } 5) Revert the SLL: void rev_sll(nodeptr *head) { // create temporary reverse list nodeptr *middle,*back,*next; if(list_crt==0) { printf("LIST NOT CREATED"); return; } middle=head->link; next=middle->link; back=NULL; while(middle->link!=NULL) {

Programming Lab Manual

middle->link=back; back=middle; middle=next; next=next->link; } middle->link=back; head->link=middle; Testing: Input and Output: Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 1 Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 2

Programming Lab Manual

The list is: EMPTY Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 3 Enter data to be inserted 10 where u want to insert? 1.At Front 2.At End 3.In Middle Enter your choice: 1 Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 2 The list is: 10 Menu:

Programming Lab Manual

1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 3 Enter data to be inserted 30 where u want to insert ? 1.At Front 2.At End 3.In Middle Enter your choice: 2 The list is : 10 Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 3 Enter data to be inserted 20 where u want to insert ? 30

Programming Lab Manual

1.At Front 2.At End 3.In Middle Enter your choice: 3 Enter the data of node after which to be inserted 10 Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 2 The list is :10 Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 5 The list is: 30 Menu: 1.Create 20 10 20 30

Programming Lab Manual

2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 5 The list is: 10 Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 6 Menu: 1.Create 2.Display 3.Insert 4.Delete 5.display reverse 6.Reverse sll 7.Exit Enter your choice: 2 The list is: 10 20 30 20 30

Programming Lab Manual

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

Programming Lab Manual

Assignment No. 10
Title of Assignment : Accept input as a string and construct a Doubly Linked List for the input string with each node contains, as a data one character from the string and perform : a) Insert b) Delete c) Display forward d) Display backward. Relevant Theory / Literature Survey: 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 xorlinking), and their elementary operations are more expensive; but they are often easier to manipulate because they allow sequential access to the list in both directions. In particular, one can insert or delete a node in a

Programming Lab Manual

constant number of operations given only that node's address. Design Analysis / Implementation Logic: Pseudo code a) Insert: void insert(nodeptr *head) // insert in list pointed by head { nodeptr *temp,*prev; int ch; char x,val; if(list_crt==0) { printf("LIST NOT CREATED"); return; } printf("Enter data to be inserted"); scanf("%c",&val); scanf("%c",&val); // allocate new node temp=(nodeptr *) malloc(sizeof(nodeptr)); temp->data=(char) val; temp->rlink=NULL; temp->llink=NULL; printf("where u want to insert ? \n"); printf("1.At Front \n2.At End \n3.In Middle \n"); scanf("%d",&ch); switch(ch)

Programming Lab Manual

{ case 1: temp->rlink = head->rlink; head->rlink->llink = temp; temp->llink=head; head->rlink = temp; break; case 2: prev = head; while (prev->rlink !=NULL) // go to end of list { prev = prev->rlink; } prev->rlink=temp; temp->llink=prev; break; case 3: printf("Enter the data of node after which to be inserted"); scanf("%c",&x); prev = head->rlink; while (prev->rlink !=NULL && prev->data != x) { prev = prev->rlink; } temp->rlink=prev->rlink; prev->rlink->llink = temp; temp->llink = prev; prev->rlink = temp; break; default : printf("Invalid Choice"); } // switch

Programming Lab Manual

} // insert b) Delete: void delete(nodeptr *head) { nodeptr *temp,*prev; int ch; char x; if(list_crt==0) { printf("LIST NOT CREATED"); return; } if(head->rlink == NULL) printf("List is EMPTY.\n"); else { printf("which u want to delete ? \n"); printf("1.At Front \n2.At End \n3.In Middle \n"); scanf("%d",&ch); switch(ch) { case 1: temp = head->rlink; head->rlink = temp->rlink; temp->rlink->llink = head; free(temp); break; case 2: prev = head; while (prev->rlink != NULL) // go to second last {

Programming Lab Manual

prev = prev->rlink; } temp=prev; prev->llink->rlink = NULL; free(temp); break; case 3: printf("Enter the data of node to be deleted"); scanf("%c",&x); scanf("%c",&x); prev = head->rlink; while (prev->rlink !=NULL && prev->data != x) { prev = prev->rlink; } if(prev->data == x) { temp=prev; prev->rlink->llink = prev->llink; prev->llink->rlink = prev->rlink; free(temp); } else printf("Node with given data does not exist:"); break; default : printf("Invalid Choice"); } // switch } // else } //delete

Programming Lab Manual

c) Display forward: void disp_forwrd(nodeptr *head) { nodeptr *temp; if(list_crt==0) { printf("LIST NOT CREATED"); return; } temp=head->rlink; printf("The list is: "); if(temp==NULL) printf("EMPTY"); else while (temp !=NULL) { printf("%c\t",temp->data); temp = temp->rlink; } } //disp_frwrd d) Display backward: void disp_backwrd(nodeptr *head) { nodeptr *temp; if(list_crt==0) { printf("LIST NOT CREATED"); return;

Programming Lab Manual

} temp=head->rlink; printf("The list is: "); if(temp==NULL) printf("EMPTY"); else { while (temp->rlink !=NULL) { // printf("%d\t",temp->data); temp = temp->rlink; } while (temp!=head) { printf("%c\t",temp->data); temp = temp->llink; } } } //disp_backwrd Testing: Input and Output: Menu: 1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit

Programming Lab Manual

Enter your choice: 1 enter the string omsai Menu: 1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 2 The list is o m s a i Menu: 1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 3 s where u want to insert ? 1.At Front 2.At End 3.In Middle Enter your choice: 1 The list is: s o m s a i Menu:

Programming Lab Manual

1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 3 a where u want to insert ? 1.At Front 2.At End 3.In Middle Enter your choice: 2 The list is s o m s a i a Menu: 1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 3 t where u want to insert ? 1.At Front 2.At End 3.In Middle Enter your choice:

Programming Lab Manual

3 Enter the data of node after which to be inserted m The list is: s o m t s a i a Menu: 1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 4 which u want to delete ? 1.At Front 2.At End 3.In Middle Enter your choice: 1 The list is: o m t s a i a Menu: 1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 4

Programming Lab Manual

which u want to delete ? 1.At Front 2.At End 3.In Middle Enter your choice: 2 The list is:o m t s a i Menu: 1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 4 which u want to delete ? 1.At Front 2.At End 3.In Middle Enter your choice: 3 Enter the data to be deleted t The list is: o m s a i

Menu:

Programming Lab Manual

1.Create 2.Display Forward 3.Insert 4.Delete 5.display Backward 6.Exit Enter your choice: 5 The list is: i a s m o Conclusion: Thus we have learnt how to create doubly linked list and we have also implemented the following operations on the doubly linked list : Accept input as a string and construct a Doubly Linked List for the input string with each node contains, as a data one character from the string and perform: a) Insert b) Delete c) Display forward d) Display backward.

You might also like