74
Subject: Programming Laboratory Work Load Exam Schemes Theory Practical Term Work Practical Oral 02hrs per week 04hrs per week 25 50 -- List of Assignments Sr. No. Title of Assignment Time Span (No. of weeks) 1 Write a program to perform various string operations such as copy, length, reverse, palindrome, concatenation and to find occurrence of a substring using and without using library functions 01 2 Write a program to perform addition and multiplication and transpose operations on matrix. Write functions to determine whether the matrix is symmetric and skewed symmetric. 01 3 Represent a polynomial using array and write a menu driven program to perform addition, multiplication and evaluation. ½ 4 Write a program to perform various operations such as union and intersection on sets. ½ 5 Write a program to compute Inverse of a matrix 01 6 Write a program to implement stack as an ADT using Arrays. ½ 7 Write a program to convert the given Infix expression to Postfix and perform evaluation. 01 8 Write a program to convert the given Infix expression to Prefix and Prefix to Infix. 01 9 Write a program to convert the given Postfix expression to Infix and Postfix to Prefix. ½ 10 Write a program to implement bitwise and logical bitwise operators using stack. 01

Programming Laboratory Lab_manual

Embed Size (px)

Citation preview

Page 1: Programming Laboratory Lab_manual

Subject: Programming LaboratoryWork Load Exam Schemes

Theory Practical Term Work Practical Oral

02hrs per week 04hrs per week 25 50 --

List of Assignments

Sr. No. Title of AssignmentTime Span

(No. of weeks)

1

Write a program to perform various string operations such as copy, length, reverse, palindrome,

concatenation and to find occurrence of a substring using and without using library functions

01

2

Write a program to perform addition and multiplication and transpose operations on matrix. Write functions to determine whether the matrix is symmetric and skewed symmetric.

01

3Represent a polynomial using array and write a menu driven program to perform addition, multiplication and evaluation.

½

4Write a program to perform various operations such as union and intersection on sets.

½

5 Write a program to compute Inverse of a matrix 01

6Write a program to implement stack as an ADT using Arrays.

½

7Write a program to convert the given Infix expression to Postfix and perform evaluation.

01

8Write a program to convert the given Infix expression to Prefix and Prefix to Infix.

01

9Write a program to convert the given Postfix expression to Infix and Postfix to Prefix.

½

10Write a program to implement bitwise and logical bitwise operators using stack.

01

11Write a program to implement circular queue and double-ended queue using arrays.

01

12Write a program to implement Sequential and Binary search.

½

13.Write a program to implement following sorting methods: Bubble sort, Selection Sort and Insertion Sort.

01

14.Write a program to solve the system of Simultaneous Equations using Cramers Rule, Gauss Seidal Rule and Gauss Elimination Method.

01

15.Write a program to create a text file, read it and convert into uppercase & write the contents into another text file by using command line arguments

01

Page 2: Programming Laboratory Lab_manual

16.

Write a program to implement a small database project to understand the concept of structures, pointers, various operations on files such as create, open, add/ modify/delete/process/append a record, search a record, sort, merge, close.

02

Assignment No. 01

Title of Assignment: Write a program to perform various string operations such as copy,

length, reverse, palindrome, concatenation and to find occurrence of a substring using

and without using library functions.

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

Page 3: Programming Laboratory Lab_manual

msg[5] = '\0';

String is stored and retrieved starting from Index 0 onwards.string constants, such as "Hello" are automatically terminated by NULL by the compiler.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithms :(I)Algorithm StringCopy ( ref str <char[]> )

This algorithm reads a Source String character by character and copies it to the destination String.

Pre :- Source string should be accepted Post :- Same data should be present in destination String.Return :- reference to Copied String

1 accept the source string2 initialize index of both strings to start (0)3 loop ( not end of source string )

4 read a character from source string 5 write to destination string 6 index = index + 1 7 end loop 4 terminate destination string by ‘\0’ character 5 return reference to destination string

(II) Algorithm StringLength ( ref str <char[]> )

This algorithm reads a Source String character by character and counts characters till end of the string and returns length of the String.

Pre :- String should be acceptedPost :- Length of the String should be calculated.Return :- Length of the String.

1 accept the string2 initialize index to start (0)3 loop ( not end of string )

4 index = index + 1 5 return index

(III) Algorithm StringCompare ( ref str1<char[]>,ref str2<char[]>)

Page 4: Programming Laboratory Lab_manual

This algorithm reads both the Strings character by character and compares characters till end of the string and returns length of the String.

Pre :- Both the Strings should be acceptedPost :- Equality of the Strings should be checked.Return :- Result of comparison (1/0)

1 Calculate length of both the strings (n1 & n2) 2 if ( n1 != n2 )3 return 04 else 5 index = 06 loop( not end of str1) 7 if str1(index) == str2(index)8 index = index + 19 else 10 return 011 end loop12 end if13 return 1

(IV) Algorithm StringConcat ( ref str1<char[]>,ref str2<char[]>)

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 :- Both the Strings should be acceptedPost :- Source String should be appended at the end of destination stringReturn :- reference to destination String

1 index = 02 loop ( not end of the str1)3 index = index + 14 end loop5 index1 = 06 loop ( not end of str2 )7 str1(index) = str2(index1) 8 index = index +19 index1 = index1 + 110 end loop 11 terminate destination string(str1) by ‘\0’ character12 return reference to destination string(str1)

(V) Algorithm StringReverse ( ref str1<char[]>,ref str2<char[]>)

This algorithm reads the source string character by character and appends each

Page 5: Programming Laboratory Lab_manual

character at the end of the destination string and returns the reference to the destination String.

Pre :- the source String should be acceptedPost :- Reverse of the Source String should be present in destination String.Return :- reference to destination String

1 index = 02 loop ( not end of the str1)3 index = index + 14 end loop5 index1 = 06 loop ( not end of str2 )7 str2(index1) = str1(index) 8 index1 = index1+19 index = index - 110 end loop 11 terminate destination string(str2) by ‘\0’ character12 return reference to destination string(str2)

(VI) Algorithm SubString ( ref str1<char[]>,ref str2<char[]>)

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 :- Both the Strings should be acceptedPost :- Check for occurrence of string2 in string1.Return :- Boolean value as a result of comparison (1/0)

1 index1 = 02 index2 = 03 loop( not end of str1) 4 index2 = 0 5 loop (not end of str2)6 if str1(index1) == str2(index2)7 index1 = index1 + 18 index2 = index2 + 1 9 else10 goto step 1211 end loop12 if (end of str2(index2) )13 flag =114 goto step 1915 else16 index1 = index1 + 117 endif18 end loop19 if flag =1

Page 6: Programming Laboratory Lab_manual

20 return 121 else22 return 0

(VI) Algorithm Palindrome ( ref str1<char[]>)

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 :- Source String should be acceptedPost :- Result as palindrome or not a palindrome .Return :- Boolean value as a result (1/0)

1 index1 = 02 index2 = strlen(str1)3 loop( index1 is not equal to index2) 4 if str1(index1) == str2(index2)5 index1 = index1 + 16 index2 = index2 - 1 7 else8 goto step 109 end loop10 if (index1 =index2 )11 return 112 else13 return 0

Testing:

Input : Character string is accepted for every operation.

Output : Results are obtained in the form of either destination string or status of operation

i.e. true or false. Program is working for different input strings and outputs are matching

the standard results.

Conclusion : All the string operations have been tested and executed successfully.

Page 7: Programming Laboratory Lab_manual

Assignment No. 02

Title of Assignment: Write a program to perform addition and multiplication and transpose

operations on matrix. Write functions to determine whether the matrix is symmetric and skewed

symmetric.

Theory :

Matrix : A matrix is a rectangular table of numbers or, more generally, a table consisting of abstract quantities. Matrices can be added, multiplied, and decomposed in various ways, marking them as a key concept in linear algebra and matrix theory.For example, A matrix can be stored using double dimension arrayEg. Mat[2][2] will represent the matrix of dimension 2X2. Accept the number of rows and columns. Using loop, values are stored on the respective locations.Example : A 4*4 matrix can be given as

The vector space of all matrices with real elements will be denoted by and

The element of the matrix A that stands in the i-th row and k-th column will be denoted by aik or A(i,k) or [A]ik. The main operations with matrices are following:

transposition of matrices

addition of matrices

multiplication of matrices by a number

multiplication of matrices

Symmetric matrix : A matrix is called symmetric if AT=A and skew-symmetric if AT=-A

Page 8: Programming Laboratory Lab_manual

Examples :

Symmetric Skew-symmetric Skew-symmetric

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithms and Requirement :Algorithm main: Display menu

1. Addition of Matrix2. Multiply two matrices3. Symmetric Matrix 4. Skew Symmetric 5. Transpose of a matrix6. Exit

(I) Algorithm accept (ref m<int [][]>)Pre :- NilPost :- Matrix should be acceptedReturn :- Nil

1. Accept the rows of the matrix in r2. Accept the columns of matrix in c3. Enter the matrix elements4. for ( i=0;i<r;i++)5. for (j=0;j<c;j++)6. accept element at m1[i][j] as no7. end8. end

(II) Algorithm addition(ref m1<int [][]>, ref m2<int[][]>, ref m3<int[][]>)

Pre :- Two matrices should be accepted.Post :- Result of addition of two matricesReturn :- 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

Page 9: Programming Laboratory Lab_manual

6. end 7. else8. Display Addition not possible9. endif

(III) Algorithm multiplication (ref m1<int [][]>, ref m2<int[][]>, ref m3<int[][]>)

Pre :- Two matrices should be accepted.Post :- Result of multiplication of two matricesReturn :- Nil

1. if( c2==r2)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 loop7. end loop8. end loop9. else10. display Multiplication cannot be performed

(IV) Algorithm display (ref m<int [][]>)

Pre :- Matrix should be accepted.Post :- display the matirxReturn :- Nil

1. for (i=0;i<r1;i++)2. for(j=0;j<c1;j++)3. display matrix[i][j]4. end 5. end

(IV) Algorithm Symmetric (ref m1<int [][]>)

Pre :- Matrix to be checked should be acceptedPost :- Status for Symmetric or not symmetricReturn :- Nil

1. for(i=0;i<r;i++)2. for(j=0;j<c;j++)3. m2[i][j] = m1[j][i]4. end5. end6. for(i=0;i<r;i++)7. for(j=0;j<c;j++)

Page 10: Programming Laboratory Lab_manual

8. if ( m2[i][j] == m1[i][j] )9. flag =110. else 11. flag =012. end if13. end14. end 15. if (flag==1)16. Display as Matrix is Symmetric17. else 18. Display as Matrix is not Symmetric19. end if

(V) Algorithm Skew Symmetric (ref m1<int [][]> )

Pre :- Matrix should be acceptedPost :- status if Skew Symmetric or notReturn :- Nil

1. for(i=0;i<r;i++)2. for(j=0;j<c;j++)3. if( m2[i][j] == (- m1[j][i]))4. flag = 15. else6. flag = 07. i = r; j = c; 8. end if9. end10. end 11. if (flag == 1)12. display as Skew Symmetric13. else14. Display as Not skew symmetric

(VI) Algorithm Transpose (ref m1<int [][]>)

Pre :- Matrix should be accepted.Post :- Transpose of MatrixReturn :- Nil

1. for(i=0;i<r;i++)2. for(j=0;j<c;j++)3. m2[i][j] = m1[j][i]4. end5. end6. Display matrix m2[r][c]

Page 11: Programming Laboratory Lab_manual

Testing:

(Input : Accept the matrix as 2D array and perform the different matrix operations. Test the

results for different input test cases, i.e. different size and different valued matrices.

Output : Results of each operation are matching the standard results.

Conclusion: All options stated above are tested and executed successfully.

Page 12: Programming Laboratory Lab_manual

Assignment No. 03

Title of Assignment:

Represent a polynomial using array and write a menu driven program to perform

addition, multiplication and evaluation.

Theory : Polynomial: An algebraic expression consisting of one or more summed terms.

A polynomial is an expression that can be written in the form a n x n + a n-1 x n-1 + a n-2 x n-2 ... + a 0 where n is an integer greater than or equal to zero.

We can represent the Polynomial in one variable, using one dimensional array. The vector element is used as exponent and the array elements are used as coefficients.

For eg. X3 +2X2+4 will be represented as :

0 41 0

A : 2 23 14 0

Polynomial Operations: Display menu

1. Add two polynomials2. Multiply two polynomials3. Evaluate the value of one polynomial4. Exit from program

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithms:

(I) Algorithm accept (ref poly<int[]>)Pre :- NilPost :- Polynomial acceptedReturn :- Nil

This algorithm accepts the polynomial from the user1. Loop ( ; ch == ‘y’ || ch =’Y’; )2. Accept the exponent in exp3. Accept the coefficient in coef.4. poly[exp] = poly[exp] + coef.5. Ask user to continue or break

Page 13: Programming Laboratory Lab_manual

6. end

(II) Algorithm display(ref poly<int[]>)This algorithm displays the polynomial

Pre :- Polynomial to be displayedPost :- Display the polynomial Return :- Nil

1. for( i=0;i>0;i--)2. if (poly[i] !=0 )3. if (poly[i] >0)4. printf(“ \t %d x^%d”; poly[i],i) 5. else6. printf(“%dx^%d”,poly[i],i);7. end if8. endif9. end

(III) Algorithm addpoly (ref poly1<int[], ref poly2<int[]>, ref res<int[] )

This algorithm reads two Source polynomials and adds it to the result.Pre :- Two polynomials should be acceptedPost :- Result of addition of the two poly.Return :- Nil

1. for ( i=0;i<10;i++)2. res[i] = poly1[i] + poly2[i] 3. end

(IV) algorithm Multiplication of polynomial (ref poly1<int[]>, ref poly2<int[], ref res<int[]> )

This algorithm reads two Source polynomials and multiplies the two to get the result in res poly.Pre :- two polynomials should be acceptedPost :- Result of multiplication of two poly.Return :- Nil

1. for ( i=0;i<10;i++)2. for (j=0;j<10;j++)3. res[i+j] += poly1[i] * poly2[j]4. end 5. end

(V) Algorithm Evaluation of polynomial (int poly1[int]) This algorithm evaluates the polynomialPre :- One polynomial should be acceptedPost :- Will evaluate the polynomialReturn :- Nil

1. Accept the value of the character x

Page 14: Programming Laboratory Lab_manual

2. Initialize sum to 03. for (i=0;i<10;i++)4. k = pow(x,i) 5. Sum += poly[i] *k6. end

Testing:

Input : Accept two polynomials with maximum degree and no. of terms in the form of a

pair of exponent and coefficient.

Output : Displayed the result of each operation. It is matching with standard results.

Conclusion: All the polynomial operations have been tested and executed successfully.

Page 15: Programming Laboratory Lab_manual

Assignment No. 04

Title of Assignment: Write a program to perform various operations such as union and

intersection on sets.

Theory : A set is a collection of distinct elements of similar type. e.g. We can have a set of integers (having same domain) as SETA = { 1, 2, 3, 4, 5 }; SETB = { 4, 5, 6, 7, 8 }; UNIION = { 1, 2, 3, 4, 5, 6, 7, 8 }; INTERSECTION = { 4, 5 };

The power set of s is the set of all subsets of s.  The power set of (1, 2, 3) has 8 elements as follows.

(∅,(1),(2),(3),(1,2),(1,3),(2,3),(1,2,3))

Union and intersection are binary operations on sets. An element x is a member of sU t if x is a member of s or t.  An element x is a member of s∩t if x is a member of s and t.  Various possible operations on sets are union, intersection, complement, subset, and power set etc.

Union and intersection are commutative, associative, and distributive over each other. 

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Data Structure used : 1D Array is used to store the set of integers.

Algorithms and requirements:

(I) Algorithm UNION( ref a<int[]>, ref B<int[]>, val m<integer>, val n<integer> )

Purpose : This algorithm finds union of the two sets A and B into set CPre : The two integer sets should be acceptedPost : Union should be present in Result set CReturn : No of elements in C

1 Initialize flag 0 and k02 For i 1 to m do3 C(k) A(i)4 k++5 for j 1 to n6 for I 1 to m and flag =0 do7 If B(j) = A(i)8 Then flag 19 end10 If flag = 011 C(k) B(j)

Page 16: Programming Laboratory Lab_manual

12 k++13 Else14 Flag 015 End elseif16 end 17 Return k

(II) Algorithm INTERSECTION( ref a<int[]>, ref B<int[]>, val m<integer>, val n<integer> )

Purpose : This algorithm finds intersection of the two sets A and B into set CPre : The two integer sets should be acceptedPost : Intersection should be present in Result set CReturn : No of elements in C

1 Initialize flag 0 and k02 for j 1 to n3 for i 1 to m and flag =0 do4 If B(j) = A(i)5 C(k) B(j)6 k++7 endif8 end 9 end10 return k(The source code of the above Program is in d:\tc\bin\setop2.c)

Testing:Input: The two sets with integer numbers as the set elements are accepted with size n and m. Output: The union and intersection results of the two is matching with standard results.

Conclusion: All options stated above are tested and executed successfully.

Page 17: Programming Laboratory Lab_manual

Assignment No. 05

Title of Assignment:

Write a program to compute Inverse of a Matrix.

Theory :

For a square matrix A, the inverse is written A-1. When A is multiplied by A-1 the result is the identity matrix I. Non-square matrices do not have inverses.

Note: Not all square matrices have inverses. A square matrix which has an inverse is called invertible or nonsingular, and a square matrix without an inverse is called noninvertible or singular.

 

AA-1 = A-1A = I

Example: For matrix , its inverse is

since

 

AA-1 =

Adjoint method

A-1 = (adjoint of A)   or   A-1 = (cofactor matrix of A)T

Example: The following steps result in A-1 for .

The cofactor matrix for A is , so the adjoint is

. Since det A = 22, we get

Page 18: Programming Laboratory Lab_manual

Cofactor

The determinant is obtained by deleting the row and column of a given element of a matrix or determinant. The cofactor is preceded by a + or – sign depending whether the element is in a + or – position.

 

 

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithm :

(I) Algorithm accept (ref m<int [][]>)Pre :- NilPost :- Matrix should be acceptedReturn :- Nil

1 Accept the rows of the matrix in r2 Accept the columns of matrix in c3 Enter the matrix elements4 for ( i=0;i<r;i++)5 for (j=0;j<c;j++)6 accept element at m1[i][j] as no7 end8 end

(II) Algorithm inverse (ref m<int [][]>)Pre :- A non-singular matrix should be accepted

Page 19: Programming Laboratory Lab_manual

Post :- Inverse of the input Matrix should be calculatedReturn :- Nil

1 Call a function to Calculate Cofactor of matrix m2 Get transpose of the cofactor matrix (Adjoint) into m2[][]3 Get the determinant of the matrix m into D4 for ( i=0;i<r;i++)5 for (j=0;j<c;j++)6 Inverse[i][j] = (1/D) * m2[i][j]7 end8 End9 Call display(Inverse) to display the Inverse of matrix.

(III) Algorithm Cofactor (ref m<int [][]>, ref cofactor<int[][]>)Pre :- A non-singular matrix should be acceptedPost :- Cofactor of the input Matrix should be calculatedReturn :- Reference to computed cofactor

1 Mij stores the major of A[i][j] 2 for ( i=0;i<r;i++)

3 for (j=0;j<c;j++)4 cofactor[i][j] = pow((-1),(i+j)) * Mij5 end 6 end end

(IV) Algorithm display (ref matrix<int [][]>)

Pre :- Matrix should be accepted.Post :- display of the matrix in row-major fashionReturn :- Nil

1 for (i=0;i<r1;i++)2 for(j=0;j<c1;j++)3 print matrix[i][j]4 end 5 end

(VI) Algorithm Transpose (ref m1<int [][]>)

Pre :- Matrix should be accepted.Post :- Transpose of MatrixReturn :- Nil

Page 20: Programming Laboratory Lab_manual

1. for(i=0;i<r;i++)2. for(j=0;j<c;j++)3. m2[i][j] = m1[j][i]4. end5. end6. Display matrix m2[r][c]

Testing:

Input : A square matrix should be accepted and first it is checked whether it is non-

singular

Output: Inverse of the input matrix is calculated by Adjoint method. It is matching with

standard results.

Conclusion:

Different valued matrices are tested and their Inverse is calculated successfully.

Page 21: Programming Laboratory Lab_manual

Assignment No. 06

Title of Assignment:

Write a program to implement stack as an ADT using Arrays.Theory : A stack is an ordered list in which all insertions and deletions are made at one end, called the top. Given a stack S = (a1,a2,….,an) then we say that a1 is the bottommost element and element ai is on top of the ai-1where 1 < i <= n.The restrictions on a stack imply that if the elements A, B, C, D, E are added to he stack, in that order, then the first element to be removed / deleted must be E. Equivalently we say that the last element to be inserted into the stack will be the first to be removed. For this reason sometimes it is referred to as Last In First Out lists.

To represent stack as an Abstract Data Type, associated with the object stack there are several operations that are necessary:

1) CREATE(S) : which creates S as an empty stack;2) ADD( i , S ) : which inserts the element I onto the stack S;3) DELETE(S) : which removes the top element of stack S;4) TOP(S) : which returns the top element of stack S;5) ISEMTS(S) : which returns true if S is empty else false;

These five functions constitute a working definition of a stack.Formally structure stack is defined as follows:Structure STACK(item)Declare CREATE() stackADD(item, stack) stackDELETE(stack) stackTOP(stack) itemISEMTS(stack) Boolean;for all S in stack, I in item letISEMTS(CREATE) ::= trueISEMTS(ADD(i,S)) ::= falseDELETE(CREATE) ::= errorDELETE(ADD(i,S)) ::= STOP(CREATE) ::= errorTOP(ADD(i,S)) ::= iend

end STACK

The simplest way to represent stack is using one dimensional array, say STACK(0:n-1), where n is the maximum no. of allowable entries.Bottommost element is stored as STACK(0) and topmost as STACK(n-1).

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

Page 22: Programming Laboratory Lab_manual

Algorithms and Requirement :

The simplest way to represent a stack is by using a one dimensional array.But to get top and stack together we combine them into one structure.

(I)Algorithm Push ( ref s<struct stack>, val no<integer> )

This algorithm will push/add one element to stack.

Pre :- Stack should not be fullReturn :- new stack

4 If ! IsFull() then 5 s.top= s.top +16 s.stack[s.top] = no7 End if

(II) Algorithm Pop ( ref s<struct stack> )

This algorithm will pop/delete one element from the stack.

Pre :- Stack should not be emptyReturn :- new stack with one element popped

8 If ! IsEmpty() then 9 Element = s.stack(s.top)10 s.top = s.top -111 Print the element popped12 End if

(III)algorithm Top ( val stack<struct> )

This algorithm will read the element on top of the stack.

Pre :- Stack should not be emptyPost :- Top is unchanged Return :- element on top of the stack

1 If ! IsEmpty() then 2 return s.stack(s.top)3 End if

(IV)algorithm IsEmpty ( val s<struct stack> )

Page 23: Programming Laboratory Lab_manual

This algorithm checks whether stack is empty.

Pre :- Stack should be createdReturn :- Boolean value true(1) if stack is empty else false(0)

1 If s.top = -1 then return 1 2 else return 0

(II) Algorithm ( val s<struct stack> )This algorithm checks whether stack is full.

Pre :- Stack should be createdReturn :- Boolean value true(1) if stack is full else false(0)

1 If s.top = MAX -1 then return 1 2 else return 0

Testing:

Input : If the elements are pushed to stack in order 10 20 30 40 50

If we want to add more than 5 elements, tack full message pops up.

i.e. LIFO order is followed.Output : The order in which they are popped is 50 40 30 20 10After deleting 5 elements it shows stack empty.

Conclusion:

All options stated above are tested and executed successfully.

Page 24: Programming Laboratory Lab_manual

Assignment No. 07

Title of Assignment:

Write a program to convert the given Infix expression to Postfix and perform evaluation.

Theory :

A stack is an ordered list in which all insertions and deletions are made at one end, called the top. Given a stack S = (a1,a2,….,an) then we say that a1 is the bottommost element and element ai is on top of the ai-1 where 1 < i <= n. The restrictions on a stack imply that if the elements A, B, C, D, E are added to he stack, in that order, then the first element to be removed / deleted must be E. Equivalently we say that the last element to be inserted into the stack will be the first to be removed. For this reason sometimes it is referred to as Last In First Out lists.As stack follows the LIFO order, there are large no. of applications of a stack as follows :

1) Conversion from Infix to Postfix and Prefix Expression2) Evaluating the Postfix expressions3) Processing of subroutine calls4) Reversing a string5) Checking Correctness of nested parenthesis6) Simulating recursion7) Parsing of computer Programs8) Backtracking algorithms9) Computation like Decimal to Binary Conversion.

Here we are implementing the first Application, i.e. Conversion of the expression from Infix form to Postfix and prefix form, so that the expression can be evaluated in proper order i.e. as per the priority of the operators in the expression. Compiler will not understand the exact order once expression is given. To make it clear, expression is converted to either postfix or prefix form in which arrangement of operands and operators is done as per their priorities and associativity (L-R/ R-L).Stack is used to hold the operators in conversion process. In evaluation stack holds the operands for the current operation and final result is also present on stack at the end of evaluation.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

Data structure used: Stack is used to hold the operators in Infix expression. Struct stack { char optr; int top; };

Page 25: Programming Laboratory Lab_manual

Algorithms and Requirements :(I)Algorithm Push ( ref s<struct stack>, val no<integer> )

This algorithm will push/add one element to stack.

Pre :- Stack should not be fullReturn :- new stack

13 If ! IsFull() then 14 stop stop +115 sstack[stop] no16 End if

(II) Algorithm Pop ( ref stack<struct> )

This algorithm will pop/delete one element from the stack.

Pre :- Stack should not be emptyReturn :- new stack

1 If ! IsEmpty() then 2 Element sstack(stop)3 S->top stop -14 Print the element popped5 End if

(III) Algorithm IsEmpty ( val s<struct stack> )

This algorithm checks whether stack is empty.

Pre :- Stack should be createdReturn :- Boolean value true(1) if stack is empty else false(0)

1 If s.top = -1 then return 1 2 else return 0

(IV) Algorithm IsFull( val s<struct stack> )

This algorithm checks whether stack is full.

Pre :- Stack should be created

Page 26: Programming Laboratory Lab_manual

Return :- Boolean value true(1) if stack is full else false(0)

1 If s.top = MAX -1 then return 1 2 else return 0

(IV) Algorithm POSTFIX ( ref E<char[]> )

This algorithm converts the given Infix expression into Postfix form.

Pre :- Infix expression should be accepted Post :- Postfix expression should be present in E2Return :- void

// Start scanning E from left to right1 loop2 x NEXT-TOKEN(E)3 case4 :x = ‘\0’: while top >1 do // empty the stack5 Print (STACK(top)); top top -16 end7 Add (‘\0’) at the end of string8 Return9 :x is an operand : add (x) in E210 :x = ‘)’ : while STACK(top) != ‘(‘ do11 E2 = POP(STACK)12 End13 top top -1 14 : else : while ISP(STACK(top)) >= ICP(x) do15 E2 = POP(STACK)16 End17 Push(STACK, x)18 End19 Forever20 End POSTFIX

(IV) Algorithm EVAL ( ref E<char[]> )

This algorithm evaluates the given Postfix expression.

Pre :- Postfix expression should be accepted Post :- Result of expression evaluation should be present on top of the Stack.Return :- void

// Start scanning E from left to right1 top 0 // Initialize stack2 loop3 x NEXT-TOKEN(E)

Page 27: Programming Laboratory Lab_manual

4 case5 :x = ‘\0’: return // answer is at top of the stack6 :x is an operand : call Push(STACK, x) on stack7 :else [ remove the correct no of operands for the operator x 8 from STACK, perform the operation and store the result, 9 if any onto the stack ]10 End11 Forever12 End EVAL

Testing:

Input : Infix expression in the form of character string should be accepted, like

a+b*(d-h)/p

Output: Output is the postfix expression in character string format, like

abdh-*p/+, this is evaluated with constant values of a, b,d, h & p and result

obtained is matching the standard results.

Conclusion: All options stated above are tested and executed successfully.

Page 28: Programming Laboratory Lab_manual

Assignment No. 08

Title of Assignment :

. Write a program to convert the given Infix expression to Prefix and Prefix to Infix

Theory :

A stack is an ordered list in which all insertions and deletions are made at one end, called the top. Given a stack S = (a1,a2,….,an) then we say that a1 is the bottommost element and element ai is on top of the ai-1 where 1 < i <= n. The restrictions on a stack imply that if the elements A, B, C, D, E are added to he stack, in that order, then the first element to be removed / deleted must be E. Equivalently we say that the last element to be inserted into the stack will be the first to be removed. For this reason sometimes it is referred to as Last In First Out lists.As stack follows the LIFO order, there are large no. of applications of a stack as follows :

1. Conversion from Infix to Postfix and Prefix Expression2. Evaluating the Postfix expressions3. Processing of subroutine calls4. Reversing a string5. Checking Correctness of nested parenthesis6. Simulating recursion7. Parsing of computer Programs8. Backtracking algorithms9. Computation like Decimal to Binary Conversion.

Here we are implementing the first Application, i.e. Conversion of the expression from Infix form to Postfix and prefix form, so that the expression can be evaluated in proper order i.e. as per the priority of the operators in the expression. Compiler will not understand the exact order once expression is given. To make it clear, expression is converted to either postfix or prefix form in which arrangement of operands and operators is done as per their priorities and associativity (L-R/ R-L).Stack is used to hold the operators in conversion process. In evaluation stack holds the operands for the current operation and final result is also present on stack at the end of evaluation.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Data structure used: Stack is used to hold the operators in Infix expression. Struct stack { char optr; int top; };

Algorithms and Requirements :(I)Algorithm Push ( ref s<struct stack>, val no<integer> )

This algorithm will push/add one element to stack.

Page 29: Programming Laboratory Lab_manual

Pre :- Stack should not be fullReturn :- new stack

1. If ! IsFull() then 2. stop stop +13. sstack[stop] no4. End if

(II) Algorithm Pop ( ref stack<struct> )

This algorithm will pop/delete one element from the stack.

Pre :- Stack should not be emptyReturn :- new stack

1 If ! IsEmpty() then 2 Element sstack(stop)3 S->top stop -14 Print the element popped5 End if

(III) Algorithm IsEmpty ( val s<struct stack> )

This algorithm checks whether stack is empty.

Pre :- Stack should be createdReturn :- Boolean value true(1) if stack is empty else false(0)

1 If s.top = -1 then return 1 2 else return 0

(IV) Algorithm IsFull( val s<struct stack> )

This algorithm checks whether stack is full.

Pre :- Stack should be createdReturn :- Boolean value true(1) if stack is full else false(0)

1 If s.top = MAX -1 then return 1 2 else return 0

(IV) Algorithm PREFIX ( ref E<char[]> )

Page 30: Programming Laboratory Lab_manual

This algorithm converts the given Infix expression into Prefix form.

Pre :- Infix expression should be accepted Post :- Prefix expression should be present in E2Return :- void

// Start scanning E from right to left1 loop

2 x NEXT-TOKEN(E)3 case4 :x = ‘\0’: while top >1 do // empty the stack5 Print (STACK(top)); top top -16 end7 Add (‘\0’) at the end of string8 Return9 :x is an operand : add (x) in E210 :x = ‘)’ : while STACK(top) != ‘(‘ do11 E2 = POP(STACK)12 End13 top top -1 14 : else : while ISP(STACK(top)) > ICP(x) do

15 E2 = POP(STACK)16 End17 Push(STACK, x)18 End19 Forever20 Get the reverse of E2 (actual prefix expression)21 End PREFIX

Testing:

The Infix expression is entered in a character array as : A+B*(C-D)/GThen the expression is converted to Postfix form as : ABCD-*G/+This is given as input for evaluation of expression after assigning proper values to variables. Result of evaluation as per the priority is displayed at the end.So any parenthesized expression containing n no of variables and operators(+,-,/,*,%,^) should be evaluated in correct order.

Conclusion:

All options stated above are tested and executed successfully.

Page 31: Programming Laboratory Lab_manual

Assignment No. 09

Title of the assignment :Write a program to convert the given Postfix expression to Infix and Postfix to Prefix.Theory :

Given the postfix expression we can convert it to Infix and prefix.

Data structure used: stack to hold operands and partial expressions which are in prefix

or infix form.

Struct stack { char exp[20]; int top; };

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

(I) Algorithm POSTTOPRE ( ref post<char[]> )

This algorithm converts the given postfix expression to prefix.

Pre : Postfix expression should be accepted

Post : Prefix should be generated

Result : Nil

1 loop ( not end of post expression )

2 ch = nexttoken(post)

3 if( ch = operand )

4 push(s, ch)

5 if( (ch = operator )

6 op2 = pop(s)

7 op1 = pop(s)

8 push(s, “ch,op1,op2”);

9 endif

10 if ch = ‘\0’

11 display stack contents (prefix obtained)

(II) Algorithm POSTTOIN ( ref post<char[]> )

This algorithm converts the given postfix expression to infix.

Pre : Postfix expression should be accepted

Post : Infix should be generated

Page 32: Programming Laboratory Lab_manual

Result : Nil

1 loop ( not end of post expression )

2 ch = nexttoken(post)

3 if( ch = operand )

4 push(s, ch)

5 if( (ch = operator )

6 op2 = pop(s)

7 op1 = pop(s)

8 push(s, “(op1,ch,op2)”);

9 endif

10 if ch = ‘\0’

11 display stack contents (infix obtained)

Testing:

Input : Postfix expression in the form of character string should be accepted

Output : Prefix and Infix expression is given as the ouput after conversion which matches

the standard results.

Conclusion:

All options stated above are tested and executed successfully, so conversion from postfix to prefix and infix is implemented successfully

Page 33: Programming Laboratory Lab_manual

Assignment No. 10

Title of Assignment:

Write a program to understand various logical and bitwise operators as follows using stack to convert the no from Decimal to binary form :

1) Bitwise |2) Bitwise &3) Bitwise ^4) Bitwise ~5) Bitwise <<6) Bitwise >>

Theory :

The Logical Bitwise Operators

There are three Logical Bitwise operators: bitwise and (&), bitwise exclusive or (^), and bitwise or (|). Each of these operators requires two integer–type operands. The operations are carried out independently on each pair of corresponding bits within the operands. Thus the least significant bits (i.e., the rightmost bits) within the two operands will be compared, then the next least significant bits, and so on, until all of the bits have been compared. The results of these comparisons are:

A bitwise and expression will return a 1 if both bits have a value of 1 (i.e., if both bits are true). Otherwise, it will return a value of 0.

A bitwise exclusive or expression will return a 1 if one of the bits has a value of 1 and the other has a value of 0 (one bit is true, the other false). Otherwise, it will return a value of 0.

A bitwise or expression will return if a 1 if one or more of the bits have a value of 1 (one or both bits are true). Otherwise, it will return the value of 0.

These results are summarized in Table 13 – 1. In this table, b1 and b2 represent the corresponding bits within the first and second operands, respectively.

Table 13-1 Logical Bitwise Operations

b1 b2 b1 & b2 b1^b2 b1 | b21100

1010

1000

0110

1110

Each of the logical bitwise operations has its own precedence. The bitwise and (&) operator has the highest precedence, followed by bitwise exclusive or (^), then bitwise or (|). Bitwise and follows the equality operators (== and ! =). Bitwise or is followed by logical and (&&). The associativity for each bitwise operator is left to right. See Appendix C for a summary of all C operators, showing their precedences and associativities.)

Masking

Page 34: Programming Laboratory Lab_manual

Masking is a process in which a given bit pattern is transformed into another bit pattern

by means of a logical bitwise operation. The original bit pattern is one of the operands in

the bitwise operation. The second operand, called the mask, is a specially selected bit

pattern that brings about the desired transformation.

There are several different kinds of masking operations. For example, a portion of a given bit pattern can be copied to a new word, while the remainder of the new word is filled with 0s. Thus, part of the original bit pattern will be “masked off” from the final result. The bitwise and operator (&) is used for this type of masking operation.Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithms and requirements :

(I) Algorithm BinToDecimal( val a<integer>)

Pre : Decimal No should be accepted in aPost : Result of conversion should be present in array arr[]Return : No of bits generated should be returned

1 Initialize arr (0-15) to zeros2 while no != 0 do3 begin4 arr[n] no % 25 no no/26 noofbits noofbits+17 n n-18 end9 return noofbits

(I) Algorithm BitwiseAnd( val n1<integer>, val n2<integer>)

Pre : Two decimal nos n1 and n2 should be accepted. Post : Result of operation should be present in array bitwise&[]Return : Nothing

1 Call DecToBinary(n1, bin1[]) so that bin1 contains binary representation of n1 in bin12 Call DecToBinary(n2, bin2[]) so that bin2 contains binary representation of n2 in bin23 for i 0 to 164 if bin1(i) && bin2(i)5 bitwise&(i) 16 else7 bitwise&(i) 08 endif9 Call the function to print the result of bitwise & in bitwise&[].

Page 35: Programming Laboratory Lab_manual

10 Call the function to get decimal equivalent of bitwise& and print it

(II) Algorithm BitwiseOr( val n1<integer>, val n2<integer>)

Pre : Two decimal nos n1 and n2 should be accepted. Post : Result of operation should be present in array bitwiseOR[]Return : Nothing

1 Call DecToBinary(n1, bin1[]) so that bin1 contains binary representation of n1 in bin12 Call DecToBinary(n2, bin2[]) so that bin2 contains binary representation of n2 in bin23 for i 0 to 164 if bin1(i) || bin2(i)4 bitwiseOR(i) 15 else6 bitwiseOR(i) 08 endif9 Call the function to print the result of bitwise oring in bitwiseOR[].10 Call the function to get decimal equivalent of bitwiseOR and print it

(III) Algorithm BitwiseXor( val n1<integer>, val n2<integer>)

Pre : Two decimal nos n1 and n2 should be accepted. Post : Result of operation should be present in array bitwiseXOR[]Return : Nothing

1 Call DecToBinary(n1, bin1[]) so that bin1 contains binary representation of n1 in bin12 Call DecToBinary(n2, bin2[]) so that bin2 contains binary representation of n2 in bin23 for i 0 to 164 if bin1(i) = bin2(i)4 bitwiseXOR(i) 05 else6 bitwiseOR(i) 18 endif9 Call the function to print the result of bitwise xoring in bitwiseXOR[].10 Call the function to get decimal equivalent of bitwiseXOR and print it.

(III) Algorithm BitwiseComp( val n1<integer>)

Pre : A decimal no n1 should be accepted. Post : Result of complement should be present in array bitwiseCOMP[]Return : Nothing

1 Call DecToBinary(n1, bin1[]) so that bin1 contains binary representation of n1 in bin12 for i 0 to 164 if bin1(i) = 14 bitwiseCOMP(i) 05 else6 bitwiseCOMP(i) 18 endif9 Call the function to print the result of bitwise Complement in bitwiseCOMP[].

Page 36: Programming Laboratory Lab_manual

10 Call the function to get decimal equivalent of bitwiseCOMP and print it.

(III) Algorithm BitwiseLeftShift( val n1<integer>, val n2<integer>)

Pre : Two decimal nos n1(no to be left-shifted) and n2(no of bits) should be accepted. Post : Result of left shift should be present in array bitwiseLS[]Return : Nothing

1 Call DecToBinary(n1, bin1[]) so that bin1 contains binary representation of n1 in bin12 for i 0 to (15-n2) do4 bitwiseLS(i) bitwiseLS(i+n2)9 Call the function to print the result of bitwise xoring in bitwiseXOR[].10 Call the function to get decimal equivalent of bitwiseXOR and print it.Testing:

Input : Decimal number(int) should be accepted (1/2) and converted to binary number

using stack.

Ex. : Numbers entered are : 4 , 6

Equivalent binary : 00000100 , 00000110

Output : As per the operation specified result is obtained in binary and converted back to

decimal and printed. All the results are matching the standard results.

4&6 gives 00000100 i.e. 4

Conclusion:

All bitwise operators stated above are performed and executed successfully using stack

Page 37: Programming Laboratory Lab_manual

Assignment No. 11a

Title of Assignment:

Write a program to implement circular queue and double-ended queue using arrays.

Theory : Write a program to implement Circular queue as an ADT with the following operations –

a) ADDQb) DELETEQc) ISEMTQd) ISFULLQe) QFRONT

Problem Definition :

A queue is an ordered list in which all insertions can be done only at the end called rear and deletions are made at the other end, called the front. Given a queue Q = (a1,a2,….,an) then we say that a1 is at the front-end and an is at the rear end. Also we say that ai+1 is behind ai. where 1 < i <= n. The restrictions on a queue imply that if the elements A, B, C, D, E are added to the queue, in that order, then the first element to be removed / deleted must be A which is inserted first. Equivalently we say that the last element to be inserted into the queue will be the last to be removed. For this reason is referred to as First In First Out lists.To represent queue as an Abstract Data Type, associated with the object queue there are several operations that are necessary:

1 CREATE(Q) : which creates Q as an empty queue;2 ADDQ( item, Q ) : which inserts the item into the rear end of the queue Q;3 DELETEQ(Q) : which removes the element of queue Q which is at the front

position of the queue.4 FRONT(Q) : which returns the element (item) which is at the front position of the

Q;5 ISEMTQ(Q) : which returns true if Q is empty else false;6 IFULLQ(Q) : which returns true only if Queue is Full else false.

A complete specification of Queue as an ADTFormally structure queue is defined as follows:Structure QUEUE(item) Declare CREATEQ() queue ADDQ(item, queue) queue DELETEQ(queue) queue FRONT(queue) queue ISEMTQ(queue) Boolean;for all Q in queue, i in item let ISEMTQ(CREATEQ) ::= true ISEMTQ(ADDQ(i, Q)) ::= false DELETE(CREATEQ) ::= error DELETEQ(ADDQ(i, Q)) ::=

Page 38: Programming Laboratory Lab_manual

if ISEMTQ(Q) then CREATEQ else ADDQ(i,DELETEQ(Q)) FRONT(CREATEQ) ::= error FRONT(ADDQ(i, Q)) ::= if ISEMTQ(Q) then i else FRONT(Q)end

end QUEUE

The simplest way to represent queue is using one dimensional array, say QUEUE(0:n-1), where n is the maximum no. of allowable entries.Front element is stored as QUEUE(0) and rear as QUEUE(n-1). It is called as Linear Queue. But there are some drawbacks in Linear queue. The elements which are deleted from front end, cannot be used again unless and until those are not shifted. So in shifting the elements after every delete operation is a big overhead. To overcome this drawback, queue can be implemented as a Circular queue, where rear and front is incremented in round fashion, i.e. using mod operator.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

Algorithms and Requirement :To associate front and rear to queue elements, we combine them into one structure as follows :

typedef struct{ int front, rear; data-type queue[MAX];}QUEUE;

(I) Algorithm ADDQ ( ref q<struct queue>, val no<integer> )

This algorithm will add one element to queue.

Pre :- Queue should not be fullPost :- New element should be added at rear end of queue.Return :- new queue

17 Rear (rear+1) % size18 If ! IsFull() then 19 qrear no20 endif

(II) Algorithm DeleteQ ( ref q<struct queue> )

This algorithm will delete one element from the queue.

Pre :- Queue should not be empty

Page 39: Programming Laboratory Lab_manual

Post :- Element at front end is deletedReturn :- new queue

1. If ! IsEmpty() then 2. Element qqueue(qfront)3. q->front (qfront +1)% size4. Print the element deleted 5. End if

(III) Algorithm Front ( val q<struct queue> )

This algorithm will read the element on front end of the queue.

Pre :- Queue should not be emptyPost :- Element on front side is read Return :- If q not empty element on front side of queue otherwise -1

1 If ! IsEmtQ() then 2 return qqueue(qfront+1)3 Else4 Return -15 End if

(IV) Algorithm IsEmtQ ( val q<struct queue> )

This algorithm checks whether queue is empty.

Pre :- Queue should be createdPost :- Queue is unchangedReturn :- Boolean value true(1) if queue is empty else false(0)

1 If q.front = q.rear then 2 return 13 else 4 return 05 end if

(II) Algorithm IsQFull ( val q<struct queue> )

This algorithm checks whether queue is full.Pre :- Queue should be createdReturn :- Boolean value true(1) if queue is full else false(0)

1 If q.front = q.rear then 2 return 13 else 4 return 0

End if

Page 40: Programming Laboratory Lab_manual

Testing:

If the elements are added to queue in order 10 20 30 40 50The order in which they are deleted is 10 20 30 40 50i.e. FIFO order is followed.Conclusion :

All options stated above are tested and executed successfully.

Page 41: Programming Laboratory Lab_manual

Assignment No. 11b

Title of Assignment:

Write a program to implement Deque as an ADT with the following operations –1 ADDFRONTQ2 ADDREARQ3 DELETEFRONTQ4 DELETEREARQ5 ISEMTQ6 FRONTQ7 ISFULLQ

Theory :

A queue is an ordered list in which all insertions can be done only at the end called rear and deletions are made at the other end, called the front. Given a queue Q = (a1,a2,….,an) then we say that a1 is at the front-end and an is at the rear end. Also we say that ai+1 is behind ai. where 1 < i <= n. To represent queue as an Abstract Data Type, associated with the object queue there are several operations that are necessary:

1 CREATE(Q) : which creates Q as an empty queue;2 ADDQ( item, Q ) : which inserts the item into the rear end of the queue Q;3 DELETEQ(Q) : which removes the element of queue Q which is at the front

position of the queue.4 FRONT(Q) : which returns the element (item) which is at the front position of

the Q;5 ISEMTQ(Q) : which returns true if Q is empty else false;6 IFULLQ(Q) : which returns true only if Queue is Full else false.

A complete specification of Queue as an ADTThe simplest way to represent queue is using one dimensional array, say QUEUE(0:n-1), where n is the maximum no. of allowable entries.Front element is stored as QUEUE(0) and rear as QUEUE(n-1). It is called as Linear Queue. But there are some drawbacks in Linear queue. The elements which are deleted from front end, cannot be used again unless and until those are not shifted. So in shifting the elements after every delete operation is a big overhead. One of the variants of Queue is called Deque where insertion and deletion to queue can be done from both the ends i.e. rear and front. So deque combines the properties of Queue as well as Stack when required. As per the requirement of application we can alter the insert delete of deque. In that there are two types :

1) Input restricted Deque : In this Insertions are allowed only from front or only from rear but not from both. But deletions can be done from any of the ends.

2) Output restricted Deque : In this Deletions are allowed only from front or only from rear but not from both. But Insertions can be done from any of the ends.

Page 42: Programming Laboratory Lab_manual

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithms and Requirement :To associate front and rear to queue elements, we combine them into one structure as follows :

typedef struct{ int front, rear; data-type queue[MAX];}QUEUE;

(I) Algorithm ADDFRONTQ ( ref q<struct queue>, val no<integer> )

This algorithm will add one element to queue.

Pre :- Queue should not be fullPost :- New element should be added at rear end of queue.Return :- new queue

1 Rear (rear+1) % size2 If ! IsFull() then 3 qrear no4 endif

(II) Algorithm DeleteQ ( ref q<struct queue> )

This algorithm will delete one element from the queue.

Pre :- Queue should not be emptyPost :- Element at front end is deletedReturn :- new queue

1 If ! IsEmpty() then 2 Element qqueue(qfront)3 q->front (qfront +1)% size4 Print the element deleted 5 End if

(III) Algorithm Front ( val q<struct queue> )

This algorithm will read the element on front end of the queue.

Pre :- Queue should not be emptyPost :- Element on front side is read Return :- If q not empty element on front side of queue otherwise -1

1 If ! IsEmtQ() then

Page 43: Programming Laboratory Lab_manual

2 return qqueue(qfront+1)3 Else4 Return -15 End if

(IV) Algorithm IsEmtQ ( val q<struct queue> )

This algorithm checks whether queue is empty.

Pre :- Queue should be createdPost :- Queue is unchangedReturn :- Boolean value true(1) if queue is empty else false(0)

1 If q.front = q.rear then 2 return 13 else 4 return 05 end if

(II) Algorithm IsQFull ( val q<struct queue> )

This algorithm checks whether queue is full.Pre :- Queue should be createdReturn :- Boolean value true(1) if queue is full else false(0)

1 If q.front = q.rear then 2 return 13 else 4 return 05 End if

Testing:

If the elements are added to queue in order 10 20 30 40 50 from rear endThe order in which they are deleted is 10 20 30 40 50 from front end. So here it acts as Queue. But from front-end if elements are added as 1 2 3 4 5, and if we delete them again from front side the order of deletion is 5 4 3 2 1. So here the order followed is LIFO, i.e. of stack.Thus Deque works as queue as well as stack.

Conclusion:

All options stated above are tested and executed successfully.

Page 44: Programming Laboratory Lab_manual

Assignment No. 12

Title of Assignment:

Write a program to implement Sequential and Binary search.

Theory :

A table or a file is a group of elements, each of which is called a record.Associated with each record is a key, which is used to differentiate among different records. In the simplest form key is contained within the record at a specific offset from the start of the record. It is called as internal key, which plays very important role in searching for a record. A search algorithm is an algorithm that accepts an argument a and tries to find a record whose key is a. Algorithm returns either entire record or a pointer to that record.The two different searching techniques that we’ll implement are as follows:

1. Linear search: It also known as sequential search that is suitable for searching a set of data for a particular value. It is simplest form of a search. It operates by checking every element of a list one at a time in sequence until a match is found or till list is not over. If search is successful it returns location of the match found otherwise returns -1(unsuccessful search). The worst case time complexity of sequential search is O(n).

2. Binary Search: The most efficient method of searching a sequential table is the binary search. Unlike sequential search, the list of records should be sorted on key in ascending or descending order to implement this search. It starts by getting the median of the list. Then it makes a comparison to determine whether the desired value comes before or after it, and then searches the remaining half in the same manner. A binary search is an example of a divide and conquer algorithm. The worst case time complexity of binary search is O(logn).

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithms and Requirement :

// Function to accept the array from user(I) Algorithm accept (ref arr<int []>)Pre :- NilPost :- Will accept the arrayReturn :- Returns the total number of elements.

This algorithm accepts the integer array from user1 Accept the total number of elements in n2 Initialise i 03 loop(till i<n)4 arr(i) value5 i i+1

Page 45: Programming Laboratory Lab_manual

6 end loop7 return n

//Function for Linear Search(II) Algorithm Linear(ref arr<int[]>, val len <int>, val no<int>)Pre :- List of nos. and number to be searched should be acceptedPost :- Search is successful if no is found else unsuccessfulReturn :- If no found index of no is returned else return -1.

This algorithm for linear search1 loop ( till i<len )2 if (arr(i) = no)3 return i4 end loop5 return -1

//Function for Binary search(III) Algorithm Binary(ref arr<int>, val len<int>, val no <int>)

Pre :- List of nos. and number to be searched should be acceptedPost :- Search is successful if no is found else unsuccessfulReturn :- If no found index of no is returned else return -1.Algorithm checks if given no is present in the list using binary search method.

1 Initialize high len-12 Initialize low 03 while( high >= low)4 mid (high + low)/25 if( arr(mid) = no)

return mid6 if( no > arr(mid))

low = mid +1;7 else

high = mid -1; 8 end 9 return -1

Testing:

Input : List of numbers and no to be searched should be accepted

Output : Result of whether search is successful (with location of data in the list is

displayed) or else not successful.

Conclusion:

All options stated above are executed successfully for both the searching techniques.

Page 46: Programming Laboratory Lab_manual

Assignment No. 13

Title of Assignment:

Write a program to sort the given list of numbers using -1) Bubble sort 2) Selection sort

Theory :

When we are dealing with large sized files and if frequent use of file is required for the purpose of retrieving some specific element, it is more efficient to sort the file. This is because overhead of successive searches mayfar exceed the overhead involved in sorting the file. Here is the need of sorting mechanism.

Sorting is nothing but ordering a list of items. Lots of techniques are available for sorting the given list. Programmer should make intelligent choice about which sorting method is most appropriate to a particular problem. Some sorting algorithms are simple and intuitive, such as the bubble sort. Others, such as the quick sort are extremely complicated, but produce lightening-fast results.

Three most important efficiency considerations include length of the time spent in coding a particular sorting program, the amount of machine time necessary for running the program and the amount of space necessary for program.

Bubble sort : It is the simplest, easy to understand but least efficient sorting algorithm. Each pass consists of comparing each element in file with its successor and interchange the two elements if not in proper order.

X[] is an array of integers to be sorted

X 5 4 3 2 1

Pass 1 : 4 3 2 1 5

Pass 2 : 3 2 1 4 5

Pass 3 : 2 1 3 4 5

Pass 4 : 1 2 3 4 5

So here list gets sorted in only n-1 passes.No of comparisons go on decreasing after every pass. But still in worst case the time complexity of bubble sort is O(n2) which is highest as compared to other algorithms.

Selection sort:

The straight selection sort or push-down sort implements the descending priority queue as an unordered array. It is an in-place sort b’coz array x only is used to hold the priority queue. It consists of the selection phase in which the largest of the remaining elements, large , is repeatedly placed in its proper position, I, at the end of array. To dod so, large is

Page 47: Programming Laboratory Lab_manual

interchanged with x[i]. The initial n-element priority queue is reduced by one element after each selection. After n-1 selections entire array is sorted.

It is better than bubble sort though time complexity is same i.e. O(n2).But it is less efficient than Insertion sort. Quick sort with the lease time complexity i.e. O(nlogn) is considered as the best sorting technique as compared to above two.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)Algorithms and Requirement :Following is the algorithm of bubble and selection sort for which unsorted list of numbers is accepted before.

(I) Algorithm BubbleSort ( ref x<integer[]>, val size<integer> )

This algorithm will sort the given list using Bubble Sort techniqe.

Pre :- List of numbers should be acceptedPost :- sorted list should be present in xReturn :- nothing

1. for pass 0 to size-1 and switched do2. switched 0;3. for j0 to j < (size-pass-1) do4. if( x[j] > x[j+1] )

i. switched 1 ;5. temp x[j];6. x[j] x[j+1];7. x[j+1] temp;8. endif9. end10. end

(II) Algorithm SelectionSort ( ref x<integer []>, val size<integer> )

This algorithm for selection sort technique.

Pre :- List of numbers should be acceptedPost :- sorted list should be present in xReturn :- nothing

for i n-1 to i > 0 in steps of -1 doLarge= x(0)indx = 0for j = 1 to j <= I do

Page 48: Programming Laboratory Lab_manual

if ( x[j] > large) then large = x(j) indx = j endifendx(indx) = x(i)x{i) = largeend

Testing:

If the elements entered are : 67 54 34 20 12The output of the sorting comes to be 12 20 34 54 67So unsorted lists are getting sorted correctly in ascending order.

Conclusion:

All options stated above are tested and executed successfully.

Page 49: Programming Laboratory Lab_manual

Assignment No. 14

Title of Assignment:

Write a program to solve the system of Simultaneous Equations using Cramers Rule, Gauss

Seidal Rule and Gauss Elimination Method.

Theory :

Cramer's Rule

Given a system of linear equations, Cramer's Rule is a handy way to solve for just one of the variables without having to solve the whole system of equations. They don't usually teach Cramer's Rule this way, but this is supposed to be the point of the Rule. Instead of solving the whole system, you can use Cramer's to solve for just one variable.

Look at the following system of equations:

2x +   y + z = 3   x –   y – z = 0   x + 2y + z = 0

Looking at the system, you have the left-hand side with the variables and the right-hand side with the answer values. Let D be the determinant of the coefficient matrix of the above system, and let Dx be the determinant formed by replacing the x-column values with the answer-column values. That is:

system ofequations

coefficientmatrix's

determinant

answercolumn

Dx: coefficient determinantwith answer-columnvalues in x-column

2x + 1y + 1z = 3  1x – 1y – 1z = 0 1x + 2y + 1z = 0

Similarly, Dy and Dz would then be: Copyright © Elizabeth Stapel 2000-2006 All Rights served

Cramer's Rule says that x = Dx ÷ D, y = Dy ÷ D, and z = Dz ÷ D. That is:

x = 3/3 = 1,  y = –6/3 = –2,  and  z = 9/3 = 3

Page 50: Programming Laboratory Lab_manual

The Gauss-Seidel Method

We are considering an iterative solution to the linear system

 

where is an sparse matrix, x and b are vectors of length n, and we are solving for x. Iterative solvers are an alternative to direct methods that attempt to calculate an exact solution to the system of equations. Iterative methods attempt to find a solution to the system of linear equations by repeatedly solving the linear system using approximations to the vector. Iterations continue until the solution is within a predetermined acceptable bound on the error.

Common iterative methods for general matrices include the Gauss-Jacobi and Gauss-Seidel, while conjugate gradient methods exist for positive definite matrices. Critical in the choice and use of iterative methods is the convergence of the technique. Gauss-Jacobi uses all values from the previous iteration, while Gauss-Seidel requires that the most recent values be used in calculations. The Gauss-Seidel method generally has better convergence than the Gauss-Jacobi method, although for dense matrices, the Gauss-Seidel method is inherently sequential. Better convergence means fewer iterations, and a faster overall algorithm, as long as the strict precedence rules can be observed. The convergence of the iterative method must be examined for the application along with algorithm performance to ensure that a useful solution to can be found.

The Gauss-Seidel method can be written as:

where:¯

is the unknown in during the iteration, and ,

is the initial guess for the unknown in ,

is the coefficient of in the row and column,

is the value in .

or

 

where:¯

Page 51: Programming Laboratory Lab_manual

is the iterative solution to , ,

is the initial guess at ,

is the diagonal of ,

is the of strictly lower triangular portion of ,

is the of strictly upper triangular portion of ,

is right-hand-side vector.

The representation in equation 2 is used in the development of the parallel algorithm, while the equivalent matrix-based representation in equation 3 is used below in discussions of available parallelism.

This Gauss-Seidel method has better convergence.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

(I) Algorithm CramerRule()

1 ) Read the number of variables ‘n’ in the system of equations(n).2) for ( i= 1; j <=n ; j ++)3) for (j= 1; j <=n ;j ++ )4) Read the coefficients of equations into matrix A[i][j]5) end6) end7) for ( i= 1; j <=n ; j ++)8) Read constants into B[i] array9) Find the determinant of the given matrix of equations into D.

10) for ( I = 1; I < n; I ++ ) 11) Replace the column for variable i in all equations by column of constants and get the value of this new matrix into Dval[i]. 12) for ( I = 1; I < n; I ++ ) 13) x[i] = Dval[i] / D 14) for ( I = 1; I < n; I ++ ) 15) Print value of x[i] i.e. values of variables.

(II) Algorithm Gauss-seidal()1) Read number of variables n in system of equations2) for ( i= 1; j <=n ; j ++)

Page 52: Programming Laboratory Lab_manual

3) for (j= 1; j <=n ;j ++ )4) Read the coefficients of equations into matrix A[i][j]5) end6) end7) for ( i= 1; j <=n ; j ++)8) Read constants into B[i] array9) Arrange equations such that all the diagonal elements A[i][i] (i=1 to n) are as far as possible higher in their respective columns.10) Represent the system of equations as ,11) for ( I = 1; I <= n ;I ++)12) for( j= 1; j <=n ; j++ )13) if ( I != j ) 14) Xi(k+1) = 1 / A[i][i] ( b[i] - ( A[j][1] X1(k) + A[j][2] X2(k) + A[j][3] X3(k)

+ A[j][n] Xn(k)

15) Take initial Approximation to variables16) X1(0) = X2(0) = ….= Xn(0) = 0 ( k = 0 ) 17) Execute Iterative equations of step 14) by putting values of variables of kth

iteration to obtain values of (k+1)th iteration.18) Repeat step 17) till required iterations or required accuracy is not achieved in

values of variables.19) Display the values of variables Xi ( I = 1 to n) on the screen and stop.

Testing:

Input : Input is accepted in the form of no of equations, their coefficients and vector for

constants.

Output : Using each of the method to get the solution of this set of equations, the values of

variables are calculated and they are matching with actual results.

Conclusion : All the three methods above are verified and executed successfully to get the

solution of linear equations.

Page 53: Programming Laboratory Lab_manual

Assignment No. 15

Title of Assignment:

Write a program to create a text file, read it and convert into uppercase & write the contents

into another text file by using command line arguments.

Theory :Command line Parameters: Parameters can be passed through main from O/S. Two such arguments are allowed in most C versions. Traditionally they are called as argc and argv argc: Must be integer (It is the number of parameters passed through O/S) argv: Array of pointers to character i.e. array of strings.Syntax of main function : Void main ( int argc, char *argv[ ])

We can execute the programme along with arguments. The programme name is interpreted as O/S Command. Hence line in which it is appear generally referred as command line.

Modes of File opening:

Type Descriptionr Opens existing file in read modew New file created and written

aAppend existing or create new if not exist.

r+ Open for read and write modew+ New file for read and write

a+Read and append existing, create new if not exist.

Library Functions Details: 1. fopen() : It opens a stream

Syntac: FILE *fopen(const char *filename, const char *mode);

2. fclose() : It closes the named stream.

Page 54: Programming Laboratory Lab_manual

Syntax: fclose(FILE *stream);

3. fgetc() : fgetc( ) gets a character from a stream Syntax: fgetc(FILE *stream);

4. putc() : fputc() puts a character to a stram Syntax: fputc(int c, FILE *stream);

Page 55: Programming Laboratory Lab_manual

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

(I) Algorithm main(val argc<int>, ref argv<chararr[]>)Algorithms for file handling through command line argumentsPre :- Three arguments from the user as executable filename, input file and output filePost :- Converts the file in upper caseReturn :- Nil

1 if (argc != 3)2 { invalid arguments3 exit(0) }4 Opened the mentioned argv[1] in read mode5 if source file fs == NULL6 cannot open a file7 Open the destination file in write mode8 if fp == NULL9 cannot open a file10 else11 loop ( c!= eof(fs))

12 c = fgetc(fs) 13 c = toupper(c) 14 putc(c,fp)

15 end loop16 close(fs)

17 fclose(fp)

Testing:

Input :Program should be executed either from command prompt/ thru editor with arguments

as input filename and output file name.

Ex. : prg-name in.txt out.txt

Output :Each character from input file should be read, converted to uppercase and written to

output file, then o/p file is displayed to console.

Conclusion:

All functions stated above are tested and executed successfully.

Page 56: Programming Laboratory Lab_manual

Title of Assignment:

Write a program to implement a small database project to understand the concept of structures, pointers, various operations on files such as create, open, add/ modify/delete/process/append a record, search a record, sort, merge, close.Theory :

Project can be implemented in the form of any Database system, like

Payroll system

Library system

Banking system

But it should make use of all the primitive operations on files, i.e.

Add, insert, delete, search, modify, display data etc.

The database should be maintained in files and should be manipulated with all the

file operations as :

1) fopen, fread, fwrite, fseek, fclose i.e. to operate on one record at a time.

2) It should be sorted on primary key which is unique for each record.

3) Based on this key search, delete and modification should be performed.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

As per the application which is implemented, the algorithms for addRecord,

deleteRecord, searchRecord, modifyRecord, DisplayRecord should be written in this

section. Also the data structures used for storing the database should also be

mentioned.

Testing:

(Input/ Output):

Conclusion:

Assignment No. 16