Programming Laboratory Lab - Manual
Programming Laboratory Lab - Manual
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';
This algorithm reads a Source String character by character and copies it to the
destination String.
This algorithm reads a Source String character by character and counts characters
till end of the string and returns length of the String.
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.
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)
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)
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).
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
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).
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
Examples :
Symmetric Skew-symmetric Skew-symmetric
(III) Algorithm multiplication (ref m1<int [][]>, ref m2<int[][]>, ref m3<int[][]>)
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
1. for (i=0;i<r1;i++)
2. for(j=0;j<c1;j++)
3. display matrix[i][j]
4. end
5. end
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
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 [][]>)
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.
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
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
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
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
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 commutative, associative, and distributive over each other.
(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
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
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
since
AA-1 =
Adjoint method
end
1 for (i=0;i<r1;i++)
2 for(j=0;j<c1;j++)
3 print matrix[i][j]
4 end
5 end
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:
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).
4 If ! IsFull() then
5 s.top= s.top +1
6 s.stack[s.top] = no
7 End if
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> )
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.
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.
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> )
13 If ! IsFull() then
14 stop stop +1
15 sstack[stop] no
16 End if
1 If ! IsEmpty() then
2 Element sstack(stop)
3 S->top stop -1
4 Print the element popped
5 End if
This algorithm converts the given Infix expression into Postfix form.
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.
1. If ! IsFull() then
2. stop stop +1
3. sstack[stop] no
4. End if
1 If ! IsEmpty() then
2 Element sstack(stop)
3 S->top stop -1
4 Print the element popped
5 End if
This algorithm converts the given Infix expression into Prefix form.
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;
};
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.
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
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 :
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
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:
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.
typedef struct
{
int front, rear;
data-type queue[MAX];
}QUEUE;
1. If ! IsEmpty() then
2. Element qqueue(qfront)
3. q->front (qfront +1)% size
4. Print the element deleted
5. End if
This algorithm will read the element on front end of the queue.
1 If ! IsEmtQ() then
2 return qqueue(qfront+1)
3 Else
4 Return -1
5 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:
typedef struct
{
int front, rear;
data-type queue[MAX];
}QUEUE;
1 If ! IsEmpty() then
2 Element qqueue(qfront)
3 q->front (qfront +1)% size
4 Print the element deleted
5 End if
This algorithm will read the element on front end of the queue.
1 If ! IsEmtQ() then
2 return qqueue(qfront+1)
3 Else
4 Return -1
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).
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 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.
This algorithm will sort the given list using Bubble Sort techniqe.
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.
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:
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
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.
where:¯
is the value in .
or
where:¯
is the iterative solution to , ,
is the diagonal 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.
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.
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.
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.
Testing:
(Input/ Output):
Conclusion: