assinment 2nd sem

116
July 2011 Master of Computer Application (MCA) – Semester 2 MC0066 – OOPS using C++ (Book ID: B0681 & B0715) Assignment Set – 1 1.Write a program in C++ for matrix multiplication. The program should accept the dimensions of both the matrices to be multiplied and check for compatibility with appropriate messages and give the output. ANS.. 1

Upload: dlpvrm57

Post on 01-Dec-2014

346 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Assinment 2nd Sem

July 2011Master of Computer Application (MCA) – Semester 2

MC0066 – OOPS using C++(Book ID: B0681 & B0715)

Assignment Set – 1

1.Write a program in C++ for matrix multiplication. The program should accept the dimensions of both the matrices to be multiplied and check for compatibility with appropriate messages and give the output.

ANS..

1

Page 2: Assinment 2nd Sem

2

Page 3: Assinment 2nd Sem

Q2. Write a program to check whether a string is a palindrome or not. Please note thatpalindrome is one which remains the same if you reverse the characters in the string. Forexample “MADAM”.A2.#include <cstdlib>#include <cstring>using namespace std;#include<iostream>int main(int argc, char** argv) {char str[20];int len = 0;cout << "Enter the word: ";cin >> str;len = strlen(str);len--;for (int i = 0; i < len; i++) {if (str[i] == str[len - i])continue;else {cout << str << " is not a palindrome." << endl;return 0;}}

3

Page 4: Assinment 2nd Sem

cout << str << " is a palindrome." << endl;return 0;}Q3. What is structure in C++? Define a structure named product with elementsproductcode, description, unitprice and qtyinhand. Write a C++ program that implementsthe structure and enables to store atleast 100 product data.A3. Data that are of different types but are logically related can be grouped togetherusing structures. Structures are a group of dissimilar data that are related with each other.using namespace std;#include <iostream>#define MAX_PROD 100struct product {char productcode[10];char description[50];double unitprice;int qtyinhand;};int main(void) {struct product my_prod[MAX_PROD];for (int i = 0; i < MAX_PROD; i++) {cout << "Enter product code for product number " << i + 1 << ": ";cin >> my_prod[i].productcode;cout << "Enter description for product number " << i + 1 << ": ";cin >> my_prod[i].description;cout << "Enter unit price for product number " << i + 1 << ": ";cin >> my_prod[i].unitprice;cout << "Enter quantity in hand for product number " << i + 1 << ": ";cin >> my_prod[i].qtyinhand;cin.sync();}}Book ID: B071Q4. What is the purpose of exception handling? How do you infer from the phrase,“Throwing an exception”?A4. The main purposes of exception handling are as follows:i) Writing error-handling code becomes trivial and it does not get mixed up withthe "normal" code that we write. The code is written without worrying aboutthe errors the code might throw. Later in a separate section the code is writtento cope with the errors. If you make multiple calls to a function, the errors arehandled from that function once, in one place.ii) Errors cannot be ignored. If a function needs to send an error message to thecaller of that function, it “throws” an object representing that error out of thefunction. If the caller doesn’t “catch” the error and handle it, it goes to thenext enclosing scope, and so on until someone catches the error.Meaning of “throwing an exception”: If an exceptional situation is encountered in thecode that is, a situation where there is not enough information in the current context todecide what to do – the information about the error can be sent into a larger context bycreating an object containing that information and “throwing” it out of the currentcontext. This is called throwing an exception. Here’s what it looks like:throw myerror(“something bad happened”);myerror is an ordinary class, which takes a char* as its argument. Any type can be used to

4

Page 5: Assinment 2nd Sem

throw (including built-in types), but often special types are used which are created just forthrowing exceptions. The keyword throw does the following:i) It creates an object that isn’t there under normal program execution, and ofcourse the constructor is called for that object.ii) Then the object is, in effect, “returned” from the function, even though thatobject type isn’t normally what the function is designed to return.

Assignment Set – 2

Book ID: B0681Q1. Write a program which accepts a number from the user and generates primenumbers till that number.A1. using namespace std;#include <iostream>void print_prime(int);int main(void) {int limit = 0;cout << "Enter the limit: ";cin >> limit;print_prime(limit);return 0;}void print_prime(int limit) {bool is_prime = false;for (int i = 2; i <= limit; i++) {for (int j = 2; j <= limit; j++) {if (i != j && i % j == 0) {is_prime = false;break;}elseis_prime = true;}if (is_prime)cout << i << ", ";}cout << endl;}Q2. Implement a class stack which simulates the operations of the stack allowing LIFOoperations. Also implement push and pop operations for the stack.A2.using namespace std;#include <iostream>#define SIZE 100class stack {int stck[SIZE];int top;public:stack() {top = 0;

5

Page 6: Assinment 2nd Sem

cout << "Stack initialized" << endl;}~stack() {cout << "Stack destroyed" << endl;}void push(int i);int pop();};void stack::push(int i) {if (top == SIZE) {cout << "Stack is full" << endl;return;}stck[top] = i;top++;}int stack::pop() {if (top == 0) {cout << "Stack underflow" << endl;return 0;}top--;return stck[top];}Book ID: B0715Q3. What are allocators? Describe the sequence container adapters.A3. Allocators allocate raw memory and return it. They do not create or destroy objects.Allocators are very low level features in STL and are designed to encapsulate memoryallocation and deallocation. This allows for efficient storage by use of different schemesfor particular container classes. The default allocator, alloc, is thread-safe and has goodperformance characteristics. On the whole, it is best to regard allocators as a black box,partly because their implementation is still in a state of change, and also because thedefaults work well for most applications.Sequence container adapters are used to change the user interface to other STL sequencecontainers or to user written containers if they satisfy the access function requirements.Container adapters make this change of user interface possible by presenting the samepublic interface irrespective of the underlying container. Being templatized, they avoidname proliferation. Provided the container type used supports the operations required bythe adapter class, any types can be used for underlying implementation.4. Write about the following with the help of suitable programming examples: A) Throwing an Exception B) Catching an ExceptionANS. Throwing an Exception

Exceptions are run-time anomalies that a program may detect, such as division by 0, access to an array

outside of its bounds, or the exhaustion of the free store memory. Such exceptions exist outside the

normal functioning of the program and require immediate handling by the program. The C++ language

provides built-in language features to raise and handle exceptions. These language features activate a

6

Page 7: Assinment 2nd Sem

run-time mechanism used to communicate exceptions between two unrelated (often separately

developed) portions of a C++ program.

When an exception is encountered in a C++ program, the portion of the program that detects the

exception can communicate that the exception has occurred by raising, or throwing, an exception. To

see how exceptions are thrown in C++, let's reimplement the class iStack presented in Section 4.15 to

use exceptions to indicate anomalies in the handling of the stack. The definition of the class iStack looks

like this:

#include <vector>

class iStack {

public:

iStack( int capacity )

: _stack( capacity ), _top( 0 ) { }

bool pop( int &top_value );

bool push( int value );

bool full();

bool empty();

void display();

int size();

private:

int _top;

vector< int > _stack;

};

The stack is implemented using a vector of ints. When an iStack object is created, the constructor for

iStack creates a vector of ints of the size specified with the initial value. This size is the maximum

number of elements the iStack object can contain. The following, for example, creates an iStack object

called myStack that can contain as many as 20 values of type int:

7

Page 8: Assinment 2nd Sem

iStack myStack(20);

What can go wrong when we manipulate myStack? Here are two anomalies that may be encountered

with our iStack class:

Catching an ExceptionExceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in atry block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keywordcatch, which must be placed immediately after the try block:// exceptions#include <iostream>using namespace std;

int main () { try { throw 20; } catch (int e) { cout << "An exception occurred. Exception Nr. " << e << endl; } return 0;}The code under exception handling is enclosed in a try block. In this example this code simply throws an exception:

July 2011Master of Computer Application (MCA) – Semester 2

MC0067 – Database Management System(DBMS and Oracle 9i) (Book ID: B0716 & B0717)

Assignment Set – 1

1. Write about: Linear Search

Collision Chain

ANS.

Linear Search

8

Page 9: Assinment 2nd Sem

Linear search, also known as sequential search, means starting at the beginning of the data and checking

each item in turn until either the desired item is found or the end of the data is reached. Linear search is

a search algorithm, also known as sequential search that is suitable for searching a list of data for a

particular value. It operates by checking every element of a list one at a time in sequence until a match

is found. The Linear Search, or sequential search, is simply examining each element in a list one by one

until the desired element is found. The Linear Search is not very efficient. If the item of data to be found

is at the end of the list, then all previous items must be read and checked before the item that matches

the search criteria is found. This is a very straightforward loop comparing every element in the array

with the key. As soon as an equal value is found, it returns. If the loop finishes without finding a match,

the search failed and -1 is returned. For small arrays, linear search is a good solution because it's so

straightforward. In an array of a million elements linear search on average will take500, 000

comparisons to find the key. For a much faster search, take a look at binary search.

Algorithm

For each item in the database

if the item matches the wanted info

exit with this item

Continue loop

wanted item is not in database

Collision Chain:

In computer science, a hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys (e.g., a person's name), to their associated values (e.g., their telephone number). Thus, a hash table implements an associate array. The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought.

Ideally, the hash function should map each possible key to a unique slot index, but this ideal is rarely achievable in practice (unless the hash keys are fixed; i.e. new entries are never added to the table after it is created). Instead, most hash table designs assume that hast collisions—different keys that map to the same hash value—will occur and must be accommodated in some way.

2. Write about:

9

Page 10: Assinment 2nd Sem

Integrity Rules

Relational Operators with examples for each

Linear Search

Collision Chain

ANS.2.1 Integrity Rules:

These are the rules which a relational database follows in order to stay accurate and accessible. These rules govern which operations can be performed on the data and on the structure of the database. There are three integrity rules defined for a relational databse,which are:-

Distinct Rows in a Table - this rule says that all the rows of a table should be distinct to avoid in ambiguity while accessing the rows of that table. Most of the modern database management systems can be configured to avoid duplicate rows.

Entity Integrity (A Primary Key or part of it cannot be null) - this rule says that 'null' is special value in a relational database and it doesn't mean blank or zero. It means the unavailability of data and hence a 'null' primary key would not be a complete identifier. This integrity rule is also termed as entity integirty.

Referential Integrity - this rule says that if a foreign key is defined on a table then a value matching that foreign key value must exist as th e primary key of a row in some other table.

The following are the integrity rules to be satisfied by any relation. • No Component of the Primary Key can be null. • The Database must not contain any unmatched Foreign Key values. This is called the

referential integrity rule. Unlike the case of Primary Keys, there is no integrity rule saying that no component of the

foreign key can be null. This can be logically explained with the help of the following example: Consider the relations Employee and Account as given below. Employee

Emp# EmpName EmpCity EmpAcc#

X101 Shekhar Bombay 120001

X102 Raj Pune 120002

X103 Sharma Nagpur Null

X104 Vani Bhopal 120003

Account

ACC# OpenDate BalAmt

120001 30-Aug-1998 5000

120002 29-Oct-1998 1200

120003 01-Jan-1999 3000

120004 04-Mar-1999 500

10

Page 11: Assinment 2nd Sem

EmpAcc# in Employee relation is a foreign key creating reference from Employee to Account. Here, a Null value in EmpAcc# attribute is logically possible if an Employee does not have a bank account. If the business rules allow an employee to exist in the system without opening an account, a Null value can be allowed for EmpAcc# in Employee relation.

In the case example given, Cust# in Ord_Aug cannot accept Null if the business rule insists that the Customer No. needs to be stored for every order placed.

2.2 Relational Operators:

In the relational model, the database objects seen so far have specific names:

Name Meaning

Relation Table

Tuple Record(Row)

Attribute Field(Column)

Cardinality Number of Records(Rows)

Degree(or Arity) Number of Fields(Columns)

View Query/Answer table

On these objects, a set of operators (relational operators) is provided to manipulate them:

1. Restrict

2. Project

3. Union

4. Difference

5. Product

6. Intersection

7. Join

8. Divide

Restrict:

11

Page 12: Assinment 2nd Sem

Restrict simply extract records from a table.

it is also known as “Select”, but not the same SELECT as defined in SQL.

Project:

Project selects zero or more fields from a table and generates a new table

that contains all of the records and only the selected fields (with no duplications).

Union:

Union creates a new table by adding the records of one table to another

tables, must be compatible: have the same number of fields and each of the field pairs has to have values in the same domain.

Difference:

The difference of two tables is a third table which contains the records which appear in the first BUT NOT in the second.

Product:

The product of two tables is a third which contains all of the records in the first one added to each of the records in the second.

Intersection:

The intersection of two tables is a third tables which contains the records which are common to both.

Join:

The join of two tables is a third which contains all of the records in the first and the second which are related.

12

Page 13: Assinment 2nd Sem

Divide:

Dividing a table by another table gives all the records in the first which have values in their fields matching ALL the records in the second.

The eight relational algebra operators are

1. SELECT – To retrieve specific tuples/rows from a relation.

Ord#OrdDate Cust#

101 02-08-94 002

104 18-09-94 002

2. PROJECT – To retrieve specific attributes/columns from a relation.

DescriptionPrice

Power Supply 4000

101-Keyboard 2000 2000

Mouse 800 800

13

Page 14: Assinment 2nd Sem

MS-DOS 6.0 5000 5000

MS-Word 6.0 8000 8000

3. PRODUCT – To obtain all possible combination of tuples from two relations.

Ord#OrdDate O.Cust# C.Cust# CustName City

101 02-08-94 002 001 Shah Bombay

101 02-08-94 002 002 Srinivasan Madras

101 02-08-94 002 003 Gupta Delhi

101 02-08-94 002 004 Banerjee Calcutta

101 02-08-94 002 005 Apte Bombay

102 11-08-94 003 001 Shah Bombay

102 11-08-94 003 002 Srinivasan Madras

4. UNION – To retrieve tuples appearing in either or both the relations participating in the UNION.

Eg: Consider the relation Ord_Jul as follows (Table: Ord_Jul)

Ord# OrdDate Cust#

101 03-07-94 001

102 27-07-94 003

101 02-08-94 002

102 11-08-94 003

14

Page 15: Assinment 2nd Sem

103 21-08-94 003

104 28-08-94 002

105 30-08-94 005

Note: The union operation shown above logically implies retrieval of records of Orders placed in July or in August

5. INTERSECT – To retrieve tuples appearing in both the relations participating in the INTERSECT.

Eg: To retrieve Cust# of Customers who’ve placed orders in July and in August

Cust#

003

6. DIFFERENCE – To retrieve tuples appearing in the first relation participating in the DIFFERENCE but not the second.

Eg: To retrieve Cust# of Customers who’ve placed orders in July but not in August

Cust#

001

15

Page 16: Assinment 2nd Sem

7. JOIN – To retrieve combinations of tuples in two relations based on a common field in both the relations.

Eg:

ORD_AUG join CUSTOMERS (here, the common column is Cust#)

Ord# OrdDate Cust# CustNames City

101 02-08-94 002 Srinivasan Madras

102 11-08-94 003 Gupta Delhi

103 21-08-94 003 Gupta Delhi

104 28-08-94 002 Srinivasan Madras

105 30-08-94 005 Apte Bombay

Note: The above join operation logically implies retrieval of details of all orders and the details of the corresponding customers who placed the orders. Such a join operation where only those rows having corresponding rows in the both the relations are retrieved is called the natural join or inner join. This is the most common join operation.

Consider the example of EMPLOYEE and ACCOUNT relations.

EMPLOYEE

EMP # EmpName EmpCity Acc#

X101 Shekhar Bombay 120001

X102 Raj Pune 120002

X103 Sharma Nagpur Null

X104 Vani Bhopal 120003

ACCOUNT

Acc# OpenDate BalAmt

120001 30. Aug. 1998 5000

120002 29. Oct. 1998 1200

120003 1. Jan. 1999 3000

120004 4. Mar. 1999 500

16

Page 17: Assinment 2nd Sem

A join can be formed between the two relations based on the common column Acc#. The result of the (inner) join is :

Emp# EmpName EmpCity Acc# OpenDate BalAmt

X101 Shekhar Bombay 120001 30. Aug. 1998 5000

X102 Raj Pune 120002 29. Oct. 1998 1200

X104 Vani Bhopal 120003 1. Jan 1999 3000

Note that, from each table, only those records which have corresponding records in the other table appear in the result set. This means that result of the inner join shows the details of those employees who hold an account along with the account details.

The other type of join is the outer join which has three variations – the left outer join, the right outer join and the full outer join. These three joins are explained as follows:

The left outer join retrieves all rows from the left-side (of the join operator) table. If there are corresponding or related rows in the right-side table, the correspondence will be shown. Otherwise, columns of the right-side table will take null values.

EMPLOYEE left outer join ACCOUNT gives:

Emp# EmpName EmpCity Acc# OpenDate BalAmt

X101 Shekhar Bombay 120001 30. Aug. 1998 5000

X102 Raj Pune 120002 29. Oct. 1998 1200

X103 Sharma Nagpur NULL NULL NULL

X104 Vani Bhopal 120003 1. Jan 1999 3000

The right outer join retrieves all rows from the right-side (of the join operator) table. If there are corresponding or related rows in the left-side table, the correspondence will be shown. Otherwise, columns of the left-side table will take null values.

EMPLOYEE right outer join ACCOUNT gives:

17

Page 18: Assinment 2nd Sem

Emp# EmpName EmpCity Acc# OpenDate BalAmt

X101 Shekhar Bombay 120001 30. Aug. 1998 5000

X102 Raj Pune 120002 29. Oct. 1998 1200

X104 Vani Bhopal 120003 1. Jan 1999 3000

NULL NULL NULL 120004 4. Mar. 1999 500

(Assume that Acc# 120004 belongs to someone who is not an employee and hence the details of the Account holder are not available here)

The full outer join retrieves all rows from both the tables. If there is a correspondence or relation between rows from the tables of either side, the correspondence will be shown. Otherwise, related columns will take null values.

EMPLOYEE full outer join ACCOUNT gives:

Emp# EmpName EmpCity Acc# OpenDate BalAmt

X101 Shekhar Bombay 120001 30. Aug. 1998 5000

X102 Raj Pune 120002 29. Oct. 1998 1200

X103 Sharma Nagpur NULL NULL NULL

X104 Vani Bhopal 120003 1. Jan 1999 3000

NULL NULL NULL 120004 4. Mar. 1999 500

8. DIVIDE

Consider the following three relations:

R1 divide by R2 per R3 gives:

a

18

Page 19: Assinment 2nd Sem

Thus the result contains those values from R1 whose corresponding R2 values in R3 include all R2 values.

2.3 Linear Search

Linear search, also known as sequential search, means starting at the beginning of the data and checking

each item in turn until either the desired item is found or the end of the data is reached. Linear search is

a search algorithm, also known as sequential search that is suitable for searching a list of data for a

particular value. It operates by checking every element of a list one at a time in sequence until a match

is found. The Linear Search, or sequential search, is simply examining each element in a list one by one

until the desired element is found. The Linear Search is not very efficient. If the item of data to be found

is at the end of the list, then all previous items must be read and checked before the item that matches

the search criteria is found. This is a very straightforward loop comparing every element in the array

with the key. As soon as an equal value is found, it returns. If the loop finishes without finding a match,

the search failed and -1 is returned. For small arrays, linear search is a good solution because it's so

straightforward. In an array of a million elements linear search on average will take500, 000

comparisons to find the key. For a much faster search, take a look at binary search.

Algorithm

For each item in the database

if the item matches the wanted info

exit with this item

Continue loop

wanted item is not in database

19

Page 20: Assinment 2nd Sem

2.4 Collision Chain:

In computer science, a hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys (e.g., a person's name), to their associated values (e.g., their telephone number). Thus, a hash table implements an associate array. The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought.

Ideally, the hash function should map each possible key to a unique slot index, but this ideal is rarely achievable in practice (unless the hash keys are fixed; i.e. new entries are never added to the table after it is created). Instead, most hash table designs assume that hast collisions—different keys that map to the same hash value—will occur and must be accommodated in some way.

3. Discuss the correspondences between the ER model constructs and the relational model

constructs. Show how each ER model construct can be mapped to the relational model, and

discuss any alternative mappings.

Ans:Relational Data Model:The model uses the concept of a mathematical relation-which looks somewhat like a table of values-as its basic building block, and has its theoretical basis in set theory and first order predicate logic.The relational model represents the database a collection of relations. Each relation resembles a table of values or, to some extent, a “flat” file of records. When a relation is thought of as a table of values, each row in the table represents a collection of related data values. In the relation model, each row in the table represents a fact that typically corresponds to a real-world entity or relationship. The table name and column names are used to help in interpreting the meaning of the values in each row. In the formal relational model terminology, a row is called a tuple, a column header is called an attribute, and the table is called a relation. The data type describing the types of values that can appear in each column is represented by domain of possible values.ER Model:An entity-relationship model (ERM) is an abstract and conceptual representation of data. Entity-relationship modeling is a database modeling method, used to produce a type of conceptual schema or semantic data model of a system, often a relational database, and its requirements in a top-down fashion. Diagrams created by this process are called entity-relationship diagrams, ER diagrams, or ERDs.

The first stage of information system design uses these models during the requirements analysis to describe information needs or the type of information that is to be stored in a database. In the case of the design of an information system that is based on a database, the conceptual data model is, at a later stage (usually called logical design), mapped to a logical data model, such as the relational model; this in turn is mapped to a physical model during physical design. We create a relational schema from an entity-relationship(ER) schema.In the case of the design of an information system that is based on a database, the conceptual data model is, at a later stage (usually called logical design), mapped to a logical data model, such as the relational model; this in turn is mapped to a physical model during physical design. Sometimes, both of these phases are referred to as "physical design". Key elements of this model are entities, attributes, identifiers and relationships.

20

Page 21: Assinment 2nd Sem

Correspondence between ER and Relational Models:

ER Model Relational ModelEntity type “Entity” relation1:1 or 1:N relationship type Foregin keyM:N relationship type “Relationship” relation and two foreign keysn ary relationship type “Relationship” relation and n foreign keysSimple attributes AttributesComposite attributes Set of simple component attributesMultivalued attributes Relation and foreign keyValue set DomainKey attribute Primary key or secondary key

Lets take COMPANY database example:

21

Page 22: Assinment 2nd Sem

The COMPANY ER schema is below:

1

Result of mapping the company ER schema into a relational database schema:

EMPLOYEE

FNAME INITIAL LNAME ENO DOB ADDRESS SEX SALARY SUPERENO

DNO

22

EMPLOYEE

address

salarysex

Lname

Initial

Fname

Name

END

DOB

DEPARTMENT

LocationName

Number

NoOfEmployee

WORKS_FOR

MANAGES

DEPENDENTS_OF

CONTROLS

WORKSON

SUPERVISION

StartDate

HOURS

PROJECT

Name

Number

Location

Relationship

DOB

SexName

DEPENDENT

Page 23: Assinment 2nd Sem

DEPARTMENT

DNAME DNUMBER MGRENO MGRSTARTDATE

DEPT_LOCATIONS

DNUMBER DLOCATION

PROJECT

PNAME PNUMBER PLOCATION DNUM

WORKS_ON

EENO PNO HOURS

DEPENDENT

EENO DEPENDENT_NAME SEX DOB RELATIONSHIP

Mapping of regular entity types:

For each regular entity type E in the ER schema, create a relation R that includes all the simple attributes of E. Include only the simple component attributes of a composite attribute. Choose one of the key attributes of E as primary key for R. If the chosen key of E is composite, the set of simple attributes that form it will together the primary key of R.If multiple keys were identified for E during the conceptual design, the information describing the attributes that form each additional key is kept in order to specify secondary (unique) keys of relation R. Knowledge about keys is also kept for indexing purpose and other types of analyses.We create the relations EMPLOYEE, DEPARTMENT, and PROJECT in to correspond to the regular entity types EMPLOYEE, DEPARTMENT, and PROJECT. The foreign key and relationship attributes,

23

Page 24: Assinment 2nd Sem

if any, are not include yet; they will be added during subsequent steps. These, include the attributes SUPERENO and DNO of EMPLOYEE, MGRNO and MGRSTARTDATE of DEPARTMENT, and DNUM of PROJECT. We choose ENO, DNUMBER, and PNUMBER as primary keys for the relations EMPLOYEE, DEPARTMENT, and PROJECT, respectively. Knowledge that DNAME of DEPARTMENT and PNAME of PROJCET are secondary keys is kept for possible use later in the design.The relation that is created from the mapping of entity types are sometimes called entity relations because each tuyple represents an entity instance.

4 Define the following terms: disk, disk pack, track, block, cylinder, sector, interblock gap,

read/write head.

Ans:Disk:Disk s are used for storing large amounts of data. The most basic unit of data on the disk is a single bit of information. By magnetizing a area on disk in certain ways, one can make it represent a bit value of either 0 or 1. To code information, bits are grouped into bytes. Byte sizes are typically 4 to 8 bits, depending on the computer and the device. We assume that one character is stored in a single byte, and we use the terms byte and character interchangeably. The capacity of a disk is the number of bytes it can store, which is usually very large. Small floppy disks used with microcomputers typically hold from 400 kbytes to 1.5 Mbytes; hard disks for micros typically hold from several hundred Mbytes up to a few Gbytes. Whatever their capacity, disks are all made of magnetic material shaped as a thin circular disk and protected by a plastic or acrylic cover. A disk is single-sided if it stores information on only one of its surface and double-sided if both surfaces are used.

Disk Packs:

To increase storage capacity, disks are assembled into a disk pack, which may include many disks and hence many surfaces. A Disk pack is a layered grouping of hard disk platters (circular, rigid discs coated with a magnetic data storage surface). Disk pack is the core component of a hard disk drive. In modern hard disks, the disk pack is permanently sealed inside the drive. In many early hard disks, the disk pack was a removable unit, and would be supplied with a protective canister featuring a lifting handle.

Track and cylinder:The (circular) area on a disk platter which can be accessed without moving the access arm of the drive is called track. Information is stored on a disk surface in concentric circles of small width, for each having a distinct diameter. Each circle is called a track. For disk packs, the tracks with the same diameter on the various surfaces are called cylinder because of the shape

24

Page 25: Assinment 2nd Sem

they would form if connected in space. The set of tracks of a disk drive which can be accessed without changing the position of the access arm are called cylinder. 

The number of tracks on a disk range from a few hundred to a few thousand, and the capacity of each track typically range from tens of Kbytes to 150 Kbytes.

Sector: A fixed size physical data block on a disk drive.A track usually contains a large amount of information; it is divided into smaller blocks or sectors. The division of a track into sectors is hard-coded on the disk surface and cannot be changed. One type of sector organization calls a portion of a track that subtends a fixed angle at the center as a sector. Several other sector organizations are possible, one of which is to have the sectors subtend smaller angles at the center as one moves away, thus maintaining a uniform density of recording.

Block and Interblock Gaps: A physical data record, separated on the medium from other blocks by inter-block gaps is called block. The division of a track into equal sized disk blocks is set by the operating system during disk formatting. Block size is fixed during initialization and cannot be changed dynamically. Typical disk block sizes range from 512 to 4096 bytes. A disk with hard coded sectors often has the sectors subdivided into blocks during initialization. An area between data blocks which contains no data and which separates the blocks is called interblock gap.  Blocks are separated by fixed size interblock gaps, which include specially coded control information written during disk initialization. This information is used to determine which block on the track follows each interblock gap.

Read/write Head:A tape drive is required to read the data from or to write the data to a tape reel. Usually, each group of bits that forms a byte is stored across the tape, and the bytes themselves are stored consecutively on the tape. A read/write head is used to read or write data on tape. Data records on tape are also stored in blocks-although the blocks may be substantially larger than those for disks, and interblock gaps are also quite large. With typical tape densities of 1600 to 6250 bytes per inch, a typical interblock gap of 0.6 inches corresponds to 960 to 3750 bytes of wasted storage space.

25

Page 26: Assinment 2nd Sem

July 2011Master of Computer Application (MCA) – Semester 2

MC0067 – Database Management System(DBMS and Oracle 9i) (Book ID: B0716 & B0717)

Assignment Set – 2

1. Explain the purpose of Data Modeling. What are the basic constructs of E-R Diagrams?

Ans:1Data modeling in is the process of creating a data model by applying formal data model descriptions using data modeling techniques.

Data modeling is the act of exploring data-oriented structures.  Like other modeling artifacts data models can be used for a variety of purposes, from high-level conceptual models to physical data models. 

Data modeling is the formalization and documentation of existing processes and events that occur during application software design and development. Data modeling techniques and tools capture and translate complex system designs into easily understood representations of the data flows and processes, creating a blueprint for construction and/or re-engineering. 

Basic Constructs of E-R Modeling:The ER model views the real world as a construct of entities and association between entities. The basic constructs of ER modeling are entities, attributes, and relationships.Entity:

An entity may be defined as a thing which is recognized as being capable of an independent existence and which can be uniquely identified. An entity is an abstraction from the complexities of some domain. When we speak of an entity we normally speak of some aspect of the real world which can be distinguished from other aspects of the real world.

An entity may be a physical object such as a house or a car, an event such as a house sale or a car service, or a concept such as a customer transaction or order. Although the term entity is the one most commonly used, following Chen we should really distinguish between an entity and an entity-type. An

26

Page 27: Assinment 2nd Sem

entity-type is a category. An entity, strictly speaking, is an instance of a given entity-type. There are usually many instances of an entity-type. Because the term entity-type is somewhat cumbersome, most people tend to use the term entity as a synonym for this term.

Entities can be thought of as nouns. Examples: a computer, an employee, a song, a mathematical theorem.

Relationship:

A relationship captures how two or more entities are related to one another. Relationships can be thought of as verbs, linking two or more nouns. Examples: an owns relationship between a company and a computer, a supervises relationship between an employee and a department, a performs relationship between an artist and a song, a proved relationship between a mathematician and a theorem.

Attributes:

Entities and relationships can both have attributes. Examples: an employee entity might have a Social Security Number (SSN) attribute; the proved relationship may have a date attribute.

2. Write about:

Types of Discretionary Privileges

Propagation of Privileges using Grant Option

Physical Storage Structure of DBMS

Indexing

Ans:2Types of Discretionary Privileges:The concept of an authorization identifier is used to refer, to a user account. The DBMS must provide selective access to each relation in the database based on specific accounts. There are two levels for assigning privileges to use use the database system:

The account level: At this level, the DBA specifies the particular privileges that each account holds independently of the relations in the database.

The relation (or table level): At this level, the DBA can control the privilege to access each individual relation or view in the database.

The privileges at the account level apply to the capabilities provided to the account itself and can include the CREATE SCHEMA or CREATE TABLE privilege, to create a schema or base relation; the CREATE VIEW privilege; the ALTER privilege, to apply schema changes such adding or removing attributes from relations; the DROP privilege, to delete relations or views; the MODIFY privilege, to insert, delete, or update tuples; and the SELECT privilege, to retrieve information from the database by using a SELECT query.The second level of privileges applies to the relation level, whether they are base relations or virtual (view) relations.The granting and revoking of privileges generally follow an authorization model for discretionary privileges known as the access matrix model, where the rows of a matrix M represents subjects (users, accounts, programs) and the columns represent objects (relations, records, columns, views, operations).

27

Page 28: Assinment 2nd Sem

Each position M(i,j) in the matrix represents the types of privileges (read, write, update) that subject i holds on object j. To control the granting and revoking of relation privileges, each relation R in a database is assigned and owner account, which is typically the account that was used when the relation was created in the first place. The owner of a relation is given all privileges on that relation. The owner account holder can pass privileges on R to other users by granting privileges to their accounts.In SQL the following types of privileges can be granted on each individual relation R:

SELECT (retrieval or read) privilege on R: Gives the account retrieval privilege. In SQL this gives the account the privilege to use the SELECT statement to retrieve tuples from R.

MODIFY privileges on R: This gives the account the capability to modify tuples of R. In SQL this privilege is further divided into UPDATE, DELETE, and INSERT privileges to apply the corresponding SQL command to R. In addition, both the INSERT and UPDATE privileges can specify that only certain attributes can be updated or inserted by the account.

REFERENCES privilege on R: This gives the account the capability to reference relation R when specifying integrity constraints. The privilege can also be restricted to specific attributes of R.

Propagation of Privileges using the GRANT OPTION:Whenever the owner A of a relation R grants a privilege on R to another account B, privilege can be given to B with or without the GRANT OPTION. If the GRANT OPTION is given, this means that B can also grant that privilege on R to other accounts. Suppose that B is given the GRANT OPTION by A and that B then grants the privilege on R to a third account C, also with GRANT OPTION. In this way, privileges on R can propagate to other accounts without the knowledge of the owner of R. If the owner account A now revokes the privilege granted to B, all the privileges that B propagated based on that privilege should automatically be revoked by the system.

Physical Storage Structure of DBMS:

The physical design of the database specifies the physical configuration of the database on the

storage media. This includes detailed specification of data elements, data types, indexing

options and other parameters residing in the DBMS data dictionary. It is the detailed design of a

system that includes modules & the database's hardware & software specifications of the

system. Physical structures are those that can be seen and operated on from the operating

system, such as the physical files that store data on a disk.

• Basic Storage Concepts (Hard Disk)

• disk access time = seek time + rotational delay

• disk access times are much slower than access to main memory.

overriding DBMS performance objective is to minimise the number of disk accesses (disk I/Os)

Indexing:

Data structure allowing a DBMS to locate particular records more quickly and hence speed up

queries.Book index has index term (stored in alphabetic order) with a page number.Database

28

Page 29: Assinment 2nd Sem

index (on a particular attribute) has attribute value (stored in order) with a memory address.An

index gives direct access to a record and prevents having to scan every record sequentially to

find the one required.

• Using SUPPLIER(Supp# , SName, SCity)

Consider the query Get all the suppliers in a certain city ( e.g. London)

2 possible strategies:

a. Search the entire supplier file for records with city 'London'

b. Create an index on cities, access it for 'London’ entries and follow the pointer to the

corresponding records

SCity Index Supp# SName SCity

Dublin S1 Smith London

London S2 Jones Paris

London S3 Brown Paris

Paris S4 Clark London

Paris S5 Ellis Dublin

3. What is a relationship type? Explain the differences among a relationship instance, a

relationship type, and a relationship set

Ans:4

There are three type of relationships

1) One to one

2) One to many

3) Many to many

Say we have table1 and table2

For one to one relationship, a record(row) in table1 will have at most one matching record or row in table2

29

Page 30: Assinment 2nd Sem

I.e. it mustn’t have two matching records or no matching records in table2.

For one to many, a record in table1 can have more than one record in table2 but not vice versa

Let’s take an example,

Say we have a database which saves information about Guys and whom they are dating.

We have two tables in our database Guys and Girls

Guy id Guy name

1 Andrew

2 Bob

3 Craig

Girl id Girl name

1 Girl1

2 Girl2

3 Girl3

Here in above example Guy ID and Girl ID are primary keys of their respective table.

Say Andrew is dating Girl1, Bob – Girl2 and Craig is dating Girl3.

So we are having a one to one relationship over there.

So in this case we need to modify the Girls table to have a Guy id foreign key in it.

Girl id Girl name Guy id

1 Girl1 1

2 Girl2 2

3 Girl3 3

Now let say one guy has started dating more than one girl.

i.e. Andrew has started dating Girl1 and say a new Girl4

That takes us to one to many relationships from Guys to Girls table.

Now to accommodate this change we can modify our Girls table like this

Girl Id Girl Name Guy Id

1 Girl1 1

30

Page 31: Assinment 2nd Sem

2 Girl2 2

3 Girl3 3

4 Girl4 1

Now say after few days, comes a time where girls have also started dating more than one boy i.e. many to many relationships

So the thing to do over here is to add another table which is called Junction Table, Associate Table or linking Table which will contain primary key columns of both girls and guys table.

Let see it with an example

Guy id Guy name

1 Andrew

2 Bob

3 Craig

Girl id Girl name

1 Girl1

2 Girl2

3 Girl3

Andrew is now dating Girl1 and Girl2 and

Now Girl3 has started dating Bob and Craig

so our junction table will look like this

Guy ID Girl ID

1 1

1 2

2 2

2 3

3 3

It will contain primary key of both the Girls and Boys table.

31

Page 32: Assinment 2nd Sem

A relationship type R among n entity types E1, E2, …, En is a set of associations among entities from these types. Actually, R is a set of relationship instances ri where each ri is an n-tuple of entities (e1, e2, …, en), and each entity ej in ri is a member of entity type Ej, 1≤j≤n. Hence, a relationship type is a mathematical relation on E1, E2, …, En, or alternatively it can be defined as a subset of the Cartesian product E1x E2x … xEn . Here, entity types E1, E2, …, En defines a set of relationship, called relationship sets.

Relationship instance: Each relationship instance ri in R is an association of entities, where the association includes exactly one entity from each participating entity type. Each such relationship instance ri represent the fact that the entities participating in ri are related in some way in the corresponding miniworld situation. For example, in relationship type WORKS_FOR associates one EMPLOYEE and DEPARTMENT, which associates each employee with the department for which the employee works. Each relationship instance in the relationship set WORKS_FOR associates one EMPLOYEE and one DEPARTMENT.

4. Write about:

Categories of Data Models

Schemas, Instances and Database States

With an example for each

ANS.

Categories of Data Models

Database model

A database model is a theory or specification describing how a database is structured and used. Several such models have been suggested. Common models include:

Flat model

 

32

Page 33: Assinment 2nd Sem

Hierarchical model

 

Network model

 

Relational model

Flat model: This may not strictly qualify as a data model. The flat (or table) model consists of a single, two-dimensional array of data elements, where all members of a given column are assumed to be similar values, and all members of a row are assumed to be related to one another.

Hierarchical model: In this model data is organized into a tree-like structure, implying a single upward link in each record to describe the nesting, and a sort field to keep the records in a particular order in each same-level list.

Network model: This model organizes data using two fundamental constructs, called records and sets. Records contain fields, and sets define one-to-many relationships between records: one owner, many members.

Relational model: is a database model based on first-order predicate logic. Its core idea is to describe a database as a collection of predicates over a finite set of predicate variables, describing constraints on the possible values and combinations of values.

Concept-oriented model

33

Page 34: Assinment 2nd Sem

 

Star schema

Object-relational model: Similar to a relational database model, but objects, classes and inheritance are directly supported in database schemas and in the query language.

Star schema is the simplest style of data warehouse schema. The star schema consists of a few "fact tables" (possibly only one, justifying the name) referencing any number of "dimension tables". The star schema is considered an important special case of the snowflake schema.

Schemas, Instances and Database States With an example for each.

34

Page 35: Assinment 2nd Sem

35

Page 36: Assinment 2nd Sem

July 2011Master of Computer Application (MCA) – Semester 2

MC0068 – Data Structures using c (Book ID: B0701 & B0702)Assignment Set – 1

1--Describe the theory and applications of Double Ended Queues (Deque) and circular queuesAns. Double Ended Queues (Deque):- Like an ordinary queue, a double-ended queue is a container. It supports the following operations: enq_front, enq_back, deq_front, deq_back, and empty.

By choosing a subset of these operations, you can make the double-ended queue behave like a stack or like a queue. For instance, if you use only enq_front and deq_front you get a stack, and if you use only enq_front and deq_back you get a queue.

By now, the reader should be used to using header objects in order to obtain uniform reference semantics. We will therefore go directly to a version of the double-ended queue with a separate header file and implementation file.

Example:-

#include "dqueue.h" #include "dlist.h" #include < stdlib.h>

struct dqueue {

36

Page 37: Assinment 2nd Sem

dlist head; dlist tail; };

dqueue dq_create(void) { dqueue q = malloc(sizeof(struct dqueue)); q -> head = q -> tail = NULL; return q; }

int dq_empty(dqueue q) { return q -> head == NULL; }

void dq_enq_front(dqueue q, void *element) { if(dq_empty(q)) q -> head = q -> tail = dcons(element, NULL, NULL); else { q -> head -> prev = dcons(element, NULL, q -> head);

q -> head -> prev -> next = q -> head;

q -> head = q -> head -> prev; } }

void dq_enq_back(dqueue q, void *element) { if(dq_empty(q)) q -> head = q -> tail = dcons(element, NULL, NULL); else { q -> tail -> next = dcons(element, q -> tail, NULL);

q -> tail -> next -> prev = q -> tail;q -> tail = q -> tail -> next;

} }

void * dq_deq_front(dqueue q)

{ assert(!empty(q)); { dqueue temp = q -> head; void *element = temp -> element; q -> head = q -> head -> next; free(temp); if(q -> head == NULL) q -> tail = NULL; else q -> head -> prev = NULL; return element; } }

void * dq_deq_back(dqueue q) { assert(!empty(q)); { dqueue temp = q -> tail; void *element = temp -> element; q -> tail = q -> tail -> prev; free(temp); if(q -> tail == NULL) q -> head = NULL; else q -> tail -> next = NULL; return element; } }

37

Page 38: Assinment 2nd Sem

circular queues:- A circular queue is a particular implementation of a queue. It is very efficient. It is also quite useful in low level code, because insertion and deletion are totally independant, which means that you don't have to worry about an interrupt handler trying to do an insertion at the same time as your main code is doing a deletion.

Example:-

#include <stdio.h>#include <stdlib.h>

#define MAX 10

void insert(int queue[], int *rear, int front, int value){   *rear= (*rear +1) % MAX;   if(*rear == front)   {      printf("The queue is full can not insert a value\n");      exit(0);   }   queue[*rear] = value;}

void delete(int queue[], int *front, int rear, int * value){   if(*front == rear)   {      printf("The queue is empty can not delete a value\n");      exit(0);   }   *front = (*front + 1) % MAX;   *value = queue[*front];}

void main(){   int queue[MAX];   int front,rear;   int n,value;

4

Page 39: Assinment 2nd Sem

   front=0; rear=0;

   insert(queue,&rear,front,1);   insert(queue,&rear,front,2);   insert(queue,&rear,front,3);   insert(queue,&rear,front,4);     delete(queue,&front,rear,&value);   printf("The value deleted is %d\n",value);

   delete(queue,&front,rear,&value);   printf("The value deleted is %d\n",value);

   delete(queue,&front,rear,&value);   printf("The value deleted is %d\n",value);}

2. Illustrate the C program to represents the Stack Implementation on POP and PUSHoperation.Ans:2#include<studio.h>#include<conio.h>#define Max 5Int Staff [Max], top=-1;Void display(){If ((top==-1 || (top==0))MC0068 – Data Structures using(Book ID: B0701 & B0702){Printf(“\n stack is full\n”);}Else{Printf(“\n stack elements are\n”);For(int i=top-1;i>=0;i--)}}void push(){ int ele;char ch;it(top-=-1)top=0;do{If (top>=5){Printf(“\n stack is full”);

4

Page 40: Assinment 2nd Sem

Break;}Else{Clrscr();Printf(“\n enter the element to be insearted\n”);Scanf(“%d”, &ele);Staff(top++)=eledisplay();}Printf(“\n Do u want to add more elements:?\n”);Scanf(“\n%c”, &ch);}While ((ch==’y’ ||(ch==’Y’));}void pop(){If ((top==-1)||(top==0){Printf(“\nstack is under flow\n”);}Else{Printf(“%d is deleted fro stack\n”,Staff(--top]”);display();}}Void main(){MC0068 – Data Structures using(Book ID: B0701 & B0702)clrscr();char c;int choice;do{cirscr();printf(“\n enter the choice\n”);printf(“1->push\n”);printf(“2-pop\n”);scant(“%d”, &choice);if(choice==1)push();elshif(choice==2)pop();elseprintf(“\in valid choice”);printf(“\n do u want to continue:?”);scanf(“\n%c”, &c);}While{(c==’y’)||(c==’Y’));}

4

Page 41: Assinment 2nd Sem

3. Show the result of inserting 3, 1, 4, 5, 2, 9, 6, 8 into aa) bottom-up splay treeb) top-down splay tree.Ans:3Splay TreesWe shall describe the algorithm by giving three rewrite rules in the form of pictures. In thesepictures, x is the node that was accessed (that will eventually be at the root of the tree). Bylooking at the local structure of the tree defined by x, x’s parent, and x’s grandparent we decidewhich of the following three rules to follow. We continue to apply the rules until x is at the rootof the tree:MC0068 – Data Structures using(Book ID: B0701 & B0702)Notes1) Each rule has a mirror image variant, which covers all the cases.2) The zig-zig rule is the one that distinguishes splaying from just rotating x to the root of thetree.3) Top-down splaying is much more efficient in practice.The Basic Bottom-Up Splay Tree• A technique called splaying can be used so a logarithmic amortized bound can beachieved.• We use rotations such as we’ve seen before.• The zig case.o Let X be a non-root node on the access path on which we are rotating.o If the parent of X is the root of the tree, we merely rotate X and the root as shownin Figure 2.Figure 2 Zig Caseo This is the same as a normal single rotation.• The zig-zag case.o In this case, X and both a parent P and a grandparent G. X is a right child and P isa left child (or vice versa).MC0068 – Data Structures using(Book ID: B0701 & B0702)o This is the same as a double rotation.o This is shown in Figure 3.The zig-zig case.o This is a different rotation from those we have previously seen.o Here X and P are either both left children or both right children.o The transformation is shown in Figure 4.o This is different from the rotate-to-root. Rotate-to-root rotates between X and Pand then between X and G. The zig-zig splay rotates between P and G and X andP.Figure 4 Zig-zig Case• Given the rotations, consider the example in Figure 5, where we are splaying c.Top-Down Splay Trees• Bottom-up splay trees are hard to implement.• We look at top-down splay trees that maintain the logarithmic amortized bound.o This is the method recommended by the inventors of splay trees.• Basic idea – as we descend the tree in our search for some node X, we must take thenodes that are on the access path, and move them and their subtrees out of the way. Wemust also perform some tree rotations to guarantee the amortized time bound.MC0068 – Data Structures using

4

Page 42: Assinment 2nd Sem

(Book ID: B0701 & B0702)• At any point in the middle of a splay, we have:o The current node X that is the root of its subtree.o Tree L that stores nodes less than X.o Tree R that stores nodes larger than X.• Initially, X is the root of T, and L and R are empty.• As we descend the tree two levels at a time, we encounter a pair of nodes.o Depending on whether these nodes are smaller than X or larger than X, they areplaced in L or R along with subtrees that are not on the access path to X.When we finally reach X, we can then attach L and R to the bottom of the middle tree,and as a result X will have been moved to the root.• We now just have to show how the nodes are placed in the different tree. This is shownbelow:o Zig rotation – Figure 7Zig-Zig – Figure 8MC0068 – Data Structures using(Book ID: B0701 & B0702)Zig-Zag – FigureMC0068 – Data Structures using(Book ID: B0701 & B0702)4. Discuss the techniques for allowing a hash file to expand and shrink dynamically.What are the advantages and disadvantages of each?Ans:4Dynamic Hashing:As the database grows over time, we have three options:1. Choose hash function based on current file size. Get performance degradation as filegrows.2. Choose has function based on anticipated file size. Space is wasted initially.3. Periodically re-organize hash structure as file grows. Requires selecting new hashfunction, recomputing all addresses and generating new bucket assignments.Some hashing techniques allow the hash function to be modified dynamically to accommodatethe growth or shrinking of the database. These are called dynamic hash functions. Extendablehashing is one form of dynamic hashing. Extendable hashing splits and coalesces buckets asdatabase size changes.Figure 11.9: General extendable hash structure.We choose a hash function that is uniform and random that generates values over arelatively large range.Range is b-bit binary integers (typically b=32).is over 4 billion, so we don't generate that many buckets!Instead we create buckets on demand, and do not use all b bits of the hash initially.At any point we use i bits where .The i bits are used as an offset into a table of bucket addresses.Value of i grows and shrinks with the database.Figure 11.19 shows an extendable hash structure.MC0068 – Data Structures using(Book ID: B0701 & B0702)Note that the i appearing over the bucket address table tells how many bits are requiredto determine the correct bucket.It may be the case that several entries point to the same bucket.All such entries will have a common hash prefix, but the length of this prefix may be lessthan i.

4

Page 43: Assinment 2nd Sem

So we give each bucket an integer giving the length of the common hash prefix.This is shown in Figure 11.9 (textbook 11.19) as .Number of bucket entries pointing to bucket j is then .To find the bucket containing search key value :Compute .Take the first i high order bits of .Look at the corresponding table entry for this i-bit string.Follow the bucket pointer in the table entry.We now look at insertions in an extendable hashing scheme.Follow the same procedure for lookup, ending up in some bucket j.If there is room in the bucket, insert information and insert record in the file.If the bucket is full, we must split the bucket, and redistribute the records.If bucket is split we may need to increase the number of bits we use in the hash.Two cases exist:1. If , then only one entry in the bucket address table points to bucket j.Then we need to increase the size of the bucket address table so that we can includepointers to the two buckets that result from splitting bucket j.We increment i by one, thus considering more of the hash, and doubling the size of thebucket address table.Each entry is replaced by two entries, each containing original value.Now two entries in bucket address table point to bucket j.We allocate a new bucket z, and set the second pointer to point to z.Set and to i.Rehash all records in bucket j which are put in either j or z.Now insert new record.MC0068 – Data Structures using(Book ID: B0701 & B0702)It is remotely possible, but unlikely, that the new hash will still put all of the records inone bucket.If so, split again and increment i again.2. If , then more than one entry in the bucket address table points to bucket j.Then we can split bucket j without increasing the size of the bucket address table(why?).Note that all entries that point to bucket j correspond to hash prefixes that have the samevalue on the leftmost bits.We allocate a new bucket z, and set and to the original value plus 1.Now adjust entries in the bucket address table that previously pointed to bucket j.Leave the first half pointing to bucket j, and make the rest point to bucket z.Rehash each record in bucket j as before.Reattempt new insert.Note that in both cases we only need to rehash records in bucket j.Deletion of records is similar. Buckets may have to be coalesced, and bucket address table mayhave to be halved.Insertion is illustrated for the example deposit file of Figure 11.20.32-bit hash values on bname are shown in Figure 11.21.An initial empty hash structure is shown in Figure 11.22.We insert records one by one.We (unrealistically) assume that a bucket can only hold 2 records, in order to illustrateboth situations described.As we insert the Perryridge and Round Hill records, this first bucket becomes full.When we insert the next record (Downtown), we must split the bucket.

4

Page 44: Assinment 2nd Sem

Since , we need to increase the number of bits we use from the hash.We now use 1 bit, allowing us buckets.This makes us double the size of the bucket address table to two entries.We split the bucket, placing the records whose search key hash begins with 1 in the newbucket, and those with a 0 in the old bucket (Figure 11.23).Next we attempt to insert the Redwood record, and find it hashes to 1.That bucket is full, and .So we must split that bucket, increasing the number of bits we must use to 2.This necessitates doubling the bucket address table again to four entries (Figure 11.24).MC0068 – Data Structures using(Book ID: B0701 & B0702)We rehash the entries in the old bucket.We continue on for the deposit records of Figure 11.20, obtaining the extendable hashstructure of Figure 11.25.Advantages:Extendable hashing provides performance that does not degrade as the file grows.Minimal space overhead - no buckets need be reserved for future use. Bucket addresstable only contains one pointer for each hash value of current prefix length.Disadvantages:Extra level of indirection in the bucket address tableAdded complexitySet-21. Explain the double ended queue with the help of suitable example.Ans:1A double-ended queue (dequeue, often abbreviated to deque, pronounced deck) is anabstract data structure that implements a queue for which elements can only be added to orremoved from the front (head) or back (tail). It is also often called a head-tail linked list.Deque is a special type of data structure in which insertions and deletions will bedone either at the front end or at the rear end of the queue. The operations that canbe performed on deques are· Insert an item from front end· Insert an item from rear end· Delete an item from front end· Delete an item from rear endMC0068 – Data Structures using(Book ID: B0701 & B0702)· Display the contents of queueThe three operations insert rear, delete front and display and the associated operations to checkfor an underflow and overflow of queue have already been discussed in ‘ordinary queue’. In thissection, other two operations i.e., insert an item at the front end and delete an item from the rearend are discussed.a) Insert at the front endConsider queue shown in above fig (a). Observe that, the front end identified by f is 0 and rearend identified by r is -1. Here, an item can be inserted first by incrementing r by 1 and then insertan item. If the front pointer f is not equal to 0 as shown in above fig. (b), an item can be insertedby decrementing the front pointer .f by 1 and then inserting an item at that position. Except forthese conditions, it is not possible to insert an item at the front end. For example, consider thequeue shown in above figure (c). Here, an item 10 is already present in the first positionidentified by f and so, it is not possible to insert an item. The complete C function to insert anitem is shown in below example.Example 1: Function to insert an item at the front end

4

Page 45: Assinment 2nd Sem

void insert_front(int item, int q[ ], int *f, int *r){if( *f= = 0 && *r = = -1)q[++(*r)] = item;else if ( *f ! = 0)q[--(*f)]=item;elseprintf("Front insertion not possible");}Delete from the rear endTo delete an element from the rear end, first access the rear element and then decrement rear endidentified by r. As an element is deleted, queue may become empty. If the queue is empty, resetthe front pointer f to 0 and rear pointer r to -1 as has been done in an ordinary queue. We deletean element only if queue is not empty. The complete C function to delete an item from the rearend is shown in below example.MC0068 – Data Structures using(Book ID: B0701 & B0702)Example 2: Function to delete an item from the rear end of queuevoid delete_rear(int q[],int *f, int *r){if ( qempty(*f,*r) ){printf("Queue underflown");return;}printf("The element deleted is %dn".q[(*r)--]);if (*f > *r){*f = 0, *r = -1 ;}}C program to Implement double-ended queue#include <stdio.h>#include <process.h>#define QUEUE_SIZE 5/* Include function to check for overflow 4.2.1 Eg.-1*//* Include function to check for underflow 4.2.1 Eg -3*//* Include function to insert an item at the front end 4.2. 3 Eg.-1*//* Include function to insert an item at the rear end 4.2.1 Eg -2*//* Include function to delete an item at the front end 4.2.1 Eg -4*//* Include function to delete an item at the rear end 4.2. 3 Eg.-2*//* Include function to display the contents of queue 4.2.1 Eg -5*/void main(){int choice,item,f,r,q [10];f=0; r = -1;for (;;){printf(" 1:Insert_front 2:lnsert_rearn");printf("3: Delete_front 4: Delete_rearn" );MC0068 – Data Structures using

4

Page 46: Assinment 2nd Sem

(Book ID: B0701 & B0702)printf("5: Display 6:Exitn");printf("Enter the choicen");scanf("%d" ,&choice );switch ( choice ){case 1:printf("Enter the item to be insertedn");scanf("%d",& item);insert_ front(item, q, &f, &r);break;case 2:printf("Enter the item to be insertedn");scanf("%d",& item);insert_rear(item, q, &r);break; case 3:delete _front(q, &f, &r);break;case 4:delete_rear(q, &f, &r);break;cases 5:display(q, f, r);break;default: .exit(0);}}}2. Explain Insert/Delete a node at the rear, front end from circular singly linked list.Ans:2MC0068 – Data Structures using(Book ID: B0701 & B0702)A singly linked circular list is a linked list where the last node in the list points to the first nodein the list. A circular list does not contain NULL pointers.With a circular list, a pointer to the last node gives easy access also to the first node, byfollowing one link. Thus, in applications that require access to both ends of the list (e.g., in theimplementation of a queue), a circular structure allows one to handle the structure by a singlepointer, instead of two.A circular list can be split into two circular lists, in constant time, by giving the addresses of thelast node of each piece. The operation consists in swapping the contents of the link fields ofthose two nodes. Applying the same operation to any two nodes in two distinct lists joins the twolist into one. This property greatly simplifies some algorithms and data structures, such as thequad-edge and face-edge.The simplest representation for an empty circular list (when such a thing makes sense) is a nullpointer, indicating that the list has no nodes. With this choice, many algorithms have to test forthis special case, and handle it separately. By contrast, the use of null to denote an emptylinear list is more natural and often creates fewer special cases.Insert a node at the rear end:Consider the list contains 4 nodes and last is a pointer variable that contains the address of thelast node.

4

Page 47: Assinment 2nd Sem

Let us insert the item 80 at the end of this list.Step 1:Obtain a free node temp from the availability list and store the item in info field. This canbe accomplished using the following statementsTemp=getnode();Temp->info=item;Step 2: Copy the address of the first node(i.e. last->link) into link field of newly obtained nodetemp and the statement to accomplish this task isTemp-> link=last->linkStep 3: Establish a link between the newly created node temp and the last node. This isachieved by copying the address of the node temp into link field of last node. The correspondingcode for this isLast->link=temp;Step 4: The new node is made as the last node using the statement:50 20 45 10MC0068 – Data Structures using(Book ID: B0701 & B0702)Return temp;These steps have designed by assuming the list already exists.Function to insert an item at the rear end of the list.NODE insert_rear(int item, NODE last){NODE temp;Temp=getnode();Temp->info=item;If(last==NULL)Last=temp;ElseEmp->link=last->link;Last->link=temp;Retrun temp;}Insert a node at the front end:Consider the list contains 4 nodes and a pointer variable last contains address of the last node.Step 1: To insert an item 50 at the front of the list, obtain a free node temp from the availabilitylist and store the item in info field. This can be accomplished using the following statementsTemp=getnode();Temp->info=item;Step 2: Copy the address of the first node(i.e. last->link) into link field of newly obtained nodetemp and the statement to accomplish this task isTemp->link=last->link.Step 3: Establish a link between the newly created node temp and the last node. This isachieved by copying the address of the node temp into link field of last node. The correspondingcode for this isLast->link=temp;Now, an item is successfully inserted at the front of the list. All these steps have been designedby assuming the list is already existing. If the list is empty, make temp itself as the last node andestablish a link between the first node and the last node. Repeatedly insert the items using theabove procedure to create a list.Function to insert an item at the front end of the list.NODE insert_front(int item, NODE last)20 45 10 80

4

Page 48: Assinment 2nd Sem

MC0068 – Data Structures using(Book ID: B0701 & B0702){NODE temp;Temp=getnode();Temp->info=item;If(last==NULL)Last=temp;Elsetemp->link=last->link;Last->link=temp;Return last;}3. a. Compare and contrast DFS and BFS and DFS+ID approachesb. Discuss how Splay Tree differs from a Binary Tree? Justify your answer withappropriate example.Ans:3 a)Once you’ve identified a problem as a search problem, it’s important to choose the right type ofsearch. Here are some information which may be useful while taking the decision.Search Time Space When to useDFS O(c^k) O(k)Must search tree anyway, know the level theanswers are on, or you aren’t looking for theshallowest number.BFS O(c^d) O(c^d) Know answers are very near top of tree, or wantshallowest answer.DFS+ID O(c^d) O(d) Want to do BFS, don’t have enough space, andcan spare the time.d is the depth of the answerk is the depth searchedd <= kRemember the ordering properties of each search. If the program needs to produce a list sortedshortest solution first (in terms of distance from the root node), use breadth first search oriterative deepening. For other orders, depth first search is the right strategy.If there isn’t enough time to search the entire tree, use the algorithm that is more likely to findthe answer. If the answer is expected to be in one of the rows of nodes closest to the root, usebreadth first search or iterative deepening. Conversely, if the answer is expected to be in theleaves, use the simpler depth first search. Be sure to keep space constraints in mind. If memory isMC0068 – Data Structures using(Book ID: B0701 & B0702)insufficient to maintain the queue for breadth first search but time is available, use iterativedeepening.B)Binary Tree:A binary tree is simply a tree in which each node can have at most two children.A binary search tree is a binary tree in which the nodes are assigned values, with the followingrestrictions ;-No duplicate values.-The left subtree of a node can only have values less than the node-The right subtree of a node can only have values greater than the nodeand recursively defined;

4

Page 49: Assinment 2nd Sem

-The left subtree of a node is a binary search tree.-The right subtree of a node is a binary search tree.Splay TreesWe shall describe the algorithm by giving three rewrite rules in the form of pictures. In thesepictures, x is the node that was accessed (that will eventually be at the root of the tree). Bylooking at the local structure of the tree defined by x, x’s parent, and x’s grandparent we decidewhich of the following three rules to follow. We continue to apply the rules until x is at the rootof the tree:Notes1) Each rule has a mirror image variant, which covers all the cases.2) The zig-zig rule is the one that distinguishes splaying from just rotating x to the root of thetree.3) Top-down splaying is much more efficient in practice.MC0068 – Data Structures using(Book ID: B0701 & B0702)Consider the following class of binary-tree based algorithms for processing a sequence ofrequests:on each access we pay the distance from the root to the accessed node.Arbitrary rotations are also allowed, at a cost of 1 per rotation.For a sequence Sigma, let C(T,Sigma) be the cost of the optimal algorithm in this class forprocessing a sequence Sigma starting from tree T. Then the cost of splaying the sequence(starting from any tree) is O(C(T,Sigma) + n).What about dynamic operations that change the set of elements in the tree? Here’s how we cando Insertion, Join, and Deletion.InsertionSay we want to insert a new item e. Proceed like ordinary binary tree insertion, but stop short oflinking the new item e into the tree. Let the node you were about to link e to be called p. Wesplay p to the root. Now construct a tree according to one of the following pictures:depending on if the item in e is before or after p.Let’s analyze this when all the weights are 1. The amortized cost of the splay is O(log n)according to the access lemma. Then we have to pay the additional amortized cost which equalsthe potential of the new root. This is log(n+1). So the amortized cost of the whole thing isO(log(n)).An alternative insertion algorithm is to do ordinary binary tree insertion, and then simply splaythe item to the root. This also has efficient amortized cost, but the analysis is a tiny bit morecomplicated.JoinHere we have two trees, say, A and B. We want to put them together with all the items in A tothe left of all the items in B. This is called the "Join" operation. This is done as follows. Splaythe rightmost node of A. Now make B the right child of this node. The amortized cost of theoperation is easily seen to be O(log n) where n is the number of nodes in the tree after joining.(Just assign uniform weights to all the nodes, as we did in the Insertion analysis.)DeletionTo delete a node, x, simply splay it to the root and then Join its left and right sub-trees togetheras described above. The amortized cost is easily seen to be O(log n), where n is the size beforethe deletion.

July 2011Master of Computer Application (MCA) – Semester 2

MC0069 – System Analysis &

4

Page 50: Assinment 2nd Sem

Design (SAD) (Book ID: B0714)Assignment Set – 1

1. Describe the following with respect to CommonModeling Techniques:A) Modeling object StructuresB) Forward and Reverse EngineeringC) Object DiagramsAns –A) Modeling Object StructuresWhen you construct a class diagram, a component diagram, or adeployment diagram, what you are really doing is capturing a set ofabstractions that are interesting to you as a group and, in that context,exposing their semantics and their relationships to other abstractions inthe group. These diagrams show only potentiality. If class A has a one-tomanyassociation to class B, then for one instance of A there might belive instances of B; for another instance of A there might be only oneinstance of B. Furthermore, at a given moment in time, that instance ofA, along with the related instances of B, will each have certain values fortheir attributes and state machines.If you freeze a running system or just imagine a moment of time in amodeled system, you’ll find a set of objects, each in a specific state, andeach in a particular relationship to other objects. You can use objectdiagrams to visualize, specify, construct, and document the structure ofthese objects. Object diagrams are especially useful for modelingcomplex data structures.When you model your system’s design view, a set of class diagramscan be used to completely specify the semantics of your abstractionsand their relationships. With object diagrams, however, you cannotcompletely specify the object structure of your system. For an individualclass, there may be a multitude of possible instances, and for a set ofclasses in relationship to one another, there may be many times morepossible configurations of these objects. Therefore, when you use objectdiagrams, you can only meaningfully expose interesting sets of concreteor prototypical objects. This is what it means to model an objectstructure an object diagram shows one set of objects in relation to oneanother at one moment in time.To model an object structure,· Identify the mechanism you’d like to model. A mechanism representssome function or behavior of the part of the system you are modelingthat results from the interaction of a society of classes, interfaces, andother things.· For each mechanism, identify the classes, interfaces, and other elementsthat participate in this collaboration; identify the relationshipsamong these things, as well.· Consider one scenario that walks through this mechanism. Freeze thatscenario at a moment in time, and render each object that participates inthe mechanism.· Expose the state and attribute values of each such object, asnecessary, to understand the scenario.· Similarly, expose the links among these objects, representing instances

4

Page 51: Assinment 2nd Sem

of associations among them.B) Forward and Reverse EngineeringForward engineering (the creation of code from a model) an objectdiagram is theoretically possible but pragmatically of limited value. In anobject-oriented system, instances are things that are created anddestroyed by the application during run time. Therefore, you can’texactly instantiate these objects from the outside.Although this is true of most typical object diagrams (which containinstances of classes), it’s not true of object diagrams containinginstances of components and of nodes. Both of these are special cases ofcomponent diagrams and deployment diagrams, respectively, and arediscussed elsewhere. In these cases, component instances and nodeinstances are things that live outside the running system and areamenable to some degree of forward engineering.Reverse engineering (the creation of a model from code) an objectdiagram is a very different thing. In fact, while you are debugging yoursystem, this is something that you or your tools will do all the time. Forexample, if you are chasing down a dangling link, you’ll want to literallyor mentally draw an object diagram of the affected objects to see where,at a given moment in time, an object’s state or its relationship to otherobjects is broken.To reverse engineer an object diagram,· Chose the target you want to reverse engineer. Typically, you’ll set yourcontext inside an operation or relative to an instance of one particularclass.· Using a tool or simply walking through a scenario, stop execution at acertain moment in time.· Identify the set of interesting objects that collaborate in that contextand render them in an object diagram.· As necessary to understand their semantics, expose these object’sstates.· As necessary to understand their semantics, identify the links that existamong these objects.· If your diagram ends up overly complicated, prune it by eliminatingobjects that are not germane to the questions about the scenario youneed answered. If your diagram is too simplistic, expand the neighbors ofcertain interesting objects and expose each object’s state more deeply.C) Object DiagramsObject diagrams model the instances of things contained in classdiagrams. An object diagram shows a set of objects and theirrelationships at a point in time.You use object diagrams to model the static design view or staticprocess view of a system. This involves modeling a snapshot of thesystem at a moment in time and rendering a set of objects, their state,and their relationships.Object diagrams are not only important for visualizing, specifying, anddocumenting structural models, but also for constructing the staticaspects of systems through forward and reverse engineering.2. Discuss the common modeling techniques in UML.

4

Page 52: Assinment 2nd Sem

Ans:- use classes most commonly to model abstractions that are drawn from the problem you are trying to solve or from the technology you are using to implement a solution to that problem. Each of these abstractions is a part of the vocabulary of your system, meaning that, together, they represent the things that are important to users and to implementers.

For users, most abstractions are not that hard to identify because, typically, they are drawn from the things that users already use to describe their system. Techniques such as CRC cards and use case-based analysis are excellent ways to help users find these abstractions. For implementers, these abstractions are typically just the things in the technology that are parts of the solution.

To model the vocabulary of a system,

Identify those things that users or implementers use to describe the problem or solution. Use CRC cards and use case-based analysis to help find these abstractions.

For each abstraction, identify a set of responsibilities. Make sure that each class is crisply defined and that there is a good balance of responsibilities among all your classes.

Provide the attributes and operations that are needed to carry out these responsibilities for each class.

To model the distribution of responsibilities in a system,

Identify a set of classes that work together closely to carry out some behavior. Identify a set of responsibilities for each of these classes. Look at this set of classes as a whole, split classes that have too many responsibilities into

smaller abstractions, collapse tiny classes that have trivial responsibilities into larger ones, and reallocate responsibilities so that each abstraction reasonably stands on its own.

Consider the ways in which those classes collaborate with one another, and redistribute their responsibilities accordingly so that no class within a collaboration does too much or too little.

o model nonsoftware things,

Model the thing you are abstracting as a class. If you want to distinguish these things from the UML's defined building blocks, create a new

building block by using stereotypes to specify these new semantics and to give a distinctive visual cue.

3. Explain the following in the context of Relationships:

A) Modeling Simple Dependencies :- While entity types describe independent artifacts, relationship types describe meaningful associations between entity types.

To be precise, the relationship type describes that entities of entity types participating in the relationship can build a

meaningful association. The actual occurrence of the association between entities is called a relationship.

4

Page 53: Assinment 2nd Sem

It is important to understand that although we defined a relationship type, this does not mean that every pair of entities

builds a relationship. A relationship type defines only that relationships can occur.

An example of a relationship type is the Employee owns Product. In this example the relationship type is Owns. The

relationship itself is: The Employee Joe Ward owns a Product, the yellow Telephone,

with the Serial Number 320TS03880.

Dependency refers to a situation in which a particular entity can not meaningfully exist without the existence of another

entity as specified within a relationship. The entity type is dependent on another entity type when each entity of a dependent

entity (subtype) depends on the existence of the corresponding parent entity in the super type.

A mandatory dependency relationship has to be specified by explicitly defining the lower limit for cardinality that is not

equal to 0 or by a fixed cardinality that is not equal to 0.

B) Modeling Single Inheritance :- To understand OO you need to understand common object

terminology. The critical terms to understand are summarized in Table 1. I present a much more

detailed explanation of these terms in The Object Primer 3/e. Some of these concepts you will have

seen before, and some of them you haven’t. Many OO concepts, such as encapsulation, coupling, and

cohesion come from software engineering. These concepts are important because they underpin good

OO design. The main point to be made here is that you do not want to deceive yourself – just because

you have seen some of these concepts before, it don’t mean you were doing OO, it just means you were

doing good design. While good design is a big part of object-orientation, there is still a lot more to it

than that.

Single Inheritance

Represents “is a”, “is like”, and “is kind of” relationships.  When class “B” inherits from class “A” it automatically has all of the attributes and operations that “A” implements (or inherits from other classes)

Associations also exist between use cases in system use case models and are depicted using dashed lines with the UML stereotypes of <<extend>> or <<include>>, as you see in.It is also possible to model inheritance between use cases, something that is not shown in the diagram.   The rectangle around the use cases is called the system boundary box and as the name suggests it delimits the scope of your system – the use cases inside the rectangle represent the functionality that you intend to implement.

4

Page 54: Assinment 2nd Sem

C) Modeling Structural Relationships :- The class is the basic logical entity in the UML. It defines both the data and the behaviour of a structural unit. A class is a template or model from which instances or objects are created at run time. When we develop a logical model such as a structural hierarchy in UML we explicitly deal with classes. When we work with dynamic diagrams, such as sequence diagrams and collaborations, we work with objects or instances of classes and their inter-actions at run-time. The principal of data hiding or encapsulation is based on localisation of effect. A class has internal data elements that it is responsible for. Access to these data elements should be through the class's exposed behaviour or interface. Adherence to this principal results in more maintainable code.

D) Multiplicity and Aggregation :-

Indicator Meaning0..1 Zero or one1 One only0..* Zero or more1..* One or moren Only n (where n > 1)0..n Zero to n (where n > 1)1..n One to n (where n > 1)

Another option for associations is to indicate the direction in which the label should be read. This is depicted using a filled triangle, called a direction indicator, an example of which is shown on the offering of association between the Seminar and Course. This symbol indicates the association should be read “a seminar is an offering of a course,” instead of “a course is an offering of a seminar.” Direction indicators should be used whenever it isn’t clear which way a label should be read. My advice, however, is if your label is not clear, then you should consider rewording it.

4

Page 55: Assinment 2nd Sem

Aggregation

Class diagram showing Aggregation between two classes

Aggregation is a variant of the "has a" or association relationship; aggregation is more specific than association. It is an association that represents a part-whole or part-of relationship. As a type of association, an aggregation can be named and have the same adornments that an association can. However, an aggregation may not involve more than two classes.

Aggregation can occur when a class is a collection or container of other classes, but where the contained classes do not have a strong life cycle dependency on the container—essentially, if the container is destroyed, its contents are not.

In UML, it is graphically represented as a hollow diamond shape on the containing class end of the tree of lines that connect contained class(es) to the containing class.

4. Write about Common Modeling techniques in Relationships.

Ans:- modeling is the act of exploring data-oriented structures.  Like other modeling artifacts data models can be used for a variety of purposes, from high-level conceptual models to physical data models.  From the point of view of an object-oriented developer data modeling is conceptually similar to class modeling. With data modeling you identify entity types whereas with class modeling you identify classes.  Data attributes are assigned to entity types just as you would assign attributes and operations to classes.  There are associations between entities, similar to the associations between classes – relationships, inheritance, composition, and aggregation are all applicable concepts in data modeling.

Traditional data modeling is different from class modeling because it focuses solely on data – class models allow you to explore both the behavior and data aspects of your domain, with a data model you can only explore data issues.  Because of this focus data modelers have a tendency to be much better at getting the data “right” than object modelers.  However, some people will model database methods (stored procedures, stored functions, and triggers) when they are physical data modeling.  It depends on the situation of course, but I personally think that this is a good idea and promote the concept in my UML data modeling profile (more on this later).

Conceptual data models. These models, sometimes called domain models, are typically used to explore domain concepts with project stakeholders. On Agile teams high-level conceptual models are often created as part of your initial requirements envisioning efforts as they are used to explore the high-level static business structures and concepts. On traditional teams conceptual data models are often created as the precursor to LDMs or as alternatives to LDMs.

Logical data models (LDMs). LDMs are used to explore the domain concepts, and their relationships, of your problem domain. This could be done for the scope of a single project or for your entire enterprise. LDMs depict the logical entity types, typically referred to simply as

4

Page 56: Assinment 2nd Sem

entity types, the data attributes describing those entities, and the relationships between the entities. LDMs are rarely used on Agile projects although often are on traditional projects (where they rarely seem to add much value in practice).

Physical data models (PDMs). PDMs are used to design the internal schema of a database, depicting the data tables, the data columns of those tables, and the relationships between the tables. PDMs often prove to be useful on both Agile and traditional projects and as a result the focus of this article is on physical modeling.

5. Describe the following structural diagrams with relevant examples:

A) Class :- The class diagram is the main building block in object oriented modelling. It is used both for general conceptual modelling of the systematics of the application, and for detailed modelling translating the models into programming code. The classes in a class diagram represent both the main objects and or interactions in the application and the objects to be programmed. In the class diagram these classes are represented with boxes which contain three parts: [1]

A class with three sections.

The upper part holds the name of the class The middle part contains the attributes of the class The bottom part gives the methods or operations the class can take or undertake

In the system design of a system, a number of classes are identified and grouped together in a class diagram which helps to determine the statical relations between those objects. With detailed modeling, the classes of the conceptual design are often split in a number of subclasses.

In order to further describe the behavior of systems, these class diagrams can be complemented by state diagram or UML state machine. Also instead of class diagrams Object role modeling can be used if you just want to model the classes and their relationships.

B) Object :- A relationship is a general term covering the specific types of logical connections found on

class and object diagrams. UML shows the following relationships:

External links

4

Page 57: Assinment 2nd Sem

A Link is the basic relationship among objects. It is represented as a line connecting two or more object

boxes. It can be shown on an object diagram or class diagram. A link is an instance of an association. In

other words, it creates a relationship between two classes.

Association

Class diagram example of association between two classes

An Association represents a family of links. Binary associations (with two ends) are normally represented as a line, with each end connected to a class box. Higher order associations can be drawn with more than two ends. In such cases, the ends are connected to a central diamond.

An association can be named, and the ends of an association can be adorned with role names, ownership indicators, multiplicity, visibility, and other properties. There are five different types of association. Bi-directional and uni-directional associations are the most common ones. For instance, a flight class is associated with a plane class bi-directionally. Associations can only be shown on class diagrams. Association represents the static relationship shared among the objects of two classes. Example: "department offers courses", is an association relation.

C) Component :- The component diagram's main purpose is to show the structural relationships between the components of a system. In UML 1.1, a component represented implementation items, such as files and executables. Unfortunately, this conflicted with the more common use of the term component," which refers to things such as COM components. Over time and across successive releases of UML, the original UML meaning of components was mostly lost. UML 2 officially changes the essential meaning of the component concept; in UML 2, components are considered autonomous, encapsulated units within a system or subsystem that provide one or more interfaces. Although the UML 2 specification does not strictly state it, components are larger design units that represent things that will typically be implemented using replaceable" modules. But, unlike UML 1.x, components are now strictly logical, design-time constructs. The idea is that you can easily reuse and/or substitute a different component implementation in your designs because a component encapsulates behavior and implements specified interfaces. [Note: The physical items that UML1.x called components are now called "artifacts" in UML 2. An artifact is a physical unit, such as a file, executable, script, database, etc. Only artifacts live on physical nodes; classes and components do not have "location." However, an artifact may manifest components and other classifiers (i.e., classes). A single component could be manifested by multiple artifacts, which could be on the same or different nodes, so a single component could indirectly be implemented on multiple nodes.

4

Page 58: Assinment 2nd Sem

Master of Computer Application (MCA) – Semester 2

MC0069 – System Analysis & Design (SAD)

Assignment Set – 2

1. Describe the following with respect to Common Modeling Techniques:

A) Modeling Simple Collaborations :- A collaboration diagram describes interactions among objects in terms of sequenced messages. Collaboration diagrams represent a combination of information taken from class, sequence, and use case diagrams describing both the static structure and dynamic behavior of a system.

Basic Collaboration Diagram Symbols and Notations

Class roles

Class roles describe how objects behave. Use the UML object symbol to illustrate class roles, but don't list object attributes.

Association roles

Association roles describe how an association will behave given a particular situation. You can draw association roles using simple lines labeled with stereotypes.

Identify mechanisms and define your system model. The mechanism represents some function or behavior of a part of the system and modeling is the result of classroom interactions, interfaces, and other things.

The mechanism will identify the classes, interfaces, and other collaborations that connect and complement each other or each other. Then check every relationship that occurs in the system

Scan the modeling is if at the time of the search ad is something missing then the diagram formed / semantic need of repair

Load the element with the class attribute or operation that may occur.

B) Modeling a logical database schema :- The software will you wake up by using a UML tool that will have a class which the object will be used continuously so that the data object allows you to save them in the database . Database that you will often use the database relational, database or database object berorintasikan used as persistent storage. UML has the ability to create a model good database logical database schema or database physically.

4

Page 59: Assinment 2nd Sem

With classes held by the UML diagrams will be very easy to form a logical database design, ER diagrams which differ by only focusing on data diagrams will be able to describe the behavior or instructions contained in a model. Logical operations is being made in the form of a database that stores a procedure would be transformed into a procedure. class diagram which is a superset of the entities of an entity relationship ERD will be able to describe in detail from a concept of databases and applications that are built.

The steps used to create a database schema in UML models as follows:

Identification of classes in your applications in which there are models that describe the activities in the application.

UML class diagram depicting the classes that have been identified and then you must define their own values – values that the details of sfesifikasi database used in the application.

Extending classes to establish the details and focusing on the relationship and cardinality of a database and transform into a structure class.

Notice the pattern of starting a common database to the intricate patterns, if necessary you can ordinary these patterns.

Consider also the behavior of these classes to expand operations necessary for data access and data integrity. In general, to provide better separation of the problem, the relevant business rules with the manipulation of these objects should be encapsulated in a layer above classes these.

Here is an illustration / example of a schematic diagram of the UML model. We will portray a simple concept classes in a UML class diagram. Here there are several classes which include: Students, Courses, and Instructors. Each student will follow a course that is held by each intructur. Each student has a school that the school must have a department for each course to be followed. While the instructor has a department and courses that are taught to every student who has been a member for the school.

C) Forward and Reverse Engineering :- The comparison of the different tools will be made based on the modeling of the chosen web application. A

full UML-model will be created as far as possible with each and every one of the individual tools. The UMLdiagrams

are created by click-drag-and-drop, complemented with necessary information about methods and

attributes based on the specification in Table 1. Potential lack of support in any tool for any functionality is

also logged and especially noted.

In the second step, C#-code is automatically generated based on the UML-model created in respectively

tool. The resulting code is evaluated based on which, if any, functionality is missing, how empty methods are

4

Page 60: Assinment 2nd Sem

handled and what error messages are generated. As noted above, the main() method is intentionally left out in

the class diagram in order to examine if the tools automatically generate such a method or not.

Finally, to test the reverse engineering capabilities of each tool, we wrote a complete software skeleton in

C# based on the generated full UML-diagrams for subsequent reverse engineering by each tool, generating

“tool specific” UML-models of the code. Again we compared functionality against the “true” model and

logged all error messages. Turning to the details in the model specification in Table 1 above, it should be

noted that the number of classes has not been in focus, but the classes are instead mainly “holders” for the methods, data and return types being investigated. The class “server” contains the return data type “DataSet”

for instance, which requires a using directive normally not part of auto-generated code. The intention is to

investigate if each tool automatically adds the necessary using directive or not. The same class also contains

the attribute “ArrayList”, which in the same way is not a part of the most common using directives.

2. Define the following terms with suitable examples in the context of Events and Signals:

a) Kinds of Events :- In the most general terms, an event is an occurrence in time and space that has significance to the system. Strictly speaking, in the UML specification,[1] the term event refers to the type of occurrence rather than to any concrete instance of that occurrence. For example, Keystroke is an event for the keyboard, but each press of a key is not an event but a concrete instance of the Keystroke event. Another event of interest for the keyboard might be Power-on, but turning the power on tomorrow at 10:05:36 will be just an instance of the Power-on event.

An event can have associated parameters, allowing the event instance to convey not only the occurrence of some interesting incident but also quantitative information regarding that occurrence. For example, the Keystroke event generated by pressing a key on a computer keyboard has associated parameters that convey the character scan code as well as the status of the Shift, Ctrl, and Alt keys.

4

Page 61: Assinment 2nd Sem

An event instance outlives the instantaneous occurrence that generated it and might convey this occurrence to one or more state machines. Once generated, the event instance goes through a processing life cycle that can consist of up to three stages. First, the event instance is received when it is accepted and waiting for processing (e.g., it is placed on the event queue). Later, the event instance is dispatched to the state machine, at which point it becomes the current event. Finally, it is consumed when the state machine finishes processing the event instance. A consumed event instance is no longer available for processing.

b) Signals :- UML Activity Diagrams have Send Signal Action. This action creates an instance of a Signal

from its inputs, and transmits it to the target object, where it may cause some behavior to be executed

as a response to the signal received.

A Signal is a classifier which describes send request - i.e. the data to be transmitted from a sender of the

signal to the receiver. The data carried by a send request are represented as attributes of the signal.

Complexity in the digital systems integration rises from the heterogeneity of the

components integrated in a chip. The simulation or code generation of such systems require

to validate methodologies, platforms and technologies to support integration, veri_cation

and programming, of complex systems composed of heterogeneous virtual components.

Several formalisms are needed according to their applicability in order to propose a

framework of formal speci_cation. The uni_cation of these formalisms leads to visually model

intensive signal processing applications for embedded systems. A part of this methodology

has come down from the Array-OL language. An application is represented by a graph of

dependences between tasks and arrays. Thanks to the data-parallel paradigm, a task may

iterate the same code on di_erent patterns which tile its depending arrays.

The visual notation we propose uses a UML 2.0 standard proposal. This allows usage of

existing UML 2.0 tools to model an application. A UML pro_le dedicated to Intensive Signal

4

Page 62: Assinment 2nd Sem

Processing with a strong semantics allows automatic code generation, automatic mapping

on SoC architectures for early validation at the higher level of speci_cation.

c) Call Events :- Before UML 2, the only transition semantics in use was the external transition, in which the main source of the transition is always exited and the main target of the transition is always entered. UML 2 preserved the "external transition" semantics for backward compatibility, but introduced also a new kind of transition called local transition (see Section 15.3.15 in OMG Unified Modeling Language (OMG UML), Infrastructure Version 2.2). For many transition topologies, external and local transitions are actually identical. However, a local transition doesn’t cause exit from the main source state if the main target state is a substate of the main source. In addition, local state transition doesn’t cause exit and reentry to the target state if the main target is a superstate of the main source state.

d) Time and Change Events :- Building models which faithfully represent complex systems

is a non trivial problem and a prerequisite to the application of formal analysis techniques. Usually, modelling techniques

are applied at early phases of system development and at high abstraction level. Nevertheless, the need of a unified view of

the various development activities and of their interdependencies

motivated the so called model-based development [49]which heavily relies on the use of modelling methods and. timed process algebras [45] and timed automata [4]. In processalgebras, timing is added by a “delay” construct similar to timeout or a wait construct, as they exist in real-time

programming languages. In Petri nets, minimal and maxima lwaiting times are associated with states and transitions, and in timed automata, variables called “clocks” increase with time

4

Page 63: Assinment 2nd Sem

progress and can be set (to 0) so that they always measure the time passed since they have been last set. All these formalisms represent machines that can perform two kinds of state changes, time progress steps and actions, where actions correspond to events, that is instantaneous changes of the discrete

state which may depend on time, whereas time steps do not alter the discrete state.

An event is a phenomenon in space and time significant for the modeled system.

An event can appear synchronously or asynchronously.

o synchronous events:

• call event: triggered by call

• exception event: triggered by called object at return

asynchronous events:

• signal event: signal sent by other object

• change event: triggered by side effects on object attributes

• time event: spontaneously triggered by boolean guard over time.

e) Sending and Receiving Events :- In the most general terms, an event is an occurrence in time and space that has significance to the system. Strictly speaking, in the UML specification, the term event refers to the type of occurrence rather than to any concrete instance of that occurrence. For example, Keystroke is an event for the keyboard, but each press of a key is not an event but a concrete instance of the Keystroke event. Another event of interest for the keyboard might be Power-on, but turning the power on tomorrow at 10:05:36 will be just an instance of the Power-on event.

An event can have associated parameters, allowing the event instance to convey not only the occurrence of some interesting incident but also quantitative information regarding that occurrence. For example, the Keystroke event generated by pressing a key on a computer keyboard has associated parameters that convey the character scan code as well as the status of the Shift, Ctrl, and Alt keys.

f) Transitions :- A transition is a progression from one state to another and will be triggered by an event that is either internal or external to the entity being modeled. For a class, transitions are typically the result of the invocation of an operation that causes an important change in state, although it is important to understand that not all method invocations will result in transitions. An action is something, in the case of a class it is an operation, that is invoked by/on the entity being modeled.

1. Name Software Actions Using Implementation Language Naming Conventions 2. Name Actor Actions Using Prose 3. Indicate Entry Actions Only When Applicable For All Entry Transitions 4. Indicate Exit Actions Only When Applicable For All Exit Transitions 5. Model Recursive Transitions Only When You Want to Exit and Re-Enter the State

4

Page 64: Assinment 2nd Sem

6. Name Transition Events in Past Tense 7. Place Transition Labels Near The Source State 8. Place Transitions Labels Based on Transition Direction. To make it easier to identify which label

goes with a transition, place transition labels according to the following heuristics:

Above transition lines going left-to-right Below transition lines going right-to-left Right of transition lines going down Left of transition lines going up

3. Describe the following:

A) State machines :- UML state machine diagrams depict the various states that an object may be in and the transitions between those states. In fact, in other modeling languages, it is common for this type of a diagram to be called a state-transition diagram or even simply a state diagram. A state represents a stage in the behavior pattern of an object, and like UML activity diagrams it is possible to have initial states and final states. An initial state, also called a creation state, is the one that an object is in when it is first created, whereas a final state is one in which no transitions lead out of. A transition is a progression from one state to another and will be triggered by an event that is either internal or external to the object.

B) Advanced States :-Advanced state diagram is a type of diagram used in computer science and related fields to describe the behavior of systems. State diagrams require that the system described is composed of a finite number of states; sometimes, this is indeed the case, while at other times this is a

4

Page 65: Assinment 2nd Sem

reasonable abstraction. There are many forms of state diagrams, which differ slightly and have different semantics.Advanced State diagrams are used to give an abstract description of the behavior of a system. This behavior is analyzed and represented in series of events, that could occur in one or more possible states. Hereby "each diagram usually represents objects of a single class and track the different states of its objects through the system". a flowchart to an assembly line in manufacturing because the flowchart describes the progression of some task from beginning to end (e.g., transforming source code input into object code output by a compiler). A state machine generally has no notion of such a progression. The door state machine shown at the top of this article, for example, is not in a more advanced stage when it is in the "closed" state, compared to being in the "opened" state; it simply reacts differently to the open/close events. A state in a state machine is an efficient way of specifying a particular behavior, rather than a stage of processing.

4. Describe the following with suitable examples:

A) Modeling the realization of a Use case :- A relationship is a general term covering the specific types of logical connections found on class and object diagrams. UML shows the following relationships:

In UML modeling, a realization relationship is a relationship between two model elements, in which one model element (the client) realizes (implements or executes) the behavior that the other model element (the supplier) specifies. A realization is indicated by a dashed line with a unfilled arrowhead towards the supplier.

Realizations can only be shown on class or component diagrams.

A realization is a relationship between classes, interfaces, components, and packages that connects a client element with a supplier element. A realization relationship between classes and interfaces and between components and interfaces shows that the class realizes the operations offered by the interface.

B) Modeling the realization of an operation :- The class diagram is the main building block in object oriented modelling. It is used both for general conceptual modelling of the systematics of the application, and for detailed modelling translating the models into programming code. The classes in a class diagram represent both the main objects and or interactions in the application and the objects to be programmed. In the class diagram these classes are represented with boxes which contain three parts:

A class with three sections.

The upper part holds the name of the class The middle part contains the attributes of the class The bottom part gives the methods or operations the class can take or undertake

In the system design of a system, a number of classes are identified and grouped together in a class diagram which helps to determine the statical relations between those objects. With detailed modeling, the classes of the conceptual design are often split in a number of subclasses.

4

Page 66: Assinment 2nd Sem

In order to further describe the behavior of systems, these class diagrams can be complemented by state diagram or UML state machine. Also instead of class diagrams Object role modeling can be used if you just want to model the classes and their relationships.

C) Modeling a Mechanism :- It is important to distinguish between the UML model and the set of diagrams of a system. A diagram is a partial graphic representation of a system's model. The model also contains documentation that drive the model elements and diagrams (such as written use cases).

UML diagrams represent two different views of a system model:

Static (or structural) view: emphasizes the static structure of the system using objects, attributes, operations and relationships. The structural view includes class diagrams and composite structure diagrams.

Dynamic (or behavioral) view: emphasizes the dynamic behavior of the system by showing collaborations among objects and changes to the internal states of objects. This view includes sequence diagrams, activity diagrams and state machine diagrams.

UML models can be exchanged among UML tools by using the XMI interchange format.

5. Describe the following:A) Modeling the architecture of a system :- deployment diagram depicts a static view of the run-time configuration of processing nodes and the components that run on those nodes. In other words, deployment diagrams show the hardware for your system, the software that is installed on that hardware, and the middleware used to connect the disparate machines to one another. You want to create a deployment diagram for applications that are deployed to several machines, for example a point-of-sales application running on a thin-client network computer which interacts with several internal servers behind your corporate firewall or a customer service system deployed using a web services architecture such as Microsoft’s .NET.  Deployment diagrams can also be created to explore the architecture of embedded systems, showing how the hardware and software components work together. In short, you may want to consider creating a deployment diagram for all but the most trivial of systems. Nodes can contain other nodes or software artifacts.  The ApplicationServer node contains EJBContainer (a software node) which in turn contains three software components, a deployment specification, and a software artifact.  The software components use the same notation as component diagrams (I could have annotated them with their interfaces although that wouldn’t have added any value in my opinion).  Deployment specifications are basically configuration files, such as an EJB deployment descriptor, which define how a node should operate.

B) Modeling Systems :- UML, the Universal Modeling Language, was the first language designed to fulfill the requirement for "universality." However, it is a software-specific language, and does not support the needs of engineers designing from the broader systems-based perspective.

Therefore, SysML was created. It has been steadily gaining popularity, and many companies, especially in the heavily-regulated Defense, Automotive, Aerospace, Medical Device and Telecomms industries, are already using SysML, or are plannning to switch over to it in the near future.

4

Page 67: Assinment 2nd Sem

However, little information is currently available on the market regarding SysML. Its use is just on the crest of becoming a widespread phenomenon, and so thousands of engineers are now beginning to look for training and resources.

The proposed book will provide an introduction to SysML, and instruction on how to implement it, for all these new users. It is the first available book on SysML in English. It contains insider information! The author is a member of the SysML working group and has written sections of the specification. It features a special focus comparing SysML and UML, and explaining how both can work together.

C) Models and Views :- We need to consider the primary modelling purposes of UML. These are:

Business Process Modelling with Use Cases Class and Object Modelling Behaviour Modelling Component Modelling Distribution and Deployment Modelling

Each UML model is designed to let analysts, developers and customers view a system from different perspectives and with varying levels of abstraction. Each diagram will fit somewhere into these five architectural views representing a distinct problem solution space. These can be described as the user model view, structural model view, behavioural model view implementation model view and the environment model view.

The UML user model view encompasses the models which define a solution to a problem as understood by the client or stakeholders. This view is often also referred to as the Use Case or scenario view. The main UML model encompassed by this view is the:

Use Case Diagram: These models depict the functionality required by the system and the interaction of users and other elements (known as actors) with respect to the specific solution.

The UML structural view encompasses the models which provide the static, structural dimensions and properties of the modelled system. This view is often also referred to as the static or logical view. UML Models applicable to this view include:

Class Diagrams: These models describe the static structure and contents of a system using elements such as classes, packages and objects to display relationships such as containment, inheritance and associations.

Object Diagrams: Depict a class or the static structure of a system at a particular point in time.

The UML Implementation View combines the structural and behavioural dimensions of the solution realisation or implementation. The view is often also referred to as the component or development view. UML Models applicable to this view include:

4

Page 68: Assinment 2nd Sem

Component Diagrams: These depict the high level organisation and dependencies of source code components, binary components and executable components and whether these components exist at compile, link or run time.

D) Traces :- The ability to trace new and changed requirements to their impacted components provides critical support for managing change in an evolving software system. Unfortunately numerous studies have shown the difficulties of maintaining links using traditional traceability methods. Information retrieval techniques can be used to dynamically generate traces and alleviate the need to maintain explicit links, however prior work in this area has focused primarily on establishing intra-requirement links or links between requirements and code. We compare several retrieval techniques for generating links between requirements, code, and UML models. Tracing to UML elements provides a higher perspective on the proposed change than would be possible if links were generated directly to the code and supports the growing trend towards model driven development. Our experiment returned better results for establishing links to UML artifacts than to code, suggesting the usefulness of establishing links to code via UML artifacts. We conclude the paper by discussing the implications of this approach for managing the evolution of a software system.

Master of Computer Application (MCA) – Semester 2

MC0070 – Operating Systems with UnixAssignment Set – 1

1. Describe the following operating system components:

A) Functions of an Operating system :- Functions Of Operating System Today most operating systems perform the following important functions:1. Processor management, that is, assignment of processor to different tasks being performed by the computer system.2. Memory management, that is, allocation of main memory and other storage areas to the system programmes as well as user programmes and data.3. Input/output management, that is, co-ordination and assignment of the different output and input device while one or more programmes are being executed.4. File management, that is, the storage of file of various storage devices to another. It also allows all files to be easily changed and modified through the use of text editors or some other files manipulation routines.

5. Establishment and enforcement of a priority system. That is, it determines and maintains the order in which jobs are to be executed in the computer system.6. Automatic transition from job to job as directed by special control statements.

4

Page 69: Assinment 2nd Sem

7. Interpretation of commands and instructions. 8. Coordination and assignment of compilers, assemblers, utility programs, and other software to the various user of the computer system.9. Facilities easy communication between the computer system and the computer operator (human). It also establishes data security and integrity.

B) Operating system components :- The operating system comprises a set of software packages that can be used to manage interactions with the hardware. The following elements are generally included in this set of software:

The kernel, which represents the operating system's basic functions such as management of memory, processes, files, main inputs/outputs and communication functionalities.

The shell, allowing communication with the operating system via a control language, letting the user control the peripherals without knowing the characteristics of the hardware used, management of physical addresses, etc.

The file system, allowing files to be recorded in a tree structure.

2. Describe the following:

A. Micro Kernels :- In computer science, a microkernel is the near-minimum amount of software that can provide the mechanisms needed to implement an operating system. These mechanisms include low-level address space management, thread management, and inter-process communication(I.P.C). As an operating system design approach, microkernels permit typical operating system services, such as device drivers, protocol stacks, file systems and user interface code, to run in user space. If the hardware provides multiple rings or CPU modes, the microkernel is the only software executing at the most privileged level (generally referred to as supervisor or kernel mode).

Microkernels are closely related to exokernels.[1] They also have much in common with hypervisors,[2] but the latter make no claim to minimality, and are specialized to supporting virtual machines; indeed, the L4 microkernel frequently finds use in a hypervisor capacity.

The historical term nanokernel has been used to distinguish modern, high-performance microkernels from earlier implementations which still contained many system services. However, nanokernels have all but replaced their microkernel progenitors, and the term has fallen into disuse.

4

Page 70: Assinment 2nd Sem

B. Modules :- The variables and methods in the os module allow you to interact with files and directories. In most cases the names and functionalities are the same as the equivalent.

The os module: operating system interface :-

environ

A dictionary whose keys are the names of all currently defined environmental variables, and whose values are the values of those variables.

error

The exception raised for errors in this module.

chdir(p)

Change the current working directory to that given by string p

chmod(p,m)

Change the permissions for pathname p to m. See module stat , below, for symbolic constants to be used in making up m values.

chown(p,u,g)

Change the owner of pathname p to user id u and group id g.

_exit(n)

Exit the current process and return status code n. This method should be used only by the child process after a fork(); normally you should use sys.exit().

4

Page 71: Assinment 2nd Sem

getcwd()

Returns the current working directory name as a string.

kill(p,s)

Send signal s to the process whose process ID is p.

listdir(p)

Return a list of the names of the files in the directory whose pathname is p. This list will never contain the special entries "." and ".." for the current and parent directories. The entries may not be in any particular order.

mkdir(p[,m])

Create a directory at pathname p. You may optionally specify permissions m; see module stat below for the interpretation of permission values.

remove(p)

Removes the file with pathname p, as in the Unix rm command. Raises OSError if it fails.

rename(po, pn)

Rename path po to pn.

rmdir(p)

Remove the directory at path p.

3. Describe the concept of process control in Operating systems.

Ans:-

Process Management

Multiprogramming systems explicitly allow multiple processes to exist at any given time, where only one is using the CPU at any given moment, while the remaining processes are performing I/O or are waiting.

The process manager is of the four major parts of the operating system. It implements the process abstraction. It does this by creating a model for the way the process uses CPU and any system resources. Much of the complexity of the operating system stems from the need for multiple processes to share the hardware at the same time. As a conseuence of this goal, the process manager implements CPU sharing ( called scheduling ), process synchronization

4

Page 72: Assinment 2nd Sem

mechanisms, and a deadlock strategy. In addition, the process manager implements part of the operating system's protection and security.

Process States

During the lifespan of a process, its execution status may be in one of four states: (associated with each state is usually a queue on which the process resides)

Executing: the process is currently running and has control of a CPU Waiting: the process is currently able to run, but must wait until a CPU becomes

available Blocked: the process is currently waiting on I/O, either for input to arrive or output to be

sent Suspended: the process is currently able to run, but for some reason the OS has not

placed the process on the ready queue Ready: the process is in memory, will execute given CPU time

Process Control Block (PCB)

If the OS supports multiprogramming, then it needs to keep track of all the processes. For each process, its process control block PCB is used to track the process's execution status, including the following:

Its current processor register contents. Its processor state (if it is blocked or ready). Its memory state. A pointer to its stack. Which resources have been allocated to it. Which resources it needs.

4. Describe the following with respect to UNIX operating System:

A) Hardware Management :- One of the first things you do, after successfully plugging together a plethora of cables and components, is turn on your computer. The operating system takes care of all the starting functions that must occur to get your computer to a usable state. Various pieces of hardware need to be initialized. After the start-up procedure is complete, the operating system awaits further instructions. If you shut down the computer, the operating system also has a procedure that makes sure all the hardware is shut down correctly. Before turning your computer off again, you might want to do something useful, which means that one or more applications are executed. Most boot ROMs do some hardware initialization but not much. Initialization of I/O devices is part of the UNIX kernel.

To perform its task, a process may need to access hardware resources. The process may need to read or write to a file, send data to a network card (to communicate with another computer), or send data to a printer. The operating system provides such services for the process. This is referred to as resource allocation. A piece of hardware is a resource, and the operating system allocates available resources to the different processes that are running.

B) Unix Architecture :-

4

Page 73: Assinment 2nd Sem

Kernel:-

Unix is a multitasking, multiuser, operating system, designed from day one to be lean and

effective in dealing with real time processing of information. The operating system

design essentially embodies effective operating system control over resources (hard disk,

tapes, screen, filesystem, etc.), so that as many applications as possible to support over

the system can run concurrently, without problem.

The architecture of Unix is relatively simple. Unix derives most of its functionality via

the Kernel, which is a block of code that supports all interaction with end user

applications, shells, etc.

Process Structure:-

Unix systems multitask applications in what is generally regarded as "user" mode,

whereas the kernel code itself runs in "kernel" or "privileged" mode. The differences are

important - kernel code is customized, via device drivers, for the hardware platform -

hence, the kernel can take advantage, thru device drivers, of specialized processor

functionality that make the multitasking of applications much smoother.

Input/Output and Piping:-

Unix console applications work in a similar fashion as do Windows console applications:

they both support keyboard oriented input, and text mode output.

Unix supports all standard input/output mechanisms, including C functions like printf(),

gets() and so forth. Just like with a Windows console, these standard sources can be

redirected.

4

Page 74: Assinment 2nd Sem

Unix Architecture Diagram :-

5. Describe the following:

A) Unix Kernel :- The architecture of Unix is relatively simple. Unix derives most of its functionality via

the Kernel, which is a block of code that supports all interaction with end user

applications, shells, etc.

Along with the kernel, is the device drivers, which allow all applications, via the kernel,

to interact with the devices that are available within the system.

The kernel is designed to be flexible - Unix traditionally is distributed as a package of

source code files written in the C programming language. The target system hence either

4

Page 75: Assinment 2nd Sem

has an existing Unix implementation with a C compiler, which can recompile the latest

kernel enhancements to create a new operating system image to execute after a system

shutdown and reboot.

Recently, however, due to the standardization of the PC platform (i.e.: most PCs have a

standard set of devices - floppy, hard disk(s), CDROM, high resolution video adaptor,

etc.), you can obtain precompiled Unix releases that embody the majority of features that

an end user or multi-user environment requires.

B) Unix Startup Scripts :- In the beginning, there was "init". If you had a Unix system, you had "init" and it was almost certainly process id 1. Process 0 was the swapper (not visible in "ps"); it started init with a fork and, one way or another, init was responsible for starting everything else.

There were variations, but not many. BSD systems simply used /etc/rc and /etc/ttys. You'd configure terminals in /etc/ttys and add anything else to /etc/rc. The System V Unixes used the more complex /etc/inittab file to direct init's actions, but really that wasn't much more than the /etc/ttys - life was pretty simple. That didn't take long to change.

The Automating Program Startup article describes init and inittab as they worked on SCO Unix and Linux at that time. Linux inittab soon became mostly standardized, though with some confusion of /etc/init.d vs. /etc/rc.d/init.d and Red Hat's use of "chkconfig" (or the GUI "ntsysv" or "serviceconf" ) to control the startup scripts. With any Unix or Linux system that uses inittab, you simply need to start with /etc/inittab and follow the trail from there. For example, a recent Centos system has these entries in /etc/inittab

l0:0:wait:/etc/rc.d/rc 0l1:1:wait:/etc/rc.d/rc 1l2:2:wait:/etc/rc.d/rc 2l3:3:wait:/etc/rc.d/rc 3l4:4:wait:/etc/rc.d/rc 4l5:5:wait:/etc/rc.d/rc 5l6:6:wait:/etc/rc.d/rc 6

6. Explain the following with respect to Interprocess communication in Unix:

4

Page 76: Assinment 2nd Sem

A) Communication via pipes :- pipes the output from the ls command listing the directory's files into the standard input of the pr command which paginates them. Finally the standard output from the pr command is piped into the standard input of the lpr

command which prints the results on the default printer. Pipes then are unidirectional byte streams which connect the standard output from one process into the standard input of another process. Neither process is aware of this redirection and behaves just as it would normally. It is the shell which sets up these temporary pipes between the processes.

B) Named Pipes :- Named pipes allow two unrelated processes to communicate with each other. They are also known as FIFOs (first-in, first-out) and can be used to establish a one-way (half-duplex) flow of data.

Named pipes are identified by their access point, which is basically in a file kept on the file system. Because named pipes have the pathname of a file associated with them, it is possible for unrelated processes to communicate with each other; in other words, two unrelated processes can open the file associated with the named pipe and begin communication. Unlike anonymous pipes, which are process-persistent objects, named pipes are file system-persistent objects, that is, they exist beyond the life of the process. They have to be explicitly deleted by one of the processes by calling "unlink" or else deleted from the file system via the command line.

In order to communicate by means of a named pipe, the processes have to open the file associated with the named pipe. By opening the file for reading, the process has access to the reading end of the pipe, and by opening the file for writing, the process has access to the writing end of the pipe.

C) Message Queues :- Message queues allow one or more processes to write messages, which will be read by one or more reading processes. Linux maintains a list of message queues, the msgque vector; each element of which points to a msqid_ds data

4

Page 77: Assinment 2nd Sem

structure that fully describes the message queue. When message queues are created a new msqid_ds data structure is allocated from system memory and inserted into the vector.data structure contains an ipc_perm data structure and pointers to the messages entered onto this queue. In addition, Linux keeps queue modification times such as the last time that this queue was written to and so on. The msqid_ds also contains two wait queues; one for the writers to the queue and one for the readers of the message queue. Each time a process attempts to write a message to the write queue its effective user and group identifiers are compared with the mode in this queue's ipc_perm data structure. If the process can write to the queue then the message may be copied from the process's address space into a msg.data structure and put at the end of this message queue. Each message is tagged with an application specific type, agreed between the cooperating processes. However, there may be no room for the message as Linux restricts the number and length of messages that can be written. In this case the process will be added to this message queue's write wait queue and the scheduler will be called to select a new process to run. It will be woken up when one or more messages have been read from this message queue.

D) Message Structure:- Shared memory is a special range of addresses that is created by IPC for one process and appears in the address space of that process.

Other processes can then 'attach' the same shared memory segment into their own address space.

message store is based on a related set of files including a message store file, a directory and index file, and user files. In this structure, multiple users may have a reference in their individual files to the same message, thus the product offered a single instance message store. Message references in user files relate to message offsets stored in an indexed structure. Message offsets refer to locations within the message store file which is common to all users within a given database or "post office".

Text in character sets other than ASCII Non-text attachments Message bodies with multiple parts Header information in non-ASCII character sets

MIME's use, however, has grown beyond describing the content of e-mail to describing content type in general, including for the web (see Internet media type).

Virtually all human-written Internet e-mail and a fairly large proportion of automated e-mail is transmitted via SMTP in MIME format. Internet e-mail is so closely associated with the SMTP and MIME standards that it is sometimes called SMTP/MIME e-mail.[1]

4

Page 78: Assinment 2nd Sem

The content types defined by MIME standards are also of importance outside of e-mail, such as in communication protocols like HTTP for the World Wide Web. HTTP requires that data be transmitted in the context of e-mail-like messages.

Master of Computer Application (MCA) – Semester 2

MC0070 – Operating Systems with Unix

Assignment Set –2

1. Describe the following with respect to Deadlocks in Operating Systems:

A) Livelocks :- Although numerous inconsistent definitions of livelock have been used in the literature, the term usually connotes one of the following: Starvation: Systems with a non-zero service cost and unbounded input rate may experience starvation. For example, if an operating system kernel spends all of its time servicing interrupts then user processes will starve [11].Infinite Execution: The individual processes ofan application may run successfully, but the application as a whole may be stuck in a loop [15].For example, a na¨ıve browser loads web page A

4

Page 79: Assinment 2nd Sem

that redirects to page B that erroneously redirects back to page A. Another example is a process stuck traversing a loop in a corrupted linked list.

B) Killing Zombies :- zombie process or defunct process is a process that has completed execution but still has an entry in the process table, allowing the process that started it to read its exit status. In the term's colorful metaphor, the child process has died but has not yet been reaped...".

On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the process that started the (now zombie) process to read its exit status. The term zombie process derives from the common definition of zombie—an undead person. In the term's colorful metaphor, the child process has died but has not yet been reaped. Also, unlike normal processes, the kill command has no effect on a zombie process.

When a process ends, all of the memory and resources associated with it are deallocated so they can be used by other processes. However, the process's entry in the process table remains. The parent can read the child's exit status by executing the wait system call, at which stage the zombie is removed. The wait call may be executed in sequential code, but it is commonly executed in a handler for the SIGCHLD signal, which the parent receives whenever a child has died.

C) Pipes :-

Conceptually, a pipe is a connection between two processes, such that the standard output from one process becomes the standard input of the other process

It is possible to have a series of processes arranged in a a pipeline, with a pipe between each pair of processes in the series.

Implementation: A pipe can be implemented as a 10k buffer in main memory with 2 pointers, one for the FROM process and one for TO process

One process cannot read from the buffer until another has written to it The UNIX command-line interpreter (e.g., csh) provide a pipe facility.

o % prog | more o This command runs the prog1 program and send its output to the more program.

Pipe System Call

pipe() is a system call that facilitates inter-process communication. It opens a pipe, which is an area of main memory that is treated as a "virtual file". The pipe can be used by the creating process, as well as all its child processes, for reading and writing.

One process can write to this "virtual file" or pipe and another related process can read from it. If a process tries to read before something is written to the pipe, the process is suspended until

something is written. The pipe system call finds the first two available positions in the process's open file table and

allocates them for the read and write ends of the pipe. Recall that the open system call allocates only one position in the open file table.

2. Explain the following:

4

Page 80: Assinment 2nd Sem

A) Requirements for mutual exclusion :- A way of making sure that if one process is using a shared modifiable data, the other processes will be excluded from doing the same thing.

Formally, while one process executes the shared variable, all other processes desiring to do so at the same time moment should be kept waiting; when that process has finished executing the shared variable, one of the processes waiting; while that process has finished executing the shared variable, one of the processes waiting to do so should be allowed to proceed. In this fashion, each process executing the shared data (variables) excludes all others from doing so simultaneously. This is called Mutual Exclusion.

Note that mutual exclusion needs to be enforced only when processes access shared modifiable data - when processes are performing operations that do not conflict with one another they should be allowed to proceed concurrently.

B) Mutual exclusion by using lock variables :- Mechanisms that ensure that only one person or process is doing certain things at one time (others are excluded).

Have a single shared lock variable (lock) initially set to 0.

When a process wants to enter a CS, it checks if lock is 0. If so, it sets it to 1 and enters CS. After it is done, it resets it to 0.

Note that this is not a soln, but the same problem. We need mutual exclusion for accesses to the lock variable itself.

Three elements of locking:

Lock Before Using Unlock When Done Wait(or skip) if locked .

C) Semaphore Implementation :- A synchronization variable that takes on positive integer values. Invented by E. Dijkstra in the mid 60's.

P(semaphore): an atomic operation that waits for semaphore to become positive, then decrements it by 1 ("proberen" in Dutch).

V(semaphore): an atomic operation that increments semaphore by 1 ("verhogen" in Dutch).

Semaphores are simple and elegant and allow the solution of many interesting problems. They do a lot more than just mutual exclusion.

Semaphores are used in two different ways:

Mutual exclusion: to ensure that only one process is accessing shared information at a time. If there are separate groups of data that can be accessed independently, there may be separate semaphores, one for each group of data. These semaphores are always binary semaphores.

4

Page 81: Assinment 2nd Sem

Scheduling: to permit processes to wait for certain things to happen. If there are different groups of processes waiting for different things .

3. Describe the concept of space management in file systems.

Ans:- In computer operating systems, paging is one of the memory-management schemes by which a computer can store and retrieve data from secondary storage for use in main memory. In the paging memory-management scheme, the operating system retrieves data from secondary storage in same-size blocks called pages. The main advantage of paging is that it allows the physical address space of a process to be noncontiguous. Before paging, systems had to fit whole programs into storage contiguously, which caused various storage and fragmentation problems.[1]

Paging is an important part of virtual memory implementation in most contemporary general-purpose operating systems, allowing them to use disk storage for data that does not fit into physical random-access memory (RAM).

The main functions of paging are performed when a program tries to access pages that are not currently mapped to physical memory (RAM). This situation is known as a page fault. The operating system must then take control and handle the page fault, in a manner invisible to the program. Therefore, the operating system must:

1. Determine the location of the data in auxiliary storage.2. Obtain an empty page frame in RAM to use as a container for the data.3. Load the requested data into the available page frame.4. Update the page table to show the new data.5. Return control to the program, transparently retrying the instruction that caused the page fault.

4. Explain the theory of working with files and directories in Unix file system.

Ans:-

The Unix File System :

The purpose of this lesson is to introduce you to how files and directories are handled in Unix.

Unix keeps track of files and directories of files using a file system. When you log in to your Unix account, you are placed in your "home" directory. Your home directory thus becomes your "present working directory" when you log in. In your home directory, you can create files and subdirectories. And in the subdirectories you create, you can create more subdirectories.

The commands that you issue at the Unix prompt relate to the files and folders and resources available from your present working directory. You certainly use and can refer to resources outside of your current working directory. To understand how this works, you need to know how the Unix file system is structured.

4

Page 82: Assinment 2nd Sem

The filesystem tree :

You can visualize the Unix file system as an upside down tree. At the very top of the tree is the root directory, named "/". This special directory is maintained by the Unix system administrator. Under the root directory, subdirectories organize the files and subdirectories on the system. The names of these subdirectories might be any name at all. Here is a tree diagram of a typical Unix system.

5. Explain the working of file substitution in Unix. Also describe the usage of pipes in Unix Operating system.

Ans:- We can use the output of one command as an input to another command in another way called command substitution. Command substitution is invoked when by enclosing the substituted command in backwards single quotes. For example:

cat `find . -name aaa.txt`

which will cat ( dump to the screen ) all the files named aaa.txt that exist in the current directory or in any subdirectory tree.Usage of Pipes :-

Conceptually, a pipe is a connection between two processes, such that the standard output from one process becomes the standard input of the other process

It is possible to have a series of processes arranged in a a pipeline, with a pipe between each pair of processes in the series.

Implementation: A pipe can be implemented as a 10k buffer in main memory with 2 pointers, one for the FROM process and one for TO process

One process cannot read from the buffer until another has written to it The UNIX command-line interpreter (e.g., csh) provide a pipe facility.

o % prog | more .

6. Describe the following with respect to Unix:

A) Making Calculations with dc and bc :- UNIX has two calculator programs that you can use from the command line: dc and bc. The dc (desk calculator) program uses Reverse Polish Notation (RPN), familiar to everyone who has used Hewlett-Packard pocket calculators, and the bc (basic calculator) program uses the more familiar algebraic notation. Both programs perform essentially the same calculations.

Calculating with bc

The basic calculator, bc, can do calculations to any precision that you specify. Therefore, if you know how to calculate pi and want to know its value to 20, 50, or 200 places, for example, use bc. This tool can

4

Page 83: Assinment 2nd Sem

add, subtract, multiply, divide, and raise a number to a power. It can take square roots, compute sines and cosines of angles, calculate exponentials and logarithms, and handle arctangents and Bessel functions. In addition, it contains a programming language whose syntax looks much like that of the C programming language.

Calculating with dc

As mentioned earlier, the desk calculator, dc, uses RPN, so unless you’re comfortable with that notation, you should stick with bc. Also, dc does not provide a built-in programming language, built-in math functions, or the capability to define functions. It can, however, take its input from a file.

If you are familiar with stack-oriented calculators, you’ll find that dc is an excellent tool. It can do all the calculations that bc can and it also lets you manipulate the stack directly.

B) Various Commands for getting user information:-

whoami --- returns your username. Sounds useless, but isn't. You may need to find out who it is who forgot to log out somewhere, and make sure *you* have logged out.

finger & .plan files of course you can finger yourself, too. That can be useful e.g. as a quick check whether you got new mail. Try to create a useful .plan file soon. Look at other people's .plan files for ideas. The file needs to be readable for everyone in order to be visible through 'finger'. Do 'chmod a+r .plan' if necessary. You should realize that this information is accessible from anywhere in the world, not just to other people on turing.

passwd --- lets you change your password, which you should do regularly (at least once a year). See the LRB guide and/or look at help password.

ps -u yourusername --- lists your processes. Contains lots of information about them, including the process ID, which you need if you have to kill a process. Normally, when you have been kicked out of a dialin session or have otherwise managed to get yourself disconnected abruptly, this list will contain the processes you need to kill. Those may include the shell (tcsh or whatever you're using), and anything you were running, for example emacs or elm. Be careful not to kill your current shell - the one with the number closer to the one of the ps command you're currently running. But if it happens, don't panic. Just try again :) If you're using an X-display you may have to kill some X processes before you can start them again. These will show only when you use ps -efl, because they're root processes.

kill PID --- kills (ends) the processes with the ID you gave. This works only for your own processes, of course. Get the ID by using ps. If the process doesn't 'die' properly, use the option -9. But attempt without that option first, because it doesn't give the process a chance to finish possibly important business before dying. You may need to kill processes for example if your

4

Page 84: Assinment 2nd Sem

modem connection was interrupted and you didn't get logged out properly, which sometimes happens.

quota -v --- show what your disk quota is (i.e. how much space you have to store files), how much you're actually using, and in case you've exceeded your quota (which you'll be given an automatic warning about by the system) how much time you have left to sort them out (by deleting or gzipping some, or moving them to your own computer).

du filename --- shows the disk usage of the files and directories in filename (without argument the current directory is used). du -s gives only a total.

last yourusername --- lists your last logins. Can be a useful memory aid for when you were where, how long you've been working for, and keeping track of your phonebill if you're making a non-local phonecall for dialling in.

C) Switching Accounts with su:- The su command, also referred to as substitute user as early as 1979, has also been called "spoof user" or "set user" because it allows changing the account associated with the current terminal (window). It has also been incorrectly called "superuser" but what it does and why it does it has not been well understood, since the 1980s.

The default account that is spoofed is the root account. In practice, the most likely reason to use it is enabling the administrator to switch from working in their non-root account, to the root account. Another reason for an admin to use it pertains to the hyphen parameter (argument).

By default it does not open a login shell. Instead of using the spoofed user's environment it retains the environment of the user who invokes it. This behavior can be changed by including a hyphen as the first argument, which indicates that a login shell should be started. The most obvious differences between these two uses (login versus non-login) are changes to the default working directory and changing the path.

When run from a command line, as is typical, su asks for the target user's password, and, if accepted, grants the user access to that account and all of the files associated with it.

john@localhost:~$ suPassword: root@localhost:/home/john# exitlogoutjohn@localhost:~$

4