You are on page 1of 73

Master of Computer Application [MCA Revised]

Second & Third Semester Assignments Submitted by Ansari Sufiyan Ahmed Abdul Wahab Roll No. : 510928906

Subject Name Subject Code Assignment No

: : :

OOPS Using C++ MC 0066 01

Q.1. With a suitable programming example explain the steps in writing and compiling a C++ program. Ans. Until now, we have only presented parts of or very small programs which could easily be handled in one file. However, greater projects, say, a calendar program, should be split into manageable pieces, and often called modules. Modules are implemented in separate files Roughly speaking, modules consist of two file types: interface descriptions and implementation files. To distinguish these types, a set of suffixes are used when compiling a program. There are many C compilers around. The cc being the default Sun compiler. The GNU C compiler gcc is popular and available for many platforms. PC users may also be familiar with the Borland bcc compiler.

There are also equivalent C++ compilers which are usually denoted by CC (note upper case CC. For example Sun provides CC and GNU GCC. The GNU compiler is also denoted by g++. Other (less common) C/C++ compilers exist. All the above compilers operate in essentially the same manner and share many common command line options. However, the best source of each compiler is through the online manual pages of your system: e.g. man cc. For the sake of compactness in the basic discussions of compiler operation we will simply refer to the cc compiler - other compilers can simply be substituted in place of cc unless otherwise stated. To compile your program simply invoke the command cc. The command must be followed by the name of the (C) program you wish to compile. A number of compiler options can be specified also. Thus, the basic compilation command is: cc program.c Where program.c is the name of the file

If there are obvious errors in your program (such as mistyping, misspelling one of the key words or omitting a semi-colon), the compiler will detect and report them. There may, of course, still be logical errors that the compiler cannot detect. You may be telling the computer to do the wrong operations. When the compiler has successfully digested your program, the compiled version, or executable, is left in a file called a.out or if the compiler option -o is used: the file listed after the -o. It is more convenient to use a -o and filename in the compilation as in cc -o program program.c Which puts the compiled program into the file program (or any file you name following the "-o" argument) instead of putting it in the file a.out. Q.2. Write your own C++ functions for the following problems: Sort a book list in a library based on the discipline Print the sorted output on the console Ans. #include <iostream> #include <conio.h> #include <iomanip> #include <cstdlib> #include <string.h> using std::cout; using std::cin; using std::endl; using std::setprecision; using std::fixed; using std::setw; void students::displayMessage() { cout << "Welcome to the Student Scores Application." << endl; } // sorts data alphabetically by last name using bubble sort void students::sortData() { for(int i = 0; i < arraySize ; i++) { for(int j = i+1; i < arraySize; j++) { if(strcmp(lastName[i]) { char *temp = lastName[i]; lastName[i] = lastName[j]; lastName[j] = temp; } } } }

// Prints all the students data void students::printData() { for (int i = 0; i < arraySize; i++) cout << "Student " << num << " last name: " << lastName[i] <<", " << firstName[i] << ": " << grades[i] << endl; } // gets the number of students the user wnats to enter and sets that as the arraysize int students::getNumstudents(int arraySize) { cout << "Enter number of students to enter: "; cin >> arraySize; } // gets students info from user void students::getData(int arraysize) { int num = 1; char*userinput1; char*userinput2; int userinput3; while ( num <= arraySize) { cout << "Student " << num << " last name: "; lastName[arraysize] = userinput1; cout << "Student " << num << " first name: "; firstName[arraysize] = userinput2; cout << "Student " << num << " score: "; grades[arraysize] = userinput3; num++ } } // function main begins program exectuion int main() { students.displayMessage(); students.getNumstudents(); students.getData(); students.sortData(); students.printData(); } Q.3. Describe the usage of Virtual functions with your own programming examples. Ans. Virtual Functions: C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. The whole function body can be replaced with a new set of implementation in the derived class. The concept of c++ virtual functions is different from C++ Function overloading. C++ virtual function is,

A member function of a class

Declared with virtual keyword Usually has a different functionality in the derived class A function call is resolved at run-time

The difference between a non-virtual c++ member function and a virtual member function is the non-virtual member functions are resolved at compile time. This mechanism is called static binding. Whereas the c++ virtual member functions are resolved during run-time. This mechanism is known as dynamic binding. The most prominent reason why a C++ virtual function will be used is to have a different functionality in the derived class. For example a Create function in a class Window may have to create a window with white background. But a class called CommandButton derived or inherited from Window may have to use a gray background and write a caption on the center. The Create function for CommandButton now should have functionality different from the one at the class called Window. Example: class Window // Base class for C++ virtual function example { public: virtual void Create() // virtual function for C++ virtual function example { cout <<"Base class Window"<<endl; } }; class CommandButton : public Window { public: void Create() { cout<<"Derived class Command Button - Overridden C++ virtual function"<<endl; } }; void main() { Window *x, *y; x = new Window(); x->Create(); y = new CommandButton(); y->Create(); } Q.4. Explain different in-built file functions in C++ and write a program to demonstrate at least 4 to 5 of these functions. Ans. File handling is an important part of all programs. Most of the applications will have their own features to save some data to the local disk and read data from the disk again. C++ File I/O classes simplify such file read/write operations for the programmer by providing easier to use classes. There are 3 File I/O classes in C++ which are used for File Read/Write operations. They are

ifstream

- Can be used for File read/input operations

ofstream fstream

- Can be used for File write/output operations - Can be used for both read/write c++ file I/O operations

The most important methods which will be used for any file operations are: 1. fstream::open method - to open the file 2. fstream::Operator >> and fstream::Operator << - For reading from or writing to the file. 3. fstream::close - Flushes all buffer and close the file Reading a text file using fstream class: There are several ways of reading the text from a file. But all of them have a common approach as follows. 1. Open the file 2. Read the data 3. Close the file This sample code snippet explains how to use the c++ file i/o stream operators to read data from a file. In all cases the header file fstream.h must be included. Example: #include<fstream.h> void main() { char str[2000]; fstream file_op("c:\\test_file.txt",ios::in); while(file_op >> str) cout << str; file_op.close(); } The class fstream, which is used above is the one which is commonly used for c++ file i/o manipulations. The constructor of fstream takes 2 parameters. One is the file path and the second is the File Open mode. There are several open modes, each of them with a different purpose. Some of them are ios::in for reading, ios::out for writing, ios::app for appending to the end of file, ios::binary for opening in binary mode etc. Now for the purpose of this article, as the data is read from the file, the flag ios::in is used. After this, the read operation is continued till the end of the file. The while loop ensures a continuous read till the end of the file or it encounters any abnormal break. If the program is built and run , it displays all the data read from the file. The C++ File I/O read job is done. But if we look at the output closely, there is a draw back in using this stream operator read. The output misses the white spaces and the end of line characters. In order not to miss these characters we can either use fstream::get() or fstream::getline() methods. Here is the example for using fstream getline method. Example: #include <fstream.h> void main() { char str[2000]; fstream file_op("c:\\test_file.txt",ios::in); while(!file_op.eof()) {

file_op.getline(str,2000); cout<<str; } file_op.close(); cout <<endl; } Writing to a text file using fstream class: Writing to a text file can also be achieved with the stream operators. This also follows the same order of operations, though with a slight difference. 1. open a file - in write mode 2. Write to a file 3. close the file Look at the following sample code to see the difference. Example: #include <fstream.h> void main() { fstream file_op("c:\\CoderSource_file.txt",ios::out); file_op<<"Test Write to file"; file_op.close(); } To modify the data or to seek to a different position inside the file, the c++ file i/o class fstream provides member functions like seekg() etc., These functions can be used to relocate the record insert position to the desired locations. After all the C++ File I/O operations we do an fstream::close(), to close the file pointer. This is not mandatory. Even if this function is not called by the application, the destructor of the fstream class will close the file when the object goes out of scope.

Subject Name Subject Code Assignment No

: : :

OOPS Using C++ MC 0066 02

Q.1. Write a program in C++ to print the domestic and international flight schedules in an airport based on the following format: SNO FLIGHT_NO ARRIVAL_TIME DEPARTURE_TIME SOURCE DESTINATION The data should be printed in a matrix format and the data storage should be using structures. Ans. class air { protected: int z; char clas[10]; char source[5][10]; char dest[5][10]; int seats; int l; public: void getdata(); int search (char c[10], char[10]); void refresh(); }; void air::getdata() { cout<<"WELCOME TO SAHARA AIRLINES"; cout<<"LIST OF SOURCES AND DESTINATION ARE>>>>"; for(int s=0;s<2;s++) { cin>>source[s]; for(int d=0;d<5;d++) { cin>>dest[d]; cin>>seats; } cout<<endl; } } int air::search(char c[10],char b[10]) { for(int p=0;p<5;p++) { if((strcmp(source[p],c)==0)) { for(int h=0;h<5;h++) { if((strcmp(dest[h],b)==0)) { cout<<"flight exists"; cout<<"enter class"<<endl; cin>>clas; cout<<"SEATS>>>>"; cout<<seats; z=seats;

return (1); } else l=1; } } else l=1; } if(l==1) cout<<"sorry no flight exists as per request"; } void air::refresh() { seats=z; } void main() { clrscr(); air a; char k; char c[10]; char b[10]; fare f; fstream n; n.open("c:/s/Dev.txt",ios::in|ios::out|ios::ate|ios::binary|ios::trunc); a.getdata(); n.write((char*)&a,sizeof(a)); fstream z; z.open("c:/s/Den.txt",ios::in|ios::out|ios::ate|ios::binary|ios::trunc); n.seekg(0,ios::beg); n.read((char*)&a,sizeof(a)); while(n) { cout<<"PLEASE ENTER UR CHOICE OF SOURCE AND DESTINATION"; cin>>c>>b; n.read((char*)&a,sizeof(a)); if( a.search(c,b)==1) { f.gets(); f.amt(); } else exit(0); } n.close(); n.open("c:/s/Dev.txt",ios::in|ios::out|ios::ate|ios::binary|ios::trunc); a.refresh(); n.write((char*)&a,sizeof(a)); getch();

} Q.2. Describe various inheritance mechanisms in C++ using appropriate programming examples. Ans. Inheritance: In object-oriented programming, inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined. The inheritance concept was invented in 1967 for Simula. The new classes, known as derived classes, take over (or inherit) attribute and behavior of the preexisting classes, which are referred to as base classes (or ancestor classes). It is intended to help reuse existing code with little or no modification. Inheritance provides the support for representation by categorization in computer languages. Categorization is a powerful mechanism number of information processing, crucial to human learning by means of generalization (what is known about specific entities is applied to a wider group given a belongs relation can be established) and cognitive economy (less information needs to be stored about each specific entity, only its particularities). Inheritance is also sometimes called generalization, because this a relationships represent a hierarchy between classes of objects. For instance, a "fruit" is a generalization of "apple", "orange", "mango" and many others. One can consider fruit to be an abstraction of apple, orange, etc. Conversely, since apples are fruit (i.e., an apple is-a fruit), apples may naturally inherit all the properties common to all fruit, such as being a fleshy container for the seed of a plant. An advantage of inheritance is that modules with sufficiently similar interfaces can share a lot of code, reducing the complexity of the program. Inheritance therefore has another view, a dual, called polymorphism, which describes many pieces of code being controlled by shared control code. Inheritance is typically accomplished either by overriding (replacing) one or more methods exposed by ancestor, or by adding new methods to those exposed by an ancestor. Complex inheritance, or inheritance used within a design that is not sufficiently mature, may lead to the Yo-yo problem. A new class can be derived from an existing class. Then the new derived class is called derived class (or sub class) and the existing class is called base class (or super class). I. Single Inheritance: When a derived class inherits only from one base class, it is known as single inheritance. II. Multiple Inheritance: When a sub class inherits from multiple base classes, it is known as multiple inheritances. For Example: Base class X Y and derived class is Z ( which is derived from both class X and Y) III. Multilevel Inheritance: When a sub class inherits from a class that itself inherits from another class, it is known as multilevel inheritance. For Example; Class X ------ Base class of Y Class Y ------ Sub class of X and Base class of Z Class Z ------ Sub class of Y IV. Hierarchical Inheritance: when many sub classes inherit from a single base class, it is known as hierarchical inheritance. For Example:

Class W Class X Class Y Class Z

------ Base class ------ Sub class or Derived class (from class W) ------ Sub class or Derived class (from class W) ------ Sub class or Derived class (from class W)

V. Hybrid Inheritance: When a subclass inherits from multiple base classes and its entire base classes inherit from a single base class, this form of inheritance is known as hybrid inheritance. For Example: Class W ------ Base class Class X & Class Y ------ Derived class (From Class W) Class Z ------ Derived class ( from class X and class Y) Q.3. Describe the following with appropriate programming examples: this pointer Friend Functions Ans. The this pointer: The this pointer is used as a pointer to the class object instance by the member function. The address of the class instance is passed as an implicit parameter to the member functions. The sample below shows how to use it. It is a common knowledge that C++ keeps only one copy of each member function and the data members are allocated memory for all of their instances. This kind of various instances of data is maintained use this pointer.

this pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class. this pointer is not counted for calculating the size of the object. this pointers are not accessible for static member functions. this pointers are not modifiable.

Example: class this_pointer_example { int data1; public: int getdata() { return this->data1; } void setdata(int newval) { data1 = newval; } }; Friend Functions: Any data which is declared private inside a class is not accessible from outside the class. A function which is not a member or an external class can never access such private data. But there may be some cases, where a programmer will need access to the private data from non-member functions and external classes. C++ offers some exceptions in such cases. A class can allow non-member functions and other classes to access its own private data, by making them as friends.

Once a non-member function is declared as a friend, it can access the private data of the class similarly when a class is declared as a friend, the friend class can have access to the private data of the class which made this a friend

Example: #include <iostream.h> int AddToFriend(int x); class CPP_Tutorial { int private_data; friend int AddToFriend(int x); public: CPP_Tutorial() { private_data = 5; } }; int AddToFriend(int x) { CPP_Tutorial var1; return var1.private_data + x; } int main() { cout << "Added Result for this C++ tutorial: "<< AddToFriend(4)<<endl; } Q.4. With the help of File operations in C++, explain the Exception handling mechanisms in C++. Ans. Exception Handling: The designers of C++, Bell labs, extended it with exception handling structures. The commands being used relate closely to the terms used in exception handling (described above). The block of code you want to try starts with specifying the try command and surrounding the block with curly braces. Within this block, you can throw any occurring errors with the throw command. You must specify an error and this should be a class but we will get to this later. Immediately after the try-block is closed, the catch-block starts. Here the error handling code is placed. The following piece of pseudo code will show the idea: try { ... ... throw Exception() ... ... } catch( Exception e ) {

... ... } In this example, Exception is a defined class with a constructor with no parameters (as identified by the throw-call). It would be useful to have some info on what kind of error occurred. This could be done in two ways. We could define different exception-classes and throw them according to which error occurred. We also could give the class a parameter containing an error message and allow the class to display the message. Such a system will be introduced in the next section. File processing in C++ is performed using the fstream class. Unlike the FILE structure, fstream is a complete C++ class with constructors, a destructor and overloaded operators. To perform file processing, you can declare an instance of an fstream object. If you do not yet know the name of the file you want to process, you can use the default constructor. Unlike the FILE structure, the fstream class provides two distinct classes for file processing. One is used to write to a file and the other is used to read from a file.

Subject Name : Subject Code :

Data Structures Using C MC 0068 01

Assignment No :

Q.1. Using the concept of structures, implement a book list as per the following specifications: A book list of C programming A book list of Java Programming A sort function to sort the books according to year of publishing Ans. Program for book list of C programming: #include<stdio.h> void main() { struct C { char name; float price; int pages; }; struct C b1, b2, b3; printf(\nEnter names, prices& no. of pages of 3 C books\n); scanf(%c %f %d, &b1.name,&b1.price,&b1.pages); scanf(%c %f %d,&b2.name,&b2.price,&b2.pages); scanf(%c %f %d, &b3.name,&b3.price,&b3.pages); printf((\nAnd this is what you entered); printf(\n%c %f %d,b1.name,b1.price,b1.pages); printf(\n%c %f %d,b2.name,b2.price,b2.pages); printf(\n%c %d %d,b3.name,b3.price,b3.pages); } Program for book list of Java programming: #include<stdio.h> void main() { struct Java { char name; int No; }; struct Java Book b1,b2,b3; printf(\Enter Names, list no of three books\n); scanf(%c %d,b1.name,b1.No); scanf(%c %d,b2.name,b2.No); scanf(%c %d,b3.name,b3.No); printf(\and this is what you entered); printf(\n%c %f,b1.name,b1.No); printf(\n%c %f,b2.name,b2.No); printf(\n%c %f,b3.name,b3.No); } Q.2. Write a program to implement circular queues using linked lists.

Ans. #include<iostream.h> class linklist { private: struct node { int data; node * link; } *front, *rear; public: linklist(); void addcirq (int item); int delcirq(); void cirq_display(); ~linklist(); }; linklist :: linklist() { front = rear = NULL; } void linklist :: addcirq (int item) { node *q; q = new node; q -> data = item; if (front == NULL) front = q; else rear -> link = q; rear = q; rear -> link = front; } int linklist :: delcirq() { node *q; int item; if (front == NULL) cout << "\nqueue is empty"; else { if (front == rear) { item = front -> data; delete front; front = NULL; rear = NULL; }

else { q = front; item = q -> data; front = front -> link; rear -> link = front; delete q; } return (item); } return NULL; } void linklist :: cirq_display() { node *q, *p; q = front; p = NULL; cout << endl; while (q != p) { cout << q -> data << " "; q = q -> link; p = front; } } linklist :: ~linklist() { node *q; while (front != rear) { q = front -> link; delete front; front = q; } delete rear; } void main() { linklist l; l.addcirq(10); l.addcirq(17); l.addcirq(18); l.addcirq(5); l.addcirq(30); l.addcirq(15); cout << "\nElements in linked list before deletion: "; l.cirq_display(); l.delcirq(); l.delcirq();

l.delcirq(); cout << "\nElements in linked list after deletion: "; l.cirq_display (); } Q.3. Write the functions to implement: AVL Trees Insertion and deletion into red-black trees Ans. AVL Trees: An AVL tree is a self-balancing binary search tree, and it is the first such data structure to be invented. In an AVL tree, the heights of the two child sub trees of any node differ by at most one; therefore, it is also said to be height-balanced. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. The AVL tree is named after its two inventors, G.M. Adelson-Velskii and E.M. Landis, who published it in their 1962 paper "An algorithm for the organization of information." The balance factor of a node is the height of its right sub tree minus the height of its left sub tree and a node with balance factor 1, 0, or -1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the sub trees. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. AVL trees perform better than red-black trees for lookup-intensive applications. The AVL tree balancing algorithm appears in many computer science curricula. Insertion and Deletion into Red-Black Trees: Insertion begins by adding the node much as we would in a simple binary search tree and coloring it red. Whereas in the binary search tree, we always add a leaf, in the red-black tree leaves contain no information, so instead we add a red interior node, with two black leaves, in place of an existing black leaf. What happens next depends on the color of other nearby nodes. The term uncle node will be used to refer to the sibling of a node's parent, as in human family trees. Note that:

Property 3 (All leaves are black) always holds. Property 4 (Both children of every red node are black) is threatened only by adding a red node, repainting a black node red, or a rotation. Property 5 (All paths from any given node to its leaf nodes contain the same number of black nodes) is threatened only by adding a black node, repainting a red node black, or a rotation.

Note: The label N will be used to denote the node being inserted; P will denote N's parent node, G will denote N's grandparent, and U will denote N's uncle. Note that in between some cases, the roles and labels of the nodes are exchanged, but in each case, every label continues to represent the same node it represented at the beginning of the case. Any color shown in the diagram is either assumed in its case or implied by these assumptions. In a normal binary search tree, when deleting a node with two non-leaf children, we find either the maximum element in its left sub tree or the minimum element in its right sub tree, and move its value into the node being deleted (as shown here). We then delete the node we copied the value from, which must have less than two non-leaf children. Because merely copying a value does not violate any red-black properties, this reduces the problem of deleting to the problem of deleting a

node with at most one non-leaf child. It does not matter whether this node is the node we originally wanted to delete or the node we copied the value from. For the remainder of this discussion we can assume we are deleting a node with at most one nonleaf child, which we will call its child (if it has only leaf children, let one of them be its child). If we are deleting a red node, we can simply replace it with its child, which must be black. All paths through the deleted node will simply pass through one less red node, and both the deleted node's parent and child must be black, so properties 3 (All leaves, including nulls, are black) and 4 (Both children of every red node are black) still hold. Another simple case is when the deleted node is black and its child is red. Simply removing a black node could break Properties 4 (Both children of every red node are black) and 5 (All paths from any given node to its leaf nodes contain the same number of black nodes), but if we repaint its child black, both of these properties are preserved. Q.4. Discuss the following: Sub Graphs Special Graphs Ans. Sub Graphs: A graph G'=(V', E') is a sub graph of another graph G=(V, E) iff

V' V, and E' E ((v1, v2) E' v1, v2 V').

Note: In general, a sub graph need not have all possible edges. If a sub graph has every possible edge, it is an induced sub graph. Special Graphs: An undirected graph is said to be a tree if it contains no cycles and is connected.

1. Rooted Tree Many trees are what is called rooted where there is a notion of the top
node, which is called the root. Thus, each node has one parent, which is the adjacent node which is closer to the root, and may have any number of children, which are the rest of the nodes adjacent to it. The tree above was drawn as rooted tree. 2. Forest An undirected graph which contains no cycles is called forest. A directed a cyclic graph is often referred to as a dag. 3. Complete Graph A graph is said to be complete if there is an edge between every pair of vertices. Birpartite Graph A graph is said to be bipartite if the vertices can be split into two sets V1 and V2 such there are no edges betwee4n two vertices of V1 or two vertices of V2.

Subject Name : Subject Code :

Data Structures Using C MC 0068 02

Assignment No :

Q.1. Write a program in C using pointers to implement the following operations on a Binary Search Tree (BST): Finding the maximum and minimum values in the BST Finding the height of a BST Count the number of nodes in a BST Ans. #include<stdio.h> #include<stdlib.h> #include<conio.h> struct searchtree { int element; struct searchtree *left,*right; }*root; typedef struct searchtree *node; typedef int ElementType; node insert(ElementType, node); node delet(ElementType, node); void makeempty(); node findmin(node); node findmax(node); node find(ElementType, node); void display(node, int); void main() { int ch; ElementType a; node temp; makeempty(); while(1) { printf("\n1. Insert\n2. Delete\n3. Find min\n4. Find max\n5. Find\n6. Display\n7. Exit\nEnter Your Choice : "); scanf("%d",&ch); switch(ch) { case 1: printf("Enter an element : "); scanf("%d", &a); root = insert(a, root); break; case 2: printf("\nEnter the element to delete : "); scanf("%d",&a); root = delet(a, root); break; case 3: printf("\nEnter the element to search : "); scanf("%d",&a); temp = find(a, root); if (temp != NULL) printf("Element found");

else printf("Element not found"); break; case 4: temp = findmin(root); if(temp==NULL) printf("\nEmpty tree"); else printf("\nMinimum element : %d", temp->element); break; case 5: temp = findmax(root); if(temp==NULL) printf("\nEmpty tree"); else printf("\nMaximum element : %d", temp->element); break; case 6: if(root==NULL) printf("\nEmpty tree"); else display(root, 1); break; case 7: exit(0); default: printf("Invalid Choice"); } } } node insert(ElementType x,node t) { if(t==NULL) { t = (node)malloc(sizeof(node)); t->element = x; t->left = t->right = NULL; } else { if(x < t->element) t->left = insert(x, t->left); else if(x > t->element) t->right = insert(x, t->right); } return t; } node delet(ElementType x,node t) { node temp; if(t == NULL) printf("\nElement not found"); else {

if(x < t->element) t->left = delet(x, t->left); else if(x > t->element) t->right = delet(x, t->right); else { if(t->left && t->right) { temp = findmin(t->right); t->element = temp->element; t->right = delet(t->element,t->right); } else if(t->left == NULL) t=t->right; else t=t->left; } } return t; } void makeempty() { root = NULL; } node findmin(node temp) { if(temp == NULL || temp->left == NULL) return temp; return findmin(temp->left); } node findmax(node temp) { if(temp==NULL || temp->right==NULL) return temp; return findmin(temp->right); } node find(ElementType x, node t) { if(t==NULL) return NULL; if(x<t->element) return find(x,t->left); if(x>t->element) return find(x,t->right); return t; } void display(node t,int level) { int i; if(t) {

display(t->right, level+1); printf(\n); for(i=0;i<level;i++) printf(" "); printf("%d", t->element); display(t->left, level+1); } } Q.2. Write functions in C to find the minimum cost spanning tree using the following algorithms: Prims algorithm Kruskals Algorithm Ans. Prims Algorithm Program: #define MAX 10 #define TEMP 0 #define PERM 1 #define FALSE 0 #define TRUE 1 #define infinity 9999 struct node { int predecessor; int dist; /*Distance from predecessor */ int status; }; struct edge { int u; int v; }; int adj[MAX][MAX]; int n; main() { int i,j; int path[MAX]; int wt_tree,count; struct edge tree[MAX]; create_graph(); printf("Adjacency matrix is :\n"); display(); count = maketree(tree,&wt_tree); printf("Weight of spanning tree is : %d\n", wt_tree); printf("Edges to be included in spanning tree are : \n"); for(i=1;i<=count;i++) {

printf("%d->",tree[i].u); printf("%d\n",tree[i].v); } }/*End of main()*/ create_graph() { int i,max_edges,origin,destin,wt; printf("Enter number of vertices : "); scanf("%d",&n); max_edges=n*(n-1)/2; for(i=1;i<=max_edges;i++) { printf("Enter edge %d(0 0 to quit) : ",i); scanf("%d %d",&origin,&destin); if((origin==0) && (destin==0)) break; printf("Enter weight for this edge : "); scanf("%d",&wt); if( origin > n || destin > n || origin<=0 || destin<=0) { printf("Invalid edge!\n"); i--; } else { adj[origin][destin]=wt; adj[destin][origin]=wt; } }/*End of for*/ if(i { printf("Spanning tree is not possible\n"); exit(1); } }/*End of create_graph()*/ display() { int i,j; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf("%3d",adj[i][j]); printf("\n"); } }/*End of display()*/ int maketree(struct edge tree[MAX],int *weight) { struct node state[MAX]; int i,k,min,count,current,newdist; int m; int u1,v1;

*weight=0; /*Make all nodes temporary*/ for(i=1;i<=n;i++) { state[i].predecessor=0; state[i].dist = infinity; state[i].status = TEMP; } /*Make first node permanent*/ state[1].predecessor=0; state[1].dist = 0; state[1].status = PERM; /*Start from first node*/ current=1; count=0; /*count represents number of nodes in tree */ while( all_perm(state) != TRUE ) /*Loop till all the nodes become PERM*/ { for(i=1;i<=n;i++) { if ( adj[current][i] > 0 && state[i].status == TEMP ) { if( adj[current][i] < state[i].dist ) { state[i].predecessor = current; state[i].dist = adj[current][i]; } } }/*End of for*/ /*Search for temporary node with minimum distance and make it current node*/ min=infinity; for(i=1;i<=n;i++) { if(state[i].status == TEMP && state[i].dist < min) { min = state[i].dist; current=i; } }/*End of for*/ state[current].status=PERM; /*Insert this edge(u1,v1) into the tree */ u1=state[current].predecessor; v1=current; count++; tree[count].u=u1; tree[count].v=v1; /*Add wt on this edge to weight of tree */ *weight=*weight+adj[u1][v1]; }/*End of while*/ return (count); }/*End of maketree()*/

/*This function returns TRUE if all nodes are permanent*/ int all_perm(struct node state[MAX] ) { int i; for(i=1;i<=n;i++) if( state[i].status == TEMP ) return FALSE; return TRUE; }/*End of all_perm()*/ Kruskals Algorithm Program: #include #include #include #define ESIZE 20 #define VSIZE 40 typedef struct node { int sv,dv,wt; }edgelist; edgelist graphmat[ESIZE]; edgelist ktree[ESIZE]; int nvertex,nedges,oedges,adjmat[VSIZE][VSIZE],parent[VSIZE]; int checkdir(); void creategraph(); void sortgraph(edgelist graphmat[ESIZE],int nedges); int viewsortgraph(edgelist graphmat[ESIZE],int nedges); int viewsortgraph1(edgelist graphmat[ESIZE],int nedges); void kruskal(edgelist graphmat[ESIZE],edgelist ktree[ESIZE]); void converttograph(int adjmat[VSIZE][VSIZE],int n,edgelist graphmat[ESIZE]); void main() { int wt; clrscr(); cout<<"\n\n\t\t KRUSKAL ALGORITHM"; cout<<"\n\n\t\t *****************\n\n\n"; creategraph(); converttograph(adjmat,nvertex,graphmat); viewsortgraph1(graphmat,nedges); sortgraph(graphmat,nedges); viewsortgraph1(graphmat,nedges); kruskal(graphmat,ktree); cout<<"\n\n Final kruskal tree "; cout<<"\n ~~~~~~~~~~~~~~~~~~\n\n\n"; wt=viewsortgraph(ktree,oedges); cout<<"\n\n Weight of the spanning tree is:"< getch(); } void creategraph() { int r,c; cout<<"\n\n\n Enter the no. of vertices of weighted graph:"; cin>>nvertex; cout<<"\n Enter the cost matrix\n\n";

for(r=0;r for(c=0;c cin>>adjmat[r][c]; } int checkdir() { int r,c; for(r=0;r for(c=0;c if(adjmat[r][c]!=adjmat[c][r]) return 1; return 0; } void converttograph(int adjmat[VSIZE][VSIZE],int n,edgelist graphmat[ESIZE]) { int r,c; nedges=0; for(r=0;r for(c=(checkdir()?0:r+1);c if(adjmat[r][c]!=0) { graphmat[nedges].sv=r+1; graphmat[nedges].dv=c+1; graphmat[nedges].wt=adjmat[r][c]; nedges++; } } void sortgraph(edgelist graphmat[ESIZE],int nedges) { int i,j; edgelist te; for(i=0;i for(j=i+1;j if(graphmat[i].wt>graphmat[j].wt) { te=graphmat[i]; graphmat[i]=graphmat[j]; graphmat[j]=te; } } int viewsortgraph1(edgelist graphmat[ESIZE],int nedges) { int ed,wt=0; for(ed=0;ed { wt=wt+graphmat[ed].wt; } return wt; } int viewsortgraph(edgelist graphmat[ESIZE],int nedges) { int ed,wt=0; for(ed=0;ed { cout<<"\n v"<<<"to v"<<<" -->"<

wt=wt+graphmat[ed].wt; } return wt; } void kruskal(edgelist graphmat[ESIZE],edgelist ktree[ESIZE]) { int ed=0,v,v1,v2,pv1,pv2; while(oedges { v1=graphmat[ed].sv; v2=graphmat[ed].dv; while(v1!=0) { pv1=v1; v1=parent[v1]; } while(v2!=0) { pv2=v2; v2=parent[v2]; } if(pv1!=pv2) { ktree[oedges++]=graphmat[ed]; parent[pv2]=pv1; } ed++; } } Q.3. Write a program to implement the n queens problem Ans. #include <iostream.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> void check(int, int, char [100][100]); void print(char [100][100]); int no_of_queens, queen = 2, flagrow = 0, flagcol = 0; int count = 1; char ch, response_row, response_col; int main(void) { int row, col, i; char board[100][100], response; clrscr(); printf(" @@ This is n-queen problem. Enter the number of queens(say n) and watch how computer places them

in (n x n) matrix such that none can meet another moving along horizontally, vertically or digonally. "); printf(" Enter the number of queens : "); scanf("%d", &no_of_queens); if(no_of_queens > 23) { printf(" @@ Thought the program is OK for any queen value.But due the configuration of the output screen the output will be tranketed (A very large queen number may cause the system stack overflow). So it is highly recommended that you run the program with maximum queen number 23..."); printf(" Want to continue(Y/N)?"); fflush(stdin); scanf("%c", &response); if(toupper(response) == 'N') return (0); } else if(no_of_queens < 3) { printf("The number of Queen must be greater than 3."); getch(); return (0); } printf("Want a row number below the board(Y/N) : "); fflush(stdin); response_row = (char)getchar(); if(toupper(response_row) == 'Y') flagrow = 1; printf("Want a column number below the board(Y/N) : "); fflush(stdin); response_col = (char)getchar(); if(toupper(response_col) == 'Y') flagcol = 1; clrscr(); printf("M/c in work ! Please Wait...");

// This for-loop is used for checking all the columns of row 0 only... _setcursortype(_NOCURSOR); for(col = 0; col < no_of_queens; col++) { memset(board, '-', sizeof(board)); check( 0, col, board ); } clrscr(); printf("Thank you for seeing this program through."); getch(); return (0); } void check( int r, int c, char board[100][100] ) { int i, j; // Terminating condition for the recursion... if ( ( r == no_of_queens ) && ( c == 0 )) { clrscr(); printf(" (%d-Queen) Set : %d ", no_of_queens, count++); print( board ); fflush(stdin); ch = (char)getch(); clrscr(); if(ch == 'e') exit (0); printf("M/c in work ! Please Wait..."); } // Vertical check... for(i = 0; i < r; i++) { if ( board[i][c] == queen) return; } // Horizontal check... for(j = 0; j < c; j++) { if ( board[r][j] == queen) return; } // Left-Diagonal check... i = r; j = c; do { if ( board[i][j] == queen ) return; i--; j--; } while( i >= 0 && j >= 0 );

// Right-Diagonal check... i = r; j = c; do { if ( board[i][j] == queen ) return; i--; j++; } while( i >= 0 && j < no_of_queens ); // Placing the queen if the ckecked position is OK... board[r][c] = queen; r++; // This for-loop is used for checking all the columns for each row //starting from 1 upto the end... for(int p = 0; p < no_of_queens; p++) check(r, p, board); for(int h = 0; h < no_of_queens; h++) board[r - 1][h] = '-'; } void print(char board[100][100]) { for(int i = 0; i < no_of_queens; i++) { if(flagrow == 1) printf("%3d", i + 1); for(int j = 0; j < no_of_queens; j++) { if(board[i][j] == queen) { textcolor(RED); cprintf("%3c", queen); } else { textcolor(8); //dark gray cprintf("%3c", 22); } } printf(" "); } textcolor(7); if(flagcol == 1) { if(flagrow) printf(" "); for(i = 0; i < no_of_queens; i++) printf("%3d", i + 1); }

gotoxy(62, 1); printf("Press E to exit."); textcolor(7); } Q.4. Discuss the following theorems with respect to Splay Trees: Balance Theorem Dynamic Finger Theorem Ans. A splay tree is a self-balancing binary search tree with the additional property that recently accessed elements are quick to access again. It performs basic operations such as insertion, lookup and removal in O(log(n)) amortized time. For many non-uniform sequences of operations, splay trees perform better than other search trees, even when the specific pattern of the sequence is unknown. The splay tree was invented by Daniel Sleator and Robert Tarjan. All normal operations on a binary search tree are combined with one basic operation, called splaying. Splaying the tree for a certain element rearranges the tree so that the element is placed at the root of the tree. One way to do this is to first perform a standard binary tree search for the element in question, and then use tree rotations in a specific fashion to bring the element to the top. Alternatively, a top-down algorithm can combine the search and the tree reorganization into a single phase. Good performance for a splay tree depends on the fact that it is self-balancing, and indeed self optimizing, in that frequently accessed nodes will move nearer to the root where they can be accessed more quickly. This is an advantage for nearly all practical applications, and is particularly useful for implementing caches and garbage collection algorithms; however it is important to note that for uniform access, a splay tree's performance will be considerably (although not asymptotically) worse than a somewhat balanced simple binary search tree. Splay trees also have the advantage of being considerably simpler to implement than other selfbalancing binary search trees, such as red-black trees or AVL trees, while their average-case performance is just as efficient. Also, splay trees do not need to store any bookkeeping data, thus minimizing memory requirements. However, these other data structures provide worst-case time guarantees, and can be more efficient in practice for uniform access. One worst case issue with the basic splay tree algorithm is that of sequentially accessing all the elements of the tree in the sorted order. This leaves the tree completely unbalanced (this takes n accesses - each a O(log n) operation). Re-accessing the first item triggers an operation that takes O(n) operations to rebalance the tree before returning the first item. This is a significant delay for that final operation, although the amortized performance over the entire sequence is actually O(log n). However, recent research shows that randomly rebalancing the tree can avoid this unbalancing effect and give similar performance to the other self-balancing algorithms. Balance Theorem: The cost of performing the sequence S is O(m(logn + 1) + nlogn). In other words, splay trees perform as well as static balanced binary search trees on sequences of at least n accesses. Dynamic Finger Theorem: The cost of performing S is

Subject Name : System Analysis & Design (SAD) Subject Code : MC 0069

Assignment No : 01

Q.1. What are the three kinds of building blocks of the UML? Ans. Building Blocks of UML: The building blocks of UML can be defined as:

Things Relationships Diagrams

1) Things: Things are the most important building blocks of UML. Things can be:

Structural Behavioral Grouping Annotational

Structural things: The Structural things define the static part of the model. They represent physical and conceptual elements. Following are the brief descriptions of the structural things. Class: Class represents set of objects having similar responsibilities.

Interface: Interface defines a set of operations which specify the responsibility of a class.

Collaboration: Collaboration defines interaction between elements.

Use case: Use case represents a set of actions performed by a system for a specific goal.

Component: Component describes physical part of a system.

Node: A node can be defined as a physical element that exists at run time.

Behavioral things: A behavioral thing consists of the dynamic parts of UML models. Following are the behavioral things:

Interaction: Interaction is defined as a behavior that consists of a group of messages exchanged among elements to accomplish a specific task.

State machine: State machine is useful when the state of an object in its life cycle is important. It defines the sequence of states an object goes through in response to events. Events are external factors responsible for state change.

Grouping things: Grouping things can be defined as a mechanism to group elements of a UML model together. There is only one grouping thing available: Package: Package is the only one grouping thing available for gathering structural and behavioral things.

Annotational things: Annotational things can be defined as a mechanism to capture remarks, descriptions, and comments of UML model elements. Note is the only one Annotational thing available. Note: A note is used to render comments, constraints etc of an UML element.

2) Relationship: Relationship is another most important building block of UML. It shows how elements are associated with each other and this association describes the functionality of an application. There are four kinds of relationships available. Dependency: Dependency is a relationship between two things in which change in one element also affects the other one.

Association: Association is basically a set of links that connects elements of an UML model. It also describes how many objects are taking part in that relationship. Generalization: Generalization can be defined as a relationship which connects a specialized element with a generalized element. It basically describes inheritance relationship in the world of objects.

Realization: Realization can be defined as a relationship in which two elements are connected. One element describes some responsibility which is not implemented and the other one implements them. This relationship exists in case of interfaces.

3) UML Diagrams: UML diagrams are the ultimate output of the entire discussion. All the elements, relationships are used to make a complete UML diagram and the diagram represents a system. The visual effect of the UML diagram is the most important part of the entire process. All the other elements are used to make it a complete one. UML includes the following nine diagrams and the details are described in the following chapters. 1. 2. 3. 4. 5. 6. 7. 8. 9. Class diagram Object diagram Use case diagram Sequence diagram Collaboration diagram Activity diagram State chart diagram Deployment diagram Component diagram

Q.2. Explain with an example the three kinds of relationships that are most important in object oriented modeling. Ans. Object Oriented Modeling: Object-Oriented Modeling, or OOM, is a modeling paradigm mainly used in computer programming. Prior to the rise of OOM, the dominant paradigm was procedural programming, which emphasized the use of discreet reusable code blocks that could stand on their own, take variables, perform a function on them, and return values. The Object-Oriented paradigm assists the programmer to address the complexity of a problem domain by considering the problem not as a set of functions that can be performed but primarily as a set of related, interacting Objects. The modeling task then is specifying, for a specific context, those Objects (or the Class the Objects belongs to), their respective set of Properties and Methods, shared by all Objects members of the Class. For more discussion, see Object-oriented analysis and design and Object-oriented programming. The description of these Objects is a Schema. As an example, in a model of a Payroll System, a Company is an Object. An Employee is another Object. Employment is a Relationship or Association. An Employee Class (or Object for simplicity) has Attributes like Name, Birth date, etc. The Association itself may be considered as an Object, having Attributes, or Qualifiers like Position, etc. An Employee Method may be Promote, Raise, etc. The Model description or Schema may grow in complexity to require a Notation. Many notations have been proposed, based on different paradigms, diverged, and converged in a more popular one known as UML. An informal description or a Schema notation is translated by the programmer or a CASE tool in the case of Schema notation (created using a Module specific to the CASE tool application) into a specific programming language that supports object-oriented programming (or a Class Type), a declarative language or into a database schema. Q.3. What is the role of constraints in UML? Explain with suitable examples.

Ans. UML Constraints: In UML models, a constraint is an extension mechanism that enables you to refine the semantics of a UML model element. A constraint refines a model element by expressing a condition or a restriction in a textual statement to which the model element must conform. An example of a constraint is a condition such as an attribute having a specific value. A constraint must be enforced in the design of a system. You specify the condition or restriction in the body of the constraint. Typically, constraints do not have names. Instead, they are identified by the contents of their bodies. Some commonly used constraints are identified by names so that the contents of their bodies do not have to be repeated. The XOR constraint is applied when more than one association has a common connection to one class. You can specify the language that you use to write the body of a constraint so that others who read the constraint can more easily understand its condition or restriction. You can write the body of a constraint in the following languages:

Natural languages such as English Programming languages Mathematical notations Object Constraint Language (OCL)

For more information about OCL, read the Unified Modeling Language (UML) specification that is available on the Object Management Group (OMG) Web site. In general, syntax for the body or body language properties is not enforced. A constraint is displayed as text enclosed in braces ({}) and appears in a rectangle with a folded upper-right corner. You can add constraints to your model for the following purposes:

In models that depict software systems, constraints represent conditions or restrictions that you can find no other way to model. In models that depict time-critical software systems, constraints provide a statement about the relative or absolute value of time during an interaction.

The constraints in a model can appear in any type of UML diagram as well as in freeform diagrams. Constraint validation: You can validate a constraint. The level of validation that occurs depends on the type of constraint being validated. There are three types of constraints:

A constraint with the metaConstraint stereotype applied. A constraint defined in a profile. A constraint that does not have the metaConstraint stereotype applied and is not defined in a profile.

The syntax and the expression of a constraint are validated if the constraint has the metaConstraint stereotype applied to it or if it is defined in a profile. Only the syntax of a constraint is validated if it does not have the metaConstraint stereotype applied to it and it is not defined in a profile. Q.4. What are the important factors that need to be considered to model a system from different views? Ans. Modeling Different Views of a System: When you model a system from different views, you are in effect constructing your system simultaneously from multiple dimensions. By choosing the

right set of views, you set up a process that forces you to ask good questions about your system and to expose risks that need to be attacked. If you do a poor job of choosing these views or if you focus on one view at the expense of all others, you run the risk of hiding issues and deferring problems that will eventually destroy any chance of success. To model your system from different views:

Decide which views you need to best express the architecture of your system and to expose the technical risks to your project. The five views of an architecture described earlier are a good starting point. For each of these views, decide which artifacts you need to create to capture the essential details of that view. For the most part, these artifacts will consist of various UML diagrams. As part of your process planning, decide which of these diagrams you will want to put under some sort of formal or semi formal control. These are the diagrams for which youll want to schedule reviews and to preserve as documentation for the project. Allow room for diagrams that are thrown away. Such transitory diagrams are still useful for exploring the implications of your decisions and for experimenting with changes.

For example, if you are modeling a simple monolithic application that runs on a single machine, you might need only the following handful of diagrams.

Use case view use case diagrams Design view class diagrams (for structural modeling)

Interaction diagrams (for behavioral modeling)


Process view Implementation view Deployment view

None required None required None required

Q.5. What are the issues to be considered to model collaboration? Ans. Modeling Simple Collaboration: No class stands alone. Rather, each works in collaboration with others to carry out some semantics greater than each individual. Therefore, in addition to capturing the vocabulary of your system, youll also need to turn your attention to visualizing, specifying, constructing, and documenting the various ways these things in your vocabulary work together. You use class diagrams to represent such collaborations. When you create a class diagram, you just model a part of the things and relationships that make up your systems design view. For this reason, each class diagram should focus on one collaboration at a time. To model collaboration:

Identify the mechanism youd like to model. A mechanism represents some function or behavior of the part of the system you are modeling that results from the interaction of a society of classes, interfaces, and other things. For each mechanism, identify the classes, interfaces and other collaborations that participate in this collaboration. Identify the relationships among these things as well. Use scenarios to walk through these things. Along the way, youll discover parts of your model that were missing and parts that were just plain semantically wrong. Be sure to populate these elements with their contents. For classes, start with getting a good balance of responsibilities. Then, over time, turn these into concrete attributes and operations.

There are many more classes involved in this system, but this diagram focuses only on those abstractions that are directly involved in moving the robot. Youll see some of these same classes

in other diagrams. For example, although not shown here, the class PathAgent collaborates with at feast two other classes (Environment and GoalAgent) in a higher-level mechanism for managing the conflicting goals the robot might have at a given moment. Similarly, also not shown here, the classes CollisionSensor and Driver (and its parts) collaborate with another class (FaultAgent) in a mechanism responsible for continuously checking the robots hardware for errors. By focusing on each of these collaborations in different diagrams, you provide an understandable view of the system from several angles. Q.6. Explain the different stages to model a flow of control. Ans. Modeling Flow of Control: The most common purpose for which youll use interactions is to model the flow of control that characterizes the behavior of a system as a whole, including use cases, patterns, mechanisms, and frameworks, or the behavior of a class or an individual operation. Whereas classes, interfaces, components, nodes, and their relationships model the static aspects of your system, interactions model its dynamic aspects. When you model an interaction, you essentially build a storyboard of the actions that take place among a set of objects. Techniques such as CRC cards are particularly useful in helping you to discover and think about such interactions. To model a flow of control:

Set the context for the interaction, whether it is the system as a whole, a class or and individual operation. Set the stage for the interaction by identifying which objects play a role: set their initial properties, including their attribute values, state, and role. If your model emphasizes the structural organization of these objects, identify the links that connect them, relevant to the paths of communication that take place in this interaction. Specify the nature of the links using the UMLs standard stereotypes and constraints, as necessary. In time order, specify the messages that pass from object to object. As necessary, distinguish the different kinds of messages: include parameters and return values to convey the necessary details of this interaction. Also to convey the necessary detail of this interaction, adorn each object at every moment in time with its state and role.

Subject Name : System Analysis & Design (SAD) Subject Code : MC 0069

Assignment No : 02

Q.1. Explain the role of realization with an example. Ans. Realization shows the relationship between an Interface the class that provides the implementation for the interface. We can implement this in UML using a closed, hollow arrowhead pointing from the implementation class to the interface with a dashed line. Interface in UML: Similar to Class Diagram Structure in UML, we can show Interface Class in UML.

Realization Example: Interface Code: public interface Mammals { public String walk(); } Interface Implementation Class: public class Cats implements Mammals { public String walk() { return "Have Instructed Cats to Perform Walk Operation"; } } public class Dogs implements Mammals { public String walk() { return "Have Instructed Dogs to Perform Walk Operation"; } } Realization UML Diagram:

Q.2. Discuss the concept of dynamic modeling. How is it different from static modeling? Ans. The dynamic model is used to express and model the behavior of the system over time. It includes support for activity diagrams, state diagrams, sequence diagrams and extensions including business process modeling. Sequence Diagrams: Sequence diagrams are used to display the interaction between users, screens, objects and entities within the system. It provides a sequential map of message passing between objects over time. Frequently these diagrams are placed under Use Cases in the model to illustrate the use case scenario - how a user will interact with the system and what happens internally to get the work done. Often, the objects are represented using special stereotyped icons, as in the example below. The object labeled Login Screen is shown using the User Interface icon. The object labeled SecurityManager is shown using the Controller icon. The Object labeled users is shown using the Entity icon. Activity Diagrams: Activity diagrams are used to show how different workflows in the system are constructed, how they start and the possibly many decision paths that can be taken from start to finish. They may also illustrate the where parallel processing may occur in the execution of some activities. State Charts: State charts are used to detail the transitions or changes of state an object can go through in the system. They show how an object moves from one state to another and the rules that govern that change. State charts typically have a start and end condition. Process Model: A process model is a UML extension of an activity diagram used to model a business process - this diagram shows what goal the process has, the inputs, outputs, events and information that are involved in the process. Q.3. Define diagrams and how do you make use of these in modeling? Ans. Each UML diagram is designed to let developers and customers view a software system from a different perspective and in varying degrees of abstraction. UML diagrams commonly created in visual modeling tools include:

Use Case Diagrams: A use case is a set of scenarios that describing an interaction between a user and a system. A use case diagram displays the relationship among actors and use cases. The two main components of a use case diagram are use cases and actors.

Class Diagrams: Class diagrams are widely used to describe the types of objects in a system and their relationships. Class diagrams model class structure and contents using design elements such as classes, packages and objects. Class diagrams describe three different perspectives when designing a system, conceptual, specification, and implementation. These perspectives become evident as the diagram is created and help solidify the design. This example is only meant as an introduction to the UML and class diagrams. If you would like to learn more see the Resources page for more detailed resources on UML. Classes are composed of three things: a name, attributes, and operations. Below is an example of a class.

Interaction Diagrams: Interaction diagrams model the behavior of use cases by describing the way groups of objects interact to complete the task. The two kinds of interaction diagrams are sequence and collaboration diagrams. This example is only meant as an introduction to the UML and interaction diagrams. If you would like to learn more see the Resources page for a list of more detailed resources on UML. State Diagrams: Use state diagrams to demonstrate the behavior of an object through many use cases of the system. Only use state diagrams for classes where it is necessary to understand the behavior of the object through the entire system. Not all classes will require a state diagram and state diagrams are not useful for describing the collaboration of all objects in a use case. State diagrams are other combined with other diagrams such as interaction diagrams and activity diagrams. Activity Diagrams: Activity diagrams describe the workflow behavior of a system. Activity diagrams are similar to state diagrams because activities are the state of doing something. The diagrams describe the state of activities by showing the sequence of activities performed. Activity diagrams can show activities that are conditional or parallel. Physical Diagrams: There are two types of physical diagrams: deployment diagrams and component diagrams. Deployment diagrams show the physical relationship between hardware and software in a system. Component diagrams show the software components of a system and how they are related to each other. These relationships are called dependencies.

Q.4. What are the necessary considerations to be taken care to forward engineer a class diagram? Ans. Forward engineering is the process of transforming a model into code through a mapping to an implementation language. Forward engineering results in a loss of information, because models written in the UML are semantically richer than any current object oriented programming language. In fact, this is a major reason why you need models in addition to code. Structural features, such as collaborations, and behavioral features, such as interactions, can be visualized clearly in the UML, but not so clearly from raw code. To forward engineer a class diagram:

Identify the rules for mapping to your implementation language or languages of choice. This is something youll want to do for your project or your organization as a whole. Depending on the semantics of the languages you choose, you may have to constrain your use of certain UML features. For example, the UML permits you to model multiple inheritance, but Smalltalk permits only single inheritance. You can either choose to prohibit developers from modeling with multiple inheritances (which makes your models language dependent) or develop idioms that transform these richer features into the implementation language (which makes the mapping more complex). Use tagged values to specify your target language. You can do this at the level of individual classes if you need precise control. You can also do so at a higher level, such as with collaborations or packages. Use tools to forward engineer your models.

Q.5. Explain the different components of states with reference to state machines. Ans. A state machine is simply a device or technique that receives input and acts upon that input based on the current condition of the device or technique. Async Professional uses state machines for a variety of tasks; such as managing protocol file transfers, sending and receiving faxes, collecting data packets, and monitoring the progress of a connection attempt. State machines are one of the fundamental techniques used for asynchronous communications, where a command is transmitted and the reply is received later in the session. Consider the simple task of initializing a modem to detect Caller ID information and answering a call. The first step (after opening the correct serial port) is to send a generic initialization command (ATZCR), then wait for the modem to return either a success response (OK) or a failure response (ERROR). The next step is to send the AT command to enable Caller ID detection and text responses (AT#CID=1CR) and wait for either a success or failure response. Finally, the project waits for the modems ring indicator (RING), answers the call (ATACR) and waits for the connection response (CONNECT). Each instance of a command and response can be thought of as a separate state in a state machine, as the following table illustrates. A simple, two or three-state state machine is relatively painless to create. The state machine is usually driven by TApdDataPacket components monitoring for success or fail conditions. When TApdDataPackets OnStringPacket event is generated, the state machine progresses according to the collected data. Once a state machine grows to twenty or thirty states, with multiple conditions defining the state progression, the project code can get cumbersome, difficult to maintain, and hard to visualize. The TApdStateMachine and TApdState components exist in order to assist in the development of orderly, well-defined, and easy to maintain and visualize state machines. The TApdStateMachine component is a container for TApdState components. TApdState components contain conditions that determine the accepted input to drive the state machine. To aid in the visualization of your state machine, the TApdStateMachine and TApdState components are visual components, showing connection lines with captions and customizable colors. When the state machine is

executing, the currently active state is highlighted to aid in debugging and to show the progression of the state machine. Q.6. List some of the significant differences between components and classes. Ans. Components v/s Classes: In many ways, components are like classes: both have names; both may realize a set of interfaces; both may participate in dependency, generalization, and association relationships; both may be nested; both may have instances; both may be participants in interactions. However, there are some significant differences between components and classes.

Classes represent logical abstractions; components represent physical things that live in the world of bits. In short, components may live on nodes, classes may not. Components represent the physical packaging of otherwise logical components and are at a different level of abstraction. Classes may have attributes and operations directly. In general, components only have operations that are reachable only through their interfaces.

The first difference is the most important. When modeling a system, deciding if you should use a class or a component involves a simple decision if the thing you are modeling lives directly on a node, use a component; otherwise, use a class. The second difference suggests a relationship between classes and components. In particular, a component is the physical implementation of a set of other logical elements, such as classes and collaborations. The relationship between a component and the classes it implements can be shown explicitly by using a dependency relationship. Most of the time, youll never need to visualize these relationships graphically. Rather, you will keep them as a part of the components specification. The third difference points out how interfaces bridge components and classes. Components and classes may both realize an interface, but a components services are usually available only through its interfaces.

Subject Name Subject Code Assignment No

: : :

Software Engineering MC 0071 01

Q.1. Explain Iterative Development Model in detail. Ans. Iterative Development Model: Iterative development is a cyclic software development process developed in response to the weaknesses of the waterfall model. It starts with an initial planning and ends with deployment with the cyclic interaction in between. The iterative development is an essential part of the Rational Unified Process, the Dynamic Systems Development Method, Extreme Programming and generally the agile software development frameworks.

Iterative development slices the deliverable business value (system functionality) into iterations. In each iteration, a slice of functionality is delivered through cross-discipline work, starting from the model/requirements through to the testing/deployment. The unified process groups iterations into phases: inception, elaboration, construction, and transition. Inception identifies project scope, risks, and requirements (functional and non-functional) at a high level but in enough detail that work can be estimated. Elaboration delivers a working architecture that mitigates the top risks and fulfills the nonfunctional requirements. Construction incrementally fills-in the architecture with production-ready code produced from analysis, design, implementation, and testing of the functional requirements. Transition delivers the system into the production operating environment.

Each of the phases may be divided into 1 or more iterations, which are usually time-boxed rather than feature-boxed. Architects and analysts work one iteration ahead of developers and testers to keep their work-product backlog full. Q.2. Explain why it is necessary to design the system architecture before the specifications is written. Ans. System Architecture: A system architecture or systems architecture is the conceptual design that defines the structure and/or behavior of a system. An architecture description is a formal description of a system, organized in a way that supports reasoning about the structural properties of the system. It defines the system components or building blocks and provides a plan from which products can be procured, and systems developed, that will work together to implement the overall system. This may enable one to manage investment in a way that meets business needs. It is important to keep in mind that the modern systems architecture did not appear out of nowhere. Systems architecture depends heavily on practices and techniques which were developed over thousands of years in many other fields most importantly being, perhaps, civil architecture.

Prior to the advent of digital computers, the electronics and other engineering disciplines used the term system as it is still commonly used today. However, with the arrival of digital computers and the development of software engineering as a separate discipline, it was often necessary to distinguish among engineered hardware artifacts, software artifacts, and the combined artifacts. A programmable hardware artifact or computing machine, that lacks its software program is impotent; even as a software artifact, or program, is equally impotent unless it can be used to alter the sequential states of a suitable (hardware) machine. However, a hardware machine and its software program can be designed to perform an almost illimitable number of abstract and physical tasks. Within the computer and software engineering disciplines (and, often, other engineering disciplines, such as communications), then, the term system came to be defined as containing all of the elements necessary (which generally includes both hardware and software) to perform a useful function. Consequently, within these engineering disciplines, a system generally refers to a programmable hardware machine and its included program. And a systems engineer is defined as one concerned with the complete device, both hardware and software and, more particularly, all of the interfaces of the device, including that between hardware and software, and especially between the complete device and its user (the CHI). The hardware engineer deals (more or less) exclusively with the hardware device; the software engineer deals (more or less) exclusively with the software program; and the systems engineer is responsible for seeing that the software program is capable of properly running within the hardware device, and that the system composed of the two entities is capable of properly interacting with its external environment, especially the user, and performing its intended function. By analogy, then, systems architecture makes use of elements of both software and hardware and is used to enable design of such a composite system. A good architecture may be viewed as a 'partitioning scheme,' or algorithm, which partitions all of the system's present and foreseeable requirements into a workable set of cleanly bounded subsystems with nothing left over. That is, it is a partitioning scheme which is exclusive, inclusive, and exhaustive. A major purpose of the partitioning is to arrange the elements in the sub systems so that there is a minimum of communications needed among them. In both software and hardware, a good sub system tends to be seen to be a meaningful "object". Moreover, a good architecture provides for an easy mapping to the user's requirements and the validation tests of the user's requirements. Ideally, a mapping also exists from every least element to every requirement and test. A robust architecture is said to be one that exhibits an optimal degree of fault-tolerance, backward compatibility, forward compatibility, extensibility, reliability, maintainability, availability, serviceability, usability, and such other quality attributes as necessary and/or desirable. Q.3. Explain why it is important to describe software designs. Ans. Importance of Describing Software Design: There are many aspects to software design, and many varying methodologies. Software design is a process of problem-solving and planning for a software solution. After the purpose and specifications of software are determined, software developers will design or employ designers to develop a plan for a solution. It includes low-level component and algorithm implementation issues as well as the architectural view. The software requirements analysis (SRA) step of a software development process yields specifications that are used in software engineering. If the software is "semiautomated" or user centered, software design may involve user experience design yielding a story board to help determine those specifications. If the software is completely automated (meaning no user or user interface), a software design may be as simple as a flow chart or text describing a planned sequence of events. There are also semi-standard methods like Unified Modeling Language and Fundamental modeling concepts. In either case some documentation of the plan is usually the product of the design.

A software design may be platform-independent or platform-specific, depending on the availability of the technology called for by the design. Design considerations: There are many aspects to consider in the design of a piece of software. The importance of each should reflect the goals the software is trying to achieve. Modeling language: A modeling language is any artificial language that can be used to express information or knowledge or systems in a structure that is defined by a consistent set of rules. The rules are used for interpretation of the meaning of components in the structure. A modeling language can be graphical or textual. Design patterns: A software designer or architect may identify a design problem which has been solved by others before. A template or pattern describing a solution to a common problem is known as a design pattern. The reuse of such patterns can speed up the software development process, having been tested and proved in the past. Usage: Software design documentation may be reviewed or presented to allow constraints, specifications and even requirements to be adjusted prior to programming. Redesign may occur after review of a programmed simulation or prototype. It is possible to design software in the process of programming, without a plan or requirement analysis, but for more complex projects this would not be considered a professional approach. A separate design prior to programming allows for multidisciplinary designers and Subject Matter Experts (SMEs) to collaborate with highly-skilled programmers for software that is both useful and technically sound. Q.4. What are the advantages of Incremental Models? Ans. Advantages of Incremental Models: System is developed and delivered in increments after establishing an overall architecture. Requirements and specifications for each increment may be developed. Users may experiment with delivered increments while others are being developed. Intended to combine some of the advantages of prototyping but with a more manageable process and better system structure. Incremental development is especially useful when staffing us unavailable for a complete implementation by the business deadline. Early increments can be implemented with fewer people. Generates working software quickly and early during the software life cycle. More flexible less costly to change scope and requirements. Easier to test and debug during a smaller iteration. Easier to manage risk because risky pieces are identified and handled during its iteration. Each iteration is an easily managed milestone.

Q.5. Write an overview on the Rational Unified Process. Ans. Rational Unified Process: The Rational Unified Process (RUP) is an iterative software development process framework created by the Rational Software Corporation, a division of IBM since 2003. RUP is not a single concrete prescriptive process, but rather an adaptable process framework, intended to be tailored by the development organizations and software project teams that will select the elements of the process that are appropriate for their needs. The Rational Unified Process (RUP) is a software process product, originally developed by Rational Software, and now available from IBM. The product includes a hyperlinked knowledge base with sample artifacts and detailed descriptions for many different types of activities. RUP is included in the IBM Rational Method Composer (RMC) product which allows customization of the process.

The Rational Unified Process resulted from a merger of the "Objectory Process" as developed by Ivar Jacobson and other methodologies including principally the "Booch method" by Grady Booch, and the Object-modeling technique by James Rumbaugh who combined forces at Rational Software Corporation in the mid 1990's, and in the process, rationalized their thinking regarding best practices for the software development process. Key considerations were the failure of projects using monolithic "waterfall" style methods and also the advent of object-oriented development and GUI technologies, a desire to elevate system modeling (especially object-oriented modeling) into the development practice, and to leverage Quality principles that applied to manufacturing in general into manufacturing software. Many previous methods influenced RUP. For instance the iterative development aspect has roots in the spiral model of Barry Boehm. The creators and developers of the process focused on diagnosing the characteristics of different failed software projects; by doing so they tried to recognize the root causes of these failures. They also looked at the existing software engineering processes and their solutions for these symptoms. Project failure is caused by a combination of several symptoms, though each project fails in a unique way. The outcome of their study was a system of software best practices they named the Rational Unified Process. The Process was designed with the same techniques the team used to design software; it has an underlying object-oriented model, using Unified Modeling Language (UML). Q.6. Explain the round-trip problem solving approach. Ans. Round-trip Problem Solving Approach: The software engineering process represents a roundtrip framework for problem solving in a business content context in several senses.

The software engineering process is a problem-solving process entailing that software engineering should incorporate or utilize the problem-solving literature regardless of its interdisciplinary sources. The value of software engineering derives from its success in solving business and human problems. This entails establishing strong relationships between the software process and the business metrics used to evaluate business process in general. The software engineering process is a round-trip approach. It has a bidirectional character, which frequently requires adopting forward and reverse engineering strategies to restructure and reengineer information systems. It uses feedback control loops to ensure that specifications are accurately maintained across multiple process phases; reflective quality assurance is a critical metric for process in general. The nonterminating, continuing character of the software development process is necessary to respond to ongoing changes in customer requirements and environmental pressures.

Subject Name Subject Code Assignment No

: : :

Software Engineering MC 0071 02

Q.1. Choose a specific application and indicate a) the software application category into which it fits b) the data content associated with the application and c) the information determinacy of the application. Ans. Software may be applied in any situation for which a prespecified set of procedural steps has been defined. Information content and determinacy are important factors in determining the nature of a software application. Content refers to the meaning and form of incoming and outgoing information. Software that controls an automated machine accepts discrete data items with limited structure and produces individual machine commands in rapid succession. Information determinacy refers to the predictability of the order and timing of information. An engineering analysis program accepts data that have a predefined order, executes the analysis algorithm without interruption and produces resultant data in report or graphical format. Such applications are determinate. A multi-user operating system, on the other hand, accepts inputs that have varied content and arbitrary timing, executes algorithms that can be interrupted by external conditions, and produces output that varies as a function of a environment and time. Applications with these characteristics are indeterminate. Software applications can be neatly compartmentalized into different categories. System Software: System software is a collection of programs written to service other programs. Some system software process complex information structures. Other systems applications process largely indeterminate data. It is characterized by heavy interaction with hardware, heavy usage by multiple users, concurrent operation that requires scheduling, resource sharing, and sophisticated process management, complex data structures and multiple external interfaces. Real Time Software: Software that monitors / analyses / controls real-world events as they occur is called real time. Business Software: Business information processing is the largest single software application area. Discrete systems like payroll, accounts receivable / payable have evolved into management information systems (MIS) software that accesses one or more large databases containing business information. Applications in this area restructure existing data in a way that facilitates business operations or management decision making. Engineering and Scientific Software: Engineering and scientific software has been characterized by number crunching algorithms. Applications range from astronomy to volcano logy, from automotive stress analysis to space shuttle orbital dynamics and from molecular biology to automated manufacturing. Embedded Software: Embedded software resides only in read-only memory and is used to control products and systems for the consumer and industrial markets. Embedded software can provide very limited and esoteric functions or provide significant function and control capability. Personal Computer Software: Day to day useful applications like word processing, spreadsheets, multimedia, database management, personal and business financial applications are some of the common examples for personal computer software. We-based Software: The web pages retrieved by a browser are software that incorporates executable instructions and data. In essence, the network becomes a massive computer providing an almost unlimited software resource that can be accessed by anyone with a modem.

Artificial Intelligence Software: Artificial intelligence software makes use of non numerical algorithms to solve complex problems that are not amenable to computation or straightforward analysis. Expert systems, also called knowledge based systems, pattern recognition, game playing are representative examples of applications within this category. Software Crisis: The set of problems that are encountered in the development of computer software is limited to software that does not function properly rather the affliction encompasses problems associated with how we develop software, how we support a growing volume of existing software, and how we can expect to keep pace with a growing demand for more software. Q.2. Describe the main activities in the software design process and the outputs of these activities. Using an entity relation diagram, show possible relationship between the outputs of these activities. Ans. Main Activities in Software Design Process: The important task in creating a software product is extracting the requirements or requirements analysis. Customers typically have an abstract idea of what they want as an end result, but not what software should do. Incomplete, ambiguous, or even contradictory requirements are recognized by skilled and experienced software engineers at this point. Frequently demonstrating live code may help reduce the risk that the requirements are incorrect.

Once the general requirements are gleaned from the client, an analysis of the scope of the development should be determined and clearly stated. This is often called a scope document. Certain functionality may be out of scope of the project as a function of cost or as a result of unclear requirements at the start of development. If the development is done externally, this document can be considered a legal document so that if there are ever disputes, any ambiguity of what was promised to the client can be clarified.

Domain Analysis is often the first step in attempting to design a new piece of software, whether it is an addition to existing software, a new application, a new subsystem or a whole new system. Assuming that the developers (including the analysts) are not sufficiently knowledgeable in the subject area of the new software, the first task is to investigate the so-called "domain" of the software. The more knowledgeable they are about the domain already, the less work required. Another objective of this work is to make the analysts, who will later try to elicit and gather the requirements from the area experts, speak with them in the domain's own terminology, facilitating a better understanding of what is being said by these experts. If the analyst does not use the proper terminology it is likely that they will not be taken seriously, thus this phase is an important prelude to extracting and gathering the requirements. If an analyst hasn't done the appropriate work confusion may ensue: "I know you believe you understood what you think I said, but I am not sure you realize what you heard is not what I meant." Q.3. Draw possible data flow diagram of system design for the following application. Part of the electronic mail system which presents a mail form to a user, accepts the completed form and sends it to the identified destination. Ans. Data Flow Diagram: A data-flow diagram (DFD) is a graphical representation of the "flow" of data through an information system. DFDs can also be used for the visualization of data processing (structured design). On a DFD, data items flow from an external data source or an internal data store to an internal data store or an external data sink, via an internal process. A DFD provides no information about the timing or ordering of processes, or about whether processes will operate in sequence or in parallel. It is therefore quite different from a flowchart, which shows the flow of control through an algorithm, allowing a reader to determine what operations will be performed, in what order, and under what circumstances, but not what kinds of data will be input to and output from the system, nor where the data will come from and go to, nor where the data will be stored (all of which are shown on a DFD). It is common practice to draw a context-level data flow diagram first, which shows the interaction between the system and external agents which act as data sources and data sinks. On the context diagram (also known as the Level 0 DFD) the system's interactions with the outside world are modeled purely in terms of data flows across the system boundary. The context diagram shows the entire system as a single process, and gives no clues as to its internal organization. This context-level DFD is next "exploded", to produce a Level 1 DFD that shows some of the detail of the system being modeled. The Level 1 DFD shows how the system is divided into sub-systems (processes), each of which deals with one or more of the data flows to or from an external agent, and which together provide all of the functionality of the system as a whole. It also identifies internal data stores that must be present in order for the system to do its job, and shows the flow of data between the various parts of the system. Data-flow diagrams were invented by Larry Constantine, the original developer of structured design, based on Martin and Estrin's "data-flow graph" model of computation. Data-flow diagrams (DFDs) are one of the three essential perspectives of the structured-systems analysis and design method SSADM. The sponsor of a project and the end users will need to be briefed and consulted throughout all stages of a system's evolution. With a data-flow diagram, users are able to visualize how the system will operate, what the system will accomplish, and how the system will be implemented. The old system's dataflow diagrams can be drawn up and compared with the new system's data-flow diagrams to draw comparisons to implement a more efficient system. Data-flow diagrams can be used to provide the end user with a physical idea of where the data they input ultimately has an effect upon the structure of the whole system from

order to dispatch to report. How any system is developed can be determined through a data-flow diagram. In the course of developing a set of leveled data-flow diagrams the analyst/designers is forced to address how the system may be decomposed into component sub-systems, and to identify the transaction data in the data model. There are different notations to draw data-flow diagrams, defining different visual representations for processes, data stores, data flow, and external entities. Q.4. What are the main characteristics of successful teams? Ans. Characteristics of Successful Teams: Members share the potential for success with each other. Members share the risk of failure with each other. Have clearly established goals and objectives that are accepted by the members. Self impose high standards of performance, rather than being pressured to perform by a supervisor. Allow members to disagree and have an effective way of resolving problems and intergroup conflict. Members trust each other. Have divergent members with differing backgrounds and perspectives on the situation. Members share roles and functions including leadership. Make decisions by consensus with consideration of alternatives. Are cohesive: have a sense of unity and oneness. Experience synergy where the whole is greater than the sum of its parts. Has a comfortable working atmosphere in which members or engaged, committed and alert. Have members who listen and provide useful feedback. Use constructive criticism when necessary to facilitate interaction and accomplish tasks. Express ideas fully and frankly so that everyone has all the relevant information and hidden agendas are minimized. Recognize individual contributions. Assist members to ensure successful completion of the teams goals. Attach high value to new, creative approaches to problems. Are flexible because of members influences on each other.

Q.5. What are the various types of prototyping models? Ans. Types of Prototyping Models: There is no general agreement on what constitutes a "prototype" and the word is often used interchangeably with the word "model" which can cause confusion. In general, prototypes fall into four basic categories: Proof-of-Principle Prototype (Model) (also called a breadboard). This type of prototype is used to test some aspect of the intended design without attempting to exactly simulate the visual appearance, choice of materials or intended manufacturing process. Such prototypes can be used to prove out a potential design approach such as range of motion, mechanics, sensors, architecture, etc. These types of models are often used to identify which design options will not work, or where further development and testing is necessary.

Form Study Prototype (Model). This type of prototype will allow designers to explore the basic size, look and feel of a product without simulating the actual function or exact visual appearance of the product. They can help assess ergonomic factors and provide insight into visual aspects of the product's final form. Form Study Prototypes are often hand-carved or machined models from easily sculpted, inexpensive materials (e.g., urethane foam), without representing the intended color, finish, or texture. Due to the materials used, these models are intended for internal decision making and are generally not durable enough or suitable for use by representative users or consumers. Visual Prototype (Model) will capture the intended design aesthetic and simulate the appearance, color and surface textures of the intended product but will not actually embody the function(s) of the final product. These models will be suitable for use in market research, executive reviews and approval, packaging mock-ups, and photo shoots for sales literature. Functional Prototype (Model) (also called a working prototype) will, to the greatest extent practical, attempt to simulate the final design, aesthetics, materials and functionality of the intended design. The functional prototype may be reduced in size (scaled down) in order to reduce costs. The construction of a fully working full-scale prototype and the ultimate test of concept is the engineers' final check for design flaws and allow last-minute improvements to be made before larger production runs are ordered. Q.6. Write a brief note on COTS. Ans. Commercial, off-the-shelf (COTS): Commercial, off-the-shelf (COTS) or simply off the shelf (OTS) is a term for software or hardware, generally technology or computer products, that are ready-made and available for sale, lease, or license to the general public. They are often used as alternatives to in-house developments or one-off government-funded developments. The use of COTS is being mandated across many government and business programs, as they may offer significant savings in procurement and maintenance. However, since COTS software specifications are written by external sources, government agencies are sometimes wary of these products because they fear that future changes to the product will not be under their control. Motivations for using COTS components include reduction of overall system development and costs (as components can be bought or licensed instead of being developed from scratch) and reduced maintenance costs. In software development, many considered COTS to be the silver bullet during the 1990s, but COTS development came with many not-so-obvious tradeoffsoverall cost and development time can definitely be reduced, but often at the expense of an increase in software component integration work and a dependency on a third-party component vendor. Several groups have been formed to encourage the development of COTS systems for various purposes and promote their adoption. The Mountain View Alliance was one such group but now appears defunct. In finance or commerce, off the shelf refers to products that have already been designed and made, compared to "made to measure," (or "one-off," "custom-built," "custom made,", "bespoke", etc.), which refer to products that are made to a special order. Off-the-shelf products are generally cheaper and more quickly available than those made to measure. The term comes originally from clothing manufacture; items are either mass produced or made especially for a particular customer (i.e. made to measure that customer's exact size, not an approximation to it). Equivalent terms are ready-to-wear, off the rack, and pret-a-porter (French: ready to wear).

In the computing industry, off-the-shelf software is that available on demand as a stock item, i.e. not specially designed or custom-made. That which is made for a specific customer is generally called bespoke software.

Subject Name Subject Code Assignment No

: : :

System Programming MC 0073 02

Q.1. Explain the addressing modes of CISC. Ans. Addressing Modes of CISC: The 68000 addressing (Motorola) modes

Register to Register, Register to Memory, Memory to Register, and Memory to Memory

68000 support a wide variety of addressing modes.


Immediate mode the operand immediately follows the instruction. Absolute address the address (in either the short 16-bit form or long 32-bit form) of the operand immediately follows the instruction. Program counter relative with displacement A displacement value is added to the program counter to calculate the operands address. The displacement can be positive or negative. Program counter relative with index and displacement The instruction contains both the identity of an index register and a trailing displacement value. The contents of the index register, the displacement value, and the program counter are added together to get the final address. Register direct The operand is contained in an address or data register. Address register indirect An address register contains the address of the operand. Address register indirect with predecrement or postdecrement An address register contains the address of the operand in memory. With the predecrement option set, a predetermined value is subtracted from the register before the new address is used. With the postincrement option set, a predetermined value is added to the register after the operation completes. Address register indirect with displacement A displacement value is added to the registers contents to calculate the operands address. The displacement can be positive or negative. Address register relative with index and displacement The instruction contains both the identity of an index register and a trailing displacement value. The contents of the index register, the displacement value, and the specified address register are added together to get the final address.

Q.2. Explain the design of a multi-pass assembler. Ans. Design of Multi-pass Assembler: There are six steps to be followed in the design of assembler. They are: 1. 2. 3. 4. 5. Specify the problem Specify data structures Define format of data structures Specify algorithm Look for modularity. (Capability of one program to be subdivided into independent programming units.) 6. Repeat 1 through 5 on each module In the first step we have to specify the function the assembler has to perform. The second step specifies the data the assembler needs to perform in further operations. This will be stored in the form of tables, which is called as database (data structure). Thus the assembler makes use of the information, which is present in the database for further processing. In the third step we specify the structure or the way data has to be stored in the database. It specifies the format of storing of data, and the contents of the database. The fourth step gives the algorithm, which has to be converted to program to get the result from the assembler. The fifth step is the step for dividing the program into

sub problems, which enables the designer to write the assembler efficiently. Finally the same steps have to be repeated for the sub problems, which have been divided from the given program. Specify the problem or Statement of problem: The fundamental information requirements arise in the synthesis phase of an assembler. Hence it is best to begin by considering the information requirements of the synthesis tasks. We then consider how to make this information available, i.e. whether it should be collected during analysis or derived during synthesis. Q.3. Explain the flow chart for pass1. Ans.

Q.4. What is nesting? Explain nesting of macros with example. Ans. Macro bodies may also contain macro calls, and so may the bodies of those called macros, and so forth. If a macro call is seen throughout the expansion of a macro, the assembler starts immediately with the expansion of the called macro. For this, its expanded body lines are simply inserted into the expanded macro body of the calling, macro, until the called macro is completely expanded. Then the expansion of the calling macro is continued with the body line following the nested macro call. Example: INSIDE MACRO SUB A, R3 ENDM OUTSIDE MACRO MOV A, #42 INSIDE MOVE R7, A ENDM In the body of the macro OUTSIDE, the macro INSIDE is called. If OUTSIDE is called (and the list mode is set to 4GENONLY), one gets something like the following expansion: Line | 15+ 1 17+ 2 18+ 1 Addr 0000 0002 0003 Code 74 2A 9B SUBB FF Source MOV A, #42 A, R3 MOV R7, A

Since macro calls can be nested to any depth (while there is free memory), the macro expansion level is shown in the I-column of the list file. Since macro and include file levels can be nested in arbitrary sequence and depth, the nesting level is counted through all macro and include file levels regardless. For better distinction, the character following the global line number is : for include file levels, and + for macro levels. A macro body may also contain further macro definitions. However, these nested macro definitions arent valid until the enclosing macro has been expanded! That means, the enclosing macro must have been called, before the nested macros can be called. Example: A macro, which can be used to define macros with arbitrary names, may look as follows: DEFINE MACRO MACNAME MACNAME MACRO DB I am the macro &MACNAME. ENDM ENDM In order not to overload the example with know how, the nested macro only introduces itself kindly with a suitable character string in ROM. The call DEFINE Obiwan would define the macro Obiwan MACRO DB I am the macro Obiwan. ENDM and the call DEFINE Skywalker would define the following macro: Skywalker MACRO

DB I am the macro Skywalker. ENDM Q.5. What is Relocation? Write the relocation algorithm in detail. Ans. Relocation: One wrinkle that the loader must handle is that the actual location in memory of the library data cannot be known until after the executable and all dynamically linked libraries have been loaded into memory. This is because the memory locations used depend on which specific dynamic libraries have been loaded. It is not possible to depend ton the absolute location of the data in the executable, nor even in the library, since conflicts between different libraries would result: if two of them specified the same or overlapping addresses, it would be impossible to use both in the same program. However, in practice, the shared libraries on most systems do not change often. Therefore, it is possible to compute a likely load address fro every shared library on the system before it is needed, and store that information in the libraries and executables. If every shared library that is loaded has undergone this process, then each will load at their predetermined addresses, which speeds up the process of dynamic linking. This optimization is known as prebinding in Mac OS X and prelinking in Linux. Disadvantages of this technique include the time required to precompute these addresses every time the shared libraries change, the inability to use address space layout randomization, and the requirement of sufficient virtual address space for use (a problem that will be alleviated by the adoption of 64-bit architectures, at least for the time being). An old method was to examine the program at load time and replace all references to data in the libraries with pointers to appropriate memory locations once all libraries have been loaded. On Windows 3.1 (and some embedded systems such as Texas Instruments calculators), the references to patch were arranged as linked lists, allowing easy enumeration and replacement. Nowadays, most dynamic library systems link a symbol table with blank addresses into the program at compile time. All references to code or data in the library pass through this table, the import directory. At load time the table is modified with the location of the library code / data by the loader / linker. This process is still slow enough to significantly affect the speed of programs that call other programs at a very high rate, such as certain shell scripts. Relocation Algorithm: 1. program_linked_origin := <link origin> from linker command; 2. For each object module a. t_origin : translated origin of the object module; OM_size : size of the object module; b. relocation_factor := program_linked_origin t_origin; c. Read the machine language program in work_area. d. Read the RELOCATB of the object module. e. For each entry in RELOCTAB i. translated_addr := address in the RELOCTAB entry; ii. address_in_work_area : address of work_area + translated_addr t_origin; iii. Add relocation_factor to the operand address in the word with the address addressjn_work_area. f. program_linked_origin : program_linked_origin + OM_size; Q.6. What is compiler? Explain the compiling process. Ans. Compiler: Compiler is a translator. It translates the program written in a high level language such as FORTRAN, PL/I or COBOL into an object language, which is a low level language such as an assembly language or machine language. Executing a program written in a high-level programming language is basically a two step process. The source program must first be compiled, i.e. translated into the object program. Then the resulting object program is loaded into memory and executed.

Why do we need compilers? The answer to this question is obvious to anyone who has programmed in machine language. With machine language we must communicate directly with a computer in terms of bits, registers, and very primitive machine operations. Since a machine language program is nothing more than a sequence of 0s and 1s, programming a complex algorithm in such a language is terribly tedious and fraught with opportunities for mistakes. Perhaps the most serious disadvantage of machine language coding is that all operations and operands must be specified in a numeric code. Not only is a machine language program cryptic, but it also may be impossible to modify in a convenient manner. So to overcome theses problems, there has been evolution of new programming languages. Basically a high level programming language allows a programmer to express algorithms in a more natural notation and avoids many of the details of how a specific computer functions. A high-level programming language makes the programming task simpler, but it also introduces some problems. The most obvious is that we need a program to translate the high-level language into a language the machine can understand.

Subject Name : Statistical and Numerical Methods using C++ Subject Code : MC 0074

Assignment No : 02

Q.1. Briefly describe in your own words the concept of Markov Chains. Ans. Markov Chains: A Markov process is a stochastic process whose dynamic behavior is such that probability distribution for its future development depends only on the present state and not on how the process arrived in that state. If we assume that the state space I, is discrete, then the Markov process is known as Markov chain. If we further assume that the parameter space, T, is also discrete, then we have a discrete parameter Markov chain. We choose to observe the state of a system at a discrete set of times. The successive observations define the random variables X0,X1,X2,.Xn, ,at time step n is j. X0 is the initial state of the system. The Markov property can then be succinctly stated as: P(Xn=in|X0=i0,X1=i1,Xn-1=in-1)=P(Xn=in|Xn-1=in-1) We let pj(n) denote the pmf of the random variable Xn; that is Pj(n)=P(Xn=j) And let the conditional pmf Pjk(m,n)=P(Xn=K|Xm=j), Pjk(m,n) is known as the transition probability function of the Markov chain. For such chain, we use the notation to denote the n-step transition probabilities. Pjk(n)=P(Xm+n=K|Xm=j) To obtain the joint probabilities P(X0=i0,X1=i1,.Xn=in) . =pi0(0)pi0,i1..pin-1,in The one step transition probabilities are compactly specified in the forms of a transition probability matrix: P00 P=[pij]= P10 . . P01 P11 . . P02 ... P12 . .

The entries of the matrix P satisfy the following two properties. 0pij1 and j Pij=1 Any such square matrix that has nonnegative entries with row sums all equal to unity is called a stochastic matrix. A node labeled I of the state diagram represents state I of the Markov chain and a branch labeled pij from node to j implies that the conditional probability is P(Xn=j|Xn-1=i)=pij. Q.2. List down the different types of error? Explain each of them with examples? Ans. Types of Errors:

1. Inherent Error: The inherent error is that quantity which is already present in the statement of
the problem before its solution. The inherent error arises due to the simplified assumption in the mathematical formulation of the problem or due to the errors in the physical measurements of the parameters of the problem. In computation, inherent errors can be minimized by obtaining aids of higher precision.

2. Round-Off Error: The round-off error is the quantity R, which must be added to the finite
representation of a computed number in order to make it the true representation of that number. In computation, the round off error can be reduced by carrying the computation to more significant figures at step of the computation. At each step of the computation, retain at least one more significant figure than that given in the data; perform the last operation, and then round-off.

3. Truncation Error: The truncation error is the quantity T, which must be added to the true
representation of the quantity in order that the result is exactly equal to the quantity we are seeking to generate. This error is a result of the approximation formulas used, which are generally based on truncated series. The Taylor series with a remainder is an invaluable tool in the study of the truncation error. The study of this type of error is usually associated with the problem of convergence. Truncation error in a problem can be evaluated and it is desirable to make it as small as possible. Example: We have ex=1+x+x2/2!+x3/4!+x4/4!+x5/5!+. if we use an approximate formula by truncating the 4th and higher degree terms, we have, S(x)=1+x++x2/2!+x3/3!. Then the Truncation error is ex-S(x)=x4/4!+x5/5!+. .

4. Absolute Error: It is the numerical difference between its true value of a quantity and its
approximate value. If X is the true quantity and Xa is its approximate value then the absolute error Ea is given by Ea=|True Value-Approximate Value |=|X-Xa|.

5. Relative Error: It is the absolute error divided by the true value of the quantity and this is
denoted by Er, Relative Error Er=Absolute error/True Value = Ea/X

6. Percentage Error: Ep=Ea/X*100=Er*100


Q.3. Write the program in C++ language for addition of two matrices. Ans. Program: /*Addition of two Matrices*/ #include<iostream.h> #include<conio.h> #include<math.h> void main() { int i, j; int a[7][7], b[7][7]; clrscr(); cout<<"Enter the first matrix\n";

for (i=0; i<6; i++) { for (j=0; j<=6; j++) cin>>a[i][j]; } cout<<"\nEnter the second matrix\n"; for (i=0; i<=6; i++) { for (j=0; j<=6; j++) cin>>b[i][j]; } cout<<"\nAddition of two matrix is\n"; for (i=0; i<=6; i++) { for (j=0; j<=6; j++) { a[i][j] = a[i][j] + b[i][j]; cout<<a[i][j]<<"\t"; } Cout<<endl; } getch(); }

0 1 2 Q.4. Applying Cayley-Hamilton theorem, compute the inverse of the matrix A = 1 2 3 3 1 1


Ans. Cayley-Hamilton Theorem:

A=

0 1 1 2 3 1

2 3 1

The characteristic equation of A is |A- I | = 0. That is,

0- 1 3

1 2- 1

2 3 1-

(1)

On expanding, we get 3-32-8 +2 = 0. Applying Cayley-Hamilton theorem, A3-3A2-8A+2I = 0. Post multiplying with A-1 we have, A2-3A-8I+2A-1=O. This implies A-1=-1/2(A2-3A-8I) (2) Now A2 = A.A =

0 1 3

1 2 1

2 3 1

0 1 3

1 2 1

2 3 1

7 11 4

4 8 6

5 11 10

= Thus (ii), becomes -1/2

7 4 5 11 8 11 3 1 1

0 3 6 3 6 9 9 3 3

8 0 0 0 8 0 0 0 8

Therefore A-11/2

-1 1 -1 8 -6 2 -5 3 -1

It can be verified that AA-1=I Q.5. Find a real root of the equation x3 4x 9 = 0 using the bisection method. Ans. Real root of the Equation X3 - 4X - 9 = 0 Using Bisection Method: Let f(x)=x3-4x-9 F(1)=1-4-9=-12<0 F(2)=8-8-9=-9<0 F(3)=27-12-9=+6>0 Since f(2) is ve and f(3) is +ve, a root lies between 2 and 3. Therefore the first approximation to the root is x1=2+3/2=2.5 Then f(x1)=f(2.5)=2.53-4*2.5-9=-3.375<0 i.e. f(2.5) is ve. Hence the root lies between 2.5 and 3 since f(2.5)<0 and f(3)>0. thus the second approximation to the root is. X2=x1+3/2=2.5+3/2=2.75 Then f(x2) = f(2.75)=2.753-4*2.75-9=0.7969>0. We therefore conclude that the root lies between 2.5 and 2.75. Thus the third approximation to the root is X3=2.5+2.75/2=2.625 Then f(x3) = f(2.625)=-1.4121<0 The root lies between x2 and x3. Thus the fourth approximation to the root is X4=2.75+2.625/2=2.6875 The Procedure is repeated and successive approximations are x5=2.703125, x6=2.7109375, x7=2.70703125, x8=2.7051 etc. therefore x=x8=2.7051 is the approximate root. Q.6. From the following table, estimate the number of students who obtained marks between 40 and 45 Marks No of students 30-40 31 40-50 42 50-60 51 60-70 35 70-80 31

Ans. First we prepare the cumulative frequency table, as follows, Mark less than (x) 40 50 60 No. of students of y 31 73 124 Now the difference table is X Y 40 31 50 60 70 80 73 51 124 35 159 31 190 We shall find the number of students with marks less than 45. From the above table we have, Y0=31, y0=42, 2y0=9, 3y0=-25. 4y0=37 Taking x0=40, x=45 We have X=x0+ph 45=40+p10 P=0.5 -4 -16 42 9 2

70 159 3

80 190 4

-25 37 -12

Using Newtons forward interpolation formula, we get Y(x)=y0+py0+p(p-1)/22y0+p(p-1)(p-2)/3! 3y0+p(p-1)(p-2)(p-3)/4! 4y0 Y(45)=31+0.5(42)+(0.5)(0.5-1)2!(9)+(0.5)(0.5-1)(0.5-2)/3!(-25)+(0.5)(0.5-1)(0.5-2)(0.5-3)/4!(370 =31+21-1.125-1.5625-1.4453=47.87 Y(45)=47.87 The number of students with marks less than 45 is 47.87, which is 48. But the number of students with marks less than 40 is 31. Hence the number of students getting marks between 40 and 45 = 48 - 31 =17 students.

You might also like