You are on page 1of 56

Subject: Programming Laboratory

Work Load Exam Schemes


Theory Practical Term Work Practical Oral
02hrs per week 04hrs per week 25 50 --
List of Assignments
Time Span
Sr. No. Title of Assignment
(No. of weeks)
Write a program to perform various string operations
such as copy, length, reverse, palindrome,
1 01
concatenation and to find occurrence of a substring
using and without using library functions
Write a program to perform addition and
multiplication and transpose operations on matrix.
2 01
Write functions to determine whether the matrix is
symmetric and skewed symmetric.
Represent a polynomial using array and write a menu
3 driven program to perform addition, multiplication ½
and evaluation.
Write a program to perform various operations such
4 ½
as union and intersection on sets.
5 Write a program to compute Inverse of a matrix 01
Write a program to implement stack as an ADT using
6 ½
Arrays.
Write a program to convert the given Infix expression
7 01
to Postfix and perform evaluation.
Write a program to convert the given Infix expression
8 01
to Prefix and Prefix to Infix.
Write a program to convert the given Postfix
9 ½
expression to Infix and Postfix to Prefix.
Write a program to implement bitwise and logical
10 01
bitwise operators using stack.
Write a program to implement circular queue and
11 01
double-ended queue using arrays.
Write a program to implement Sequential and Binary
12 ½
search.
Write a program to implement following sorting
13. methods: Bubble sort, Selection Sort and Insertion 01
Sort.
Write a program to solve the system of Simultaneous
14. Equations using Cramers Rule, Gauss Seidal Rule 01
and Gauss Elimination Method.
Write a program to create a text file, read it and
15. convert into uppercase & write the contents into 01
another text file by using command line arguments
Write a program to implement a small database
project to understand the concept of structures,
16. pointers, various operations on files such as create, 02
open, add/ modify/delete/process/append a record,
search a record, sort, merge, close.

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


2 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 accepted


Post :- Length of the String should be calculated.
Return :- Length of the String.

1 accept the string


2 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[]>)


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 accepted


Post :- 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 0
4 else
5 index = 0
6 loop( not end of str1)
7 if str1(index) == str2(index)
8 index = index + 1
9 else
10 return 0
11 end loop
12 end if
13 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 accepted


Post :- Source String should be appended at the end of destination string
Return :- reference to destination String

1 index = 0
2 loop ( not end of the str1)
3 index = index + 1
4 end loop
5 index1 = 0
6 loop ( not end of str2 )
7 str1(index) = str2(index1)
8 index = index +1
9 index1 = index1 + 1
10 end loop
11 terminate destination string(str1) by ‘\0’ character
12 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
character at the end of the destination string and returns the reference to the
destination String.

Pre :- the source String should be accepted


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

1 index = 0
2 loop ( not end of the str1)
3 index = index + 1
4 end loop
5 index1 = 0
6 loop ( not end of str2 )
7 str2(index1) = str1(index)
8 index1 = index1+1
9 index = index - 1
10 end loop
11 terminate destination string(str2) by ‘\0’ character
12 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 accepted


Post :- Check for occurrence of string2 in string1.
Return :- Boolean value as a result of comparison (1/0)

1 index1 = 0
2 index2 = 0
3 loop( not end of str1)
4 index2 = 0
5 loop (not end of str2)
6 if str1(index1) == str2(index2)
7 index1 = index1 + 1
8 index2 = index2 + 1
9 else
10 goto step 12
11 end loop
12 if (end of str2(index2) )
13 flag =1
14 goto step 19
15 else
16 index1 = index1 + 1
17 endif
18 end loop
19 if flag =1
20 return 1
21 else
22 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 accepted


Post :- Result as palindrome or not a palindrome .
Return :- Boolean value as a result (1/0)

1 index1 = 0
2 index2 = strlen(str1)
3 loop( 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 loop
10 if (index1 =index2 )
11 return 1
12 else
13 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.
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 array
Eg. 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

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 Matrix
2. Multiply two matrices
3. Symmetric Matrix
4. Skew Symmetric
5. Transpose of a matrix
6. Exit

(I) Algorithm accept (ref m<int [][]>)


Pre :- Nil
Post :- Matrix should be accepted
Return :- Nil

1. Accept the rows of the matrix in r


2. Accept the columns of matrix in c
3. Enter the matrix elements
4. for ( i=0;i<r;i++)
5. for (j=0;j<c;j++)
6. accept element at m1[i][j] as no
7. end
8. 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 matrices
Return :- 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 (ref m1<int [][]>, ref m2<int[][]>, ref m3<int[][]>)

Pre :- Two matrices should be accepted.


Post :- Result of multiplication of two matrices
Return :- 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 loop
7. end loop
8. end loop
9. else
10. display Multiplication cannot be performed

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

Pre :- Matrix should be accepted.


Post :- display the matirx
Return :- 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 accepted


Post :- Status for Symmetric or not symmetric
Return :- Nil

1. for(i=0;i<r;i++)
2. for(j=0;j<c;j++)
3. m2[i][j] = m1[j][i]
4. end
5. end
6. for(i=0;i<r;i++)
7. for(j=0;j<c;j++)
8. if ( m2[i][j] == m1[i][j] )
9. flag =1
10. else
11. flag =0
12. end if
13. end
14. end
15. if (flag==1)
16. Display as Matrix is Symmetric
17. else
18. Display as Matrix is not Symmetric
19. end if

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

Pre :- Matrix should be accepted


Post :- status if Skew Symmetric or not
Return :- 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 = 1
5. else
6. flag = 0
7. i = r; j = c;
8. end if
9. end
10. end
11. if (flag == 1)
12. display as Skew Symmetric
13. else
14. Display as Not skew symmetric
(VI) Algorithm Transpose (ref m1<int [][]>)

Pre :- Matrix should be accepted.


Post :- Transpose of Matrix
Return :- Nil

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

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.
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 4
1 0
A: 2 2
3 1
4 0

Polynomial Operations:
Display menu
1. Add two polynomials
2. Multiply two polynomials
3. Evaluate the value of one polynomial
4. 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 :- Nil
Post :- Polynomial accepted
Return :- Nil

This algorithm accepts the polynomial from the user


1. Loop ( ; ch == ‘y’ || ch =’Y’; )
2. Accept the exponent in exp
3. Accept the coefficient in coef.
4. poly[exp] = poly[exp] + coef.
5. Ask user to continue or break
6. end
(II) Algorithm display(ref poly<int[]>)
This algorithm displays the polynomial

Pre :- Polynomial to be displayed


Post :- 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. else
6. printf(“%dx^%d”,poly[i],i);
7. end if
8. endif
9. 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 accepted
Post :- 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 accepted
Post :- 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 polynomial
Pre :- One polynomial should be accepted
Post :- Will evaluate the polynomial
Return :- Nil
1. Accept the value of the character x
2. Initialize sum to 0
3. for (i=0;i<10;i++)
4. k = pow(x,i)
5. Sum += poly[i] *k
6. 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.
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 C
Pre : The two integer sets should be accepted
Post : Union should be present in Result set C
Return : No of elements in C

1 Initialize flag  0 and k0


2 For i  1 to m do
3 C(k)  A(i)
4 k++
5 for j  1 to n
6 for I  1 to m and flag =0 do
7 If B(j) = A(i)
8 Then flag  1
9 end
10 If flag = 0
11 C(k)  B(j)
12 k++
13 Else
14 Flag  0
15 End elseif
16 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 C
Pre : The two integer sets should be accepted
Post : Intersection should be present in Result set C
Return : No of elements in C

1 Initialize flag  0 and k0


2 for j  1 to n
3 for i  1 to m and flag =0 do
4 If B(j) = A(i)
5 C(k)  B(j)
6 k++
7 endif
8 end
9 end
10 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.
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


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 :- Nil
Post :- Matrix should be accepted
Return :- Nil

1 Accept the rows of the matrix in r


2 Accept the columns of matrix in c
3 Enter the matrix elements
4 for ( i=0;i<r;i++)
5 for (j=0;j<c;j++)
6 accept element at m1[i][j] as no
7 end
8 end

(II) Algorithm inverse (ref m<int [][]>)


Pre :- A non-singular matrix should be accepted
Post :- Inverse of the input Matrix should be calculated
Return :- Nil

1 Call a function to Calculate Cofactor of matrix m


2 Get transpose of the cofactor matrix (Adjoint) into m2[][]
3 Get the determinant of the matrix m into D
4 for ( i=0;i<r;i++)
5 for (j=0;j<c;j++)
6 Inverse[i][j] = (1/D) * m2[i][j]
7 end
8 End
9 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 accepted
Post :- Cofactor of the input Matrix should be calculated
Return :- 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)) * Mij
5 end
6 end

end

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

Pre :- Matrix should be accepted.


Post :- display of the matrix in row-major fashion
Return :- 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 Matrix
Return :- Nil
1. for(i=0;i<r;i++)
2. for(j=0;j<c;j++)
3. m2[i][j] = m1[j][i]
4. end
5. end
6. 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.
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-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.

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()  stack
ADD(item, stack) stack
DELETE(stack)  stack
TOP(stack)  item
ISEMTS(stack)  Boolean;
for all S in stack, I in item let
ISEMTS(CREATE) ::= true
ISEMTS(ADD(i,S)) ::= false
DELETE(CREATE) ::= error
DELETE(ADD(i,S)) ::= S
TOP(CREATE) ::= error
TOP(ADD(i,S)) ::= i
end
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)
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 full


Return :- new stack

4 If ! IsFull() then
5 s.top= s.top +1
6 s.stack[s.top] = no
7 End if

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

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

Pre :- Stack should not be empty


Return :- new stack with one element popped

8 If ! IsEmpty() then
9 Element = s.stack(s.top)
10 s.top = s.top -1
11 Print the element popped
12 End if

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

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

Pre :- Stack should not be empty


Post :- 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> )
This algorithm checks whether stack is empty.

Pre :- Stack should be created


Return :- 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 created


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

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 10
After deleting 5 elements it shows stack empty.

Conclusion:
All options stated above are tested and executed successfully.
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 Expression
2) Evaluating the Postfix expressions
3) Processing of subroutine calls
4) Reversing a string
5) Checking Correctness of nested parenthesis
6) Simulating recursion
7) Parsing of computer Programs
8) Backtracking algorithms
9) 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.

Pre :- Stack should not be full


Return :- new stack

13 If ! IsFull() then
14 stop stop +1
15 sstack[stop]  no
16 End if

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

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

Pre :- Stack should not be empty


Return :- new stack

1 If ! IsEmpty() then
2 Element  sstack(stop)
3 S->top  stop -1
4 Print the element popped
5 End if

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

This algorithm checks whether stack is empty.

Pre :- Stack should be created


Return :- 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
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 E2
Return :- void

// Start scanning E from left to right


1 loop
2 x  NEXT-TOKEN(E)
3 case
4 :x = ‘\0’: while top >1 do // empty the stack
5 Print (STACK(top)); top  top -1
6 end
7 Add (‘\0’) at the end of string
8 Return
9 :x is an operand : add (x) in E2
10 :x = ‘)’ : while STACK(top) != ‘(‘ do
11 E2 = POP(STACK)
12 End
13 top  top -1
14 : else : while ISP(STACK(top)) >= ICP(x) do
15 E2 = POP(STACK)
16 End
17 Push(STACK, x)
18 End
19 Forever
20 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 right


1 top  0 // Initialize stack
2 loop
3 x  NEXT-TOKEN(E)
4 case
5 :x = ‘\0’: return // answer is at top of the stack
6 :x is an operand : call Push(STACK, x) on stack
7 :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 End
11 Forever
12 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.
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 Expression
2. Evaluating the Postfix expressions
3. Processing of subroutine calls
4. Reversing a string
5. Checking Correctness of nested parenthesis
6. Simulating recursion
7. Parsing of computer Programs
8. Backtracking algorithms
9. 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.


Pre :- Stack should not be full
Return :- new stack

1. If ! IsFull() then
2. stop stop +1
3. sstack[stop]  no
4. End if

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

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

Pre :- Stack should not be empty


Return :- new stack

1 If ! IsEmpty() then
2 Element  sstack(stop)
3 S->top  stop -1
4 Print the element popped
5 End if

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

This algorithm checks whether stack is empty.

Pre :- Stack should be created


Return :- 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


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 PREFIX ( ref E<char[]> )

This algorithm converts the given Infix expression into Prefix form.

Pre :- Infix expression should be accepted


Post :- Prefix expression should be present in E2
Return :- void

// Start scanning E from right to left


1 loop
2 x  NEXT-TOKEN(E)
3 case
4 :x = ‘\0’: while top >1 do // empty the stack
5 Print (STACK(top)); top  top -1
6 end
7 Add (‘\0’) at the end of string
8 Return
9 :x is an operand : add (x) in E2
10 :x = ‘)’ : while STACK(top) != ‘(‘ do
11 E2 = POP(STACK)
12 End
13 top  top -1
14 : else : while ISP(STACK(top)) > ICP(x) do
15 E2 = POP(STACK)
16 End
17 Push(STACK, x)
18 End
19 Forever
20 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)/G
Then 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.
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
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
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 | b2
1 1 1 0 1
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

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


Post : Result of conversion should be present in array arr[]
Return : No of bits generated should be returned

1 Initialize arr (0-15) to zeros


2 while no != 0 do
3 begin
4 arr[n]  no % 2
5 no  no/2
6 noofbits  noofbits+1
7 n  n-1
8 end
9 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 bin1


2 Call DecToBinary(n2, bin2[]) so that bin2 contains binary representation of n2 in bin2
3 for i 0 to 16
4 if bin1(i) && bin2(i)
5 bitwise&(i)  1
6 else
7 bitwise&(i)  0
8 endif
9 Call the function to print the result of bitwise & in bitwise&[].
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 bin1


2 Call DecToBinary(n2, bin2[]) so that bin2 contains binary representation of n2 in bin2
3 for i 0 to 16
4 if bin1(i) || bin2(i)
4 bitwiseOR(i)  1
5 else
6 bitwiseOR(i)  0
8 endif
9 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 bin1


2 Call DecToBinary(n2, bin2[]) so that bin2 contains binary representation of n2 in bin2
3 for i 0 to 16
4 if bin1(i) = bin2(i)
4 bitwiseXOR(i)  0
5 else
6 bitwiseOR(i)  1
8 endif
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.

(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 bin1


2 for i 0 to 16
4 if bin1(i) = 1
4 bitwiseCOMP(i)  0
5 else
6 bitwiseCOMP(i)  1
8 endif
9 Call the function to print the result of bitwise Complement in bitwiseCOMP[].
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 bin1


2 for i  0 to (15-n2) do
4 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
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) ADDQ
b) DELETEQ
c) ISEMTQ
d) ISFULLQ
e) 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 ADT
Formally 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)) ::=
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 full


Post :- New element should be added at rear end of queue.
Return :- new queue

17 Rear (rear+1) % size


18 If ! IsFull() then
19 qrear  no
20 endif

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

This algorithm will delete one element from the queue.


Pre :- Queue should not be empty
Post :- Element at front end is deleted
Return :- new queue

1. If ! IsEmpty() then
2. Element  qqueue(qfront)
3. q->front  (qfront +1)% size
4. 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 empty


Post :- 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 qqueue(qfront+1)
3 Else
4 Return -1
5 End if

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

This algorithm checks whether queue is empty.

Pre :- Queue should be created


Post :- Queue is unchanged
Return :- Boolean value true(1) if queue is empty else false(0)

1 If q.front = q.rear then


2 return 1
3 else
4 return 0
5 end if

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

This algorithm checks whether queue is full.


Pre :- Queue should be created
Return :- Boolean value true(1) if queue is full else false(0)

1 If q.front = q.rear then


2 return 1
3 else
4 return 0
End if

Testing:
If the elements are added to queue in order 10 20 30 40 50
The order in which they are deleted is 10 20 30 40 50
i.e. FIFO order is followed.
Conclusion :
All options stated above are tested and executed successfully.
Assignment No. 11b

Title of Assignment:
Write a program to implement Deque as an ADT with the following operations –
1 ADDFRONTQ
2 ADDREARQ
3 DELETEFRONTQ
4 DELETEREARQ
5 ISEMTQ
6 FRONTQ
7 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 ADT
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.
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.

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 full


Post :- New element should be added at rear end of queue.
Return :- new queue

1 Rear (rear+1) % size


2 If ! IsFull() then
3 qrear  no
4 endif

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

This algorithm will delete one element from the queue.

Pre :- Queue should not be empty


Post :- Element at front end is deleted
Return :- new queue

1 If ! IsEmpty() then
2 Element  qqueue(qfront)
3 q->front  (qfront +1)% size
4 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 empty


Post :- 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 qqueue(qfront+1)
3 Else
4 Return -1
5 End if

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

This algorithm checks whether queue is empty.

Pre :- Queue should be created


Post :- Queue is unchanged
Return :- Boolean value true(1) if queue is empty else false(0)

1 If q.front = q.rear then


2 return 1
3 else
4 return 0
5 end if

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

This algorithm checks whether queue is full.


Pre :- Queue should be created
Return :- Boolean value true(1) if queue is full else false(0)

1 If q.front = q.rear then


2 return 1
3 else
4 return 0
5 End if

Testing:
If the elements are added to queue in order 10 20 30 40 50 from rear end
The 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.
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 :- Nil
Post :- Will accept the array
Return :- Returns the total number of elements.

This algorithm accepts the integer array from user


1 Accept the total number of elements in n
2 Initialise i  0
3 loop(till i<n)
4 arr(i)  value
5 i  i+1
6 end loop
7 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 accepted
Post :- Search is successful if no is found else unsuccessful
Return :- If no found index of no is returned else return -1.

This algorithm for linear search


1 loop ( till i<len )
2 if (arr(i) = no)
3 return i
4 end loop
5 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 accepted


Post :- Search is successful if no is found else unsuccessful
Return :- 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-1


2 Initialize low  0
3 while( high >= low)
4 mid  (high + low)/2
5 if( arr(mid) = no)
return mid
6 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.
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 may
far 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
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 accepted


Post :- sorted list should be present in x
Return :- nothing

1. for pass 0 to size-1 and switched do


2. switched 0;
3. for j0 to j < (size-pass-1) do
4. 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. endif
9. end
10. end

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

This algorithm for selection sort technique.

Pre :- List of numbers should be accepted


Post :- sorted list should be present in x
Return :- nothing
for i  n-1 to i > 0 in steps of -1 do
Large= x(0)
indx = 0
for j = 1 to j <= I do
if ( x[j] > large) then
large = x(j)
indx = j
endif
end
x(indx) = x(i)
x{i) = large
end

Testing:
If the elements entered are : 67 54 34 20 12
The output of the sorting comes to be 12 20 34 54 67
So unsorted lists are getting sorted correctly in ascending order.
Conclusion:
All options stated above are tested and executed successfully.
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:

coefficient Dx: coefficient determinant


system of answer
matrix's with answer-column
equations column
determinant values 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

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:¯
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) end
6) end
7) for ( i= 1; j <=n ; j ++)
8) Read constants into B[i] array
9) 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 equations
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) end
6) end
7) for ( i= 1; j <=n ; j ++)
8) Read constants into B[i] array
9) 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 variables
16) 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.
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 Description
r Opens existing file in read mode
w New file created and written
Append existing or create new if
a
not exist.
r+ Open for read and write mode
w+ New file for read and write
Read and append existing, create
a+
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.


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);
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 arguments
Pre :- Three arguments from the user as executable filename, input file and output file
Post :- Converts the file in upper case
Return :- Nil

1 if (argc != 3)
2 { invalid arguments
3 exit(0) }
4 Opened the mentioned argv[1] in read mode
5 if source file fs == NULL
6 cannot open a file
7 Open the destination file in write mode
8 if fp == NULL
9 cannot open a file
10 else
11 loop ( c!= eof(fs))
12 c = fgetc(fs)
13 c = toupper(c)
14 putc(c,fp)
15 end loop
16 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.
Assignment No. 16

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:

You might also like