Вы находитесь на странице: 1из 9

February 2011 Master of Computer Application (MCA) Semester 2 MC0066 OOPS using C++

Assignment Set 2

1. Write a program which accepts a number from the user and generates prime numbers till that number. #include <iostream.h> void main() { int x; int prim[3000]; NUMprin =0; int found; cout << "Enter the number"; cin>>x;

for(int NUM=0 ; NUM<=X ; NUM++) // to go over all the numbers { found=0; for(int prims=0 ; prims<NUMprin ; prims++) //see if that number devided by prims we allready descover !? { if(num%prim[NUMprin] =0) { found=1; breck; } } //end of prims for if (found!=1) { for(int dev=2 ; dev<NUM ; dev++) //dev start from 2 because all number devided by 1 and them self { if(num/dev !=0) { cout << NUM <<endl ; prim[NUMprin]= NUM;

NUMprin++; breck; } }

2. Implement a class stack which simulates the operations of the stack allowing LIFO operations. Also implement push and pop operations for the stack. A FIFO is an opaque structure that allows items to be placed or pushed onto it at one end (head) and removed or pulled from it, one at at time and in sequence, from the other end (tail). A LIFO is a similarly opaque structure that allows items to be pushed onto it at one end (head or top) and removed or popped from it from that same end (head). This means that items of a LIFO are removed one at a time but in the reverse order of when they were entered. Let us further suppose that our only FIFO primitives are an append operator push and a pull operator shift. push adds elements to the head of the FIFO and shift grabs (and removes) items from the tail of the structure. Therefore, we want to build a stack (LIFO) using the pipe (FIFO) structure and its two primitive operators, push and shift. Essentially, we wish to combine push (onto head) and shift (from tail) pipe operators in some fashion to simulate push (onto head) and pop (from head) stack operators. The following short Ruby program demonstrates a simple solution to this puzzle. Basically we shift items between two FIFO structures to simulate the operations of a stack. But this program is notable less in the algorithm selected and more in the way Ruby expresses the steps required. Interesting Ruby idioms include parallel assignment, variable length argument lists, and simple method definitions and usage.
Implementation of Stack Using Two Queues class Stack def initialize *s # splat operator allows variable length argument list @q1 = [] @q2 = [] s.each { |e| push e } end def push v

# pure FIFO allows only 'push' (onto head) and 'shift' (from tail) # LIFO requires 'push' (onto head) and 'pop' (from head) empty_queue, full_queue = @q1.length == 0 ? [ @q1, @q2 ] : [ @q2, @q1 ] empty_queue.push v until (v = full_queue.shift).nil? # shift each item from non-empty queue, empty_queue.push v # pushing it onto initially empty queue: # produces new full queue in reverse entry order end end def pop full_queue = @q1.length > 0 ? @q1 : @q2 # full queue has been maintained in reverse order # by the push method of the Stack class, so a simple # shift is all that is needed to simulate a stack # pop operation el = full_queue.shift end def empty? @q1.length == 0 && @q2.length == 0 end end # test: puts "STACK: tail/bottom -> x, y, z <- head/top" stack = Stack.new stack.push 'x' stack.push 'y' stack.push 'z' # or equivalently, stack = Stack.new('x', 'y', 'z') until stack.empty? puts "popping stack, item: #{stack.pop}" end # prints items in reverse order: 'z', 'y', 'x'

Book ID: B0715

3. What are allocators? Describe the sequence container adapters.

In C++ computer programming, allocators are an important component of the C++ Standard Library. The standard library provides several data structures, such as list and set, commonly referred to as containers. A common trait among these containers is their ability to change size during the runtime of the program. To achieve this, some form of dynamic memory allocation is usually required. Allocators handle all the requests for allocation and deallocation of memory for a given container. The C++ Standard Library provides general-purpose allocators that are used by default, however, custom allocators may also be supplied by the programmer

Allocators were invented by Alexander Stepanov as part of the Standard Template Library (STL). They were originally intended as a means to make the library more flexible and

independent of the underlying memory model, allowing programmers to utilize custom pointer and reference types with the library. However, in the process of adopting STL into the C++ standard, the C++ standardization committee realized that a complete abstraction of the memory model would incur unacceptable performance penalties. To remedy this, the requirements of allocators were made more restrictive. As a result, the level of customization provided by allocators is more limited than was originally envisioned by Stepanov. Nevertheless, there are many scenarios where customized allocators are desirable. Some of the most common reasons for writing custom allocators include improving performance of allocations by using memory pools, and encapsulating access to different types of memory, like shared memory or garbage-collected memory. In particular, programs with many frequent allocations of small amounts of memory, may benefit greatly from specialized allocators, both in terms of running time and memory footprint.

30.1 Container Adapters In addition to the fundamental container classes, the C++ standard library provides special predefined container adapters that meet special needs. These are implemented by using the fundamental containers classes. The predefined container adapters are as follows: Container Adapter Stacks Queues Description Is a container that manages its elements by the LIFO (last-infirst-out) policy. Is a container that manages its elements by the FIFO (first-infirst-out) policy. That is, it is an ordinary buffer. Is a container in which the elements may have different priorities. The priority is based on a sorting criterion that the programmer may provide (by default, operator < is used). A priority queue is, in effect, a buffer in which the next element is always the element that has the highest priority inside the queue. If more than one element has the highest priority, the order of these elements is undefined.

Priority Queues

Container adapters are just special containers that use the general framework of the containers, iterators, and algorithms provided by the STL. The stack class supports a last-in, first-out (LIFO) data structure. A good analogy would be a stack of plates. Elements (plates) may be inserted, inspected, or removed only from the top of the stack, which is the last element at the end of the base container. The restriction to accessing only the top element is the reason for using the stack class. The queue class supports a first-in, first-out (FIFO) data structure. A good analogy would be people lining up for a bank teller. Elements (people) may be added to the back of the line and are removed from the front of the line. Both the front and the back of a line may be inspected. The restriction to accessing only the front and back elements in this way is the reason fur using the queue class. The priority_queue class orders its elements so that the largest element is always at the top position. It supports insertion of an element and the inspection and removal of the top element. A good analogy would be people lining up where they are arranged by age, height, or some other criterion.

4. Describe the extensibility mechanisms of UML.

Extensibility mechanisms of UML.


UML formally uses the expression extensibility mechanisms to refer to stereotypes, tagged values, and constraints. These three constructs provide the ability to customize UML diagrams for a specific subject and/or platform. These constructs appear as adornments to standard UML notation. Work is also being done for subsequent UML versions to provide extensibility through the use of metaclasses, an approach that can handle the bigger challenges of frameworks and distributed business components. Stereotypes, tagged values, and constraints will appear on nearly every diagram type described in this book. Stereotypes identify a set of qualities that may appear on a number of diagram elements. Tagged values allow you to add new features to an element of the diagram. Constraints define rules to protect the

integrity of a diagram element. All three mechanisms are defined here and applied throughout the diagram descriptions.

Stereotypes
The UML 2.0 specification defines stereotype as A new type of modeling element that extends the semantics of the metamodel. Stereotypes must be based on certain existing types or classes in the metamodel. Stereotypes may extend the semantics, but not the structure of pre-existing types and classes. Certain stereotypes are predefined in the UML, others may be user defined. Stereotypes are one of three extensibility mechanisms in UML. (UML 2.0) A stereotype is a common concept used in ordinary conversation. For example, on entering a meeting, I might point out to a colleague that the three people on the right side of the room are accounting folk, the four to our left are sales, and so on. My colleague understands that these labels identify a set of qualities like skill sets, knowledge about the project, and so forth. The labels do not explain or define their specific jobs. One of the accounting people might be a CPA, another a bookkeeper, and the other a manager. In the same manner, within a software design, I might designate some classes as user interface classes, others as controllers, and still others as utilities. The interface classes might be as diverse as buttons, frames, drop-down lists, or graphics. But all these classes are still tools for building a user interface. Stereotype notation encloses the label in guillemets (French quotes) as in user interface or controller. The stereotype is then added to the description of the model elements, the icons containing the name, and other features. Figure 3-22 provides three examples of the application of stereotypes. The first is a stereotype on a dependency between two use cases, the second is a stereotype on a class, and the third is a stereotype on the dependency between two packages.

Figure : Three examples of the application of stereotypes. A number of stereotypes have already been defined within UML. They are called Standard Elements because they are provided as part of the UML standard. Appendix C provides a complete list of the UML 2.0 standard elements. While these existing stereotypes are useful, they do not prevent you from creating your own. By definition a stereotype is a means to extend UML, to add new concepts that augment and customize its standard modeling elements. The goal of providing this mechanism is to allow users to tailor their use of UML without having to create new model elements or even a new language that fits their particular domain or platform. In my earlier description of a stereotype, I said that a stereotype brings with it some information about the entities that share the stereotype. For example, the accounting folks bring specific knowledge to the project about how the accounting processes and policies work. This stereotype-related information is attached to a stereotype using tagged values, the next topic in the description of extension mechanisms.

Tagged Values
The UML 2.0 specification defines tagged value as

The explicit definition of a property as a name-value pair. In a tagged value, the name is referred to as the tag. Certain tags are predefined in the UML; others may be user defined. Tagged values are one of three extensibility mechanisms in UML. (UML 2.0) In UML 1.4, tagged values first appear as features of a stereotype-a tagged value is paired with a tag definition, a label that describes the type of value that may be assigned to the tag. The tag definition was a bit redundant because the TaggedValue metaclass inherits from the ModelElement metaclass, which already has a name attribute. So in 2.0, tag definition is dropped but tagged values are retained. The purpose of a tagged value is to assign a feature to a model element in addition to those features already defined in the metamodel. This enables you to tailor or enhance the description of a model element while still adhering to the UML metamodel. Tagged values must not alter or contradict the existing definition of a metaclass. They may only add to it. You may add tagged values to any model element. Some common places to use tagged values include the name compartment of a class, and attribute descriptions. Some tagged values are even predefined, such as the persistence tagged value on a class that identifies whether the class is stored or transient. Tagged values are expressed in the form name=value, for example author="Tom", project_phase=2, or last_update="1-07-02". In some diagram locations they are also enclosed within curly braces, {author="Tom", last_update="1-07-02"}.

Constraints
The UML 2.0 specification defines constraint as A semantic condition or restriction. Certain constraints are predefined in the UML, others may be user defined. Constraints are one of three extensibility mechanisms in UML. (UML 2.0) Like stereotypes, constraints appear throughout UML diagrams. Constraints define the invariants that preserve the integrity of the system. A constraint defines a condition that must hold true for the duration of the context in which it is defined. A constraint on an attribute value for an object holds true for the life of the object. A constraint on an object state holds true as long as the object is that state. A constraint on an operation holds true for the duration of the attempt to execute the operation. A constraint is enclosed within curly braces {}. For example, an attribute called name on a theater performance might limit the length to 50 alpha characters, including spaces and punctuation but no special characters. The constraint may be expressed by placing the preceding text inside curly brackets, as in {up to 50 alpha characters, including spaces and punctuation but no special characters}. Figure 3-23 models the Sales Agreement class with a constraint on the attribute endDate. The end date must be no less than the start date. The constraint on the relationship states that there may be any number (zero or more) sales agreements for each contract but the dates for the sales agreements must not overlap.

Figure Constraints on attributes and associations. Note Curly braces are also used for properties.

Constraints are often expressed more formally using the UML Object Constraint Language (OCL). For example, the endDate constraint could be expressed in OCL as context SalesAgreement inv: - - definition of an invariant endDate =< startDate. The first line is a definition statement that establishes the context for the statement as being within the SalesAgreement class. The double dash designates a comment. The second line is the actual constraint stating that the end date of the sales agreement must always be equal to or greater than the start date. Constraints support traversing links, working with groups of items, and enumerations. Constraints are most often applied to attributes and associations, but may also apply to stereotypes, messages, and actions.

Вам также может понравиться