Assignment Set -1

1. Write a program that accepts a number ‘n’ from the user and generates Fibonacci series till n (Fibonacci series starts with 0 and 1 and then the subsequent numbers are generated by adding the two previous numbers in the series). Answer: // A C++ Program to generate Fibonacci Series till the given number #include<iostream.h> #include<conio.h> void main() { int n; int i=0,j=1,k; cout<<"Enter the upper limit of the series"; cin>>n; cout<<"The Fibonacci series till" <<n<<"is"<<endl; if (n<0) cout<<"Invalid Number"; else if (n==0) cout<<i; exit(0); else { cout<<i<<endl<<j<<endl; k=i+j; do { cout<<k<<endl; k=i+j; i=j; j=k; } while(k<=n) } }

2. Write a program to check whether a string is a palindrome or not. Please note that palindrome is one which remains the same if you reverse the characters in the string. For example ‘MADAM’ or “MALAYALAM” Answer: // A C++ Program to check whether the given word is Palindrome or not #include<iostream.h> #include<conio.h> #include<string.h> void main() {

unitprice and qtyinhand. We have then used this name of the structure type (product) to declare three objects of that type: apple. For example. length=strlen(a).j.weight . can have different types and different lengths. banana and melon as we would have done with any fundamental data type.. } } if(flag==0) cout<<"The text entered is a Palindrome". This can be done through structures. product banana.length. Answer: A structure is a user defined data type. We have first declared a structure type called product with two members: weight and price. each of a different fundamental type.j--) { if(a[i]!=a[j]) { flag=1. Write a C++ Program that implements the structure and enables to store at least 100 Product data. we should address melon.j<length-1.i<len/2. float price. Define a structure in C++? Define a structure named product with elements productcode. cin>>a. int i.flag=0. melon. description. A structure is a group of data elements grouped together under one name. break. else cout<<"The text entered is not a Palindrome".char c[]. known as members.i++. getch(). Data that are of different types but are logically related can be grouped together. struct product { int weight. } 3. These data elements. For example to access weight of a product. // This is going to save the length of the string of a to the variable length for(i=0. To access members of the structure dot operators can be used. cout<<"Enter a text to search". product apple. }.

What is the purpose of exception handling? How do you infer from the phrase “Throwing an exception”? Answer: Exception Handling One benefit of C++ over C is its exception handling system. If a call has been made to a particular function. cout<<"Enter Quantity in hand".qtyinhand.h> struct product { int productcode.qtyinhand. cin>>p[i]. } 4.// A C++ program defining structure #include<iostream. The code is written in a fashion where the problem is bound to be expected and cope up with that accordingly. } getch().i++) { cout<<"Enter Product Code". float unitprice. handling errors from that function is one at one place. Furthermore. An exception is a situation in which a program has an unexpected circumstance that the section of code containing the problem is not explicitly designed to handle. exception handling is useful because it makes it easy to separate the error handling code from the code written to handle the chores of the program. Doing so makes reading and writing the code easier.h> #include<conio. char description. cin>>p[i]. but only one function that needs to reliably deal with errors. the method C++ uses to handle exceptions means that it can easily handle those exceptions without any code in the intermediate functions. exception handling in C++ propagates the exceptions up the stack. for(i=0. Exception handling is a better way of handling errors. }p[100].i<100. void main() { int i. . cin>>p[i]. In C++. therefore. With exception handling:  Error handling code is not nearly so tedious to write and it doesn’t become mixed up with normal code. freeing their return values for program logic.productcode.description. One consequence is that functions don't need to return error codes. cout<<"Enter Product Description". if there are several functions called.

} } The catch statement catches exceptions that are of the proper type. take a sample function that does division: const int DivideByZero = 10. it goes to the next enclosing scope and so on until someone catches the error message. } catch(int i) { if(i==DivideByZero) { cerr<<"Divide by zero error". double divide(double x. If the caller doesn’t “catch” the error and handle it accordingly. DivideByZero::DivideByZero(double x) : divisor(x) {} int divide(int x. If a function needs to send an error message to the caller of that function. 0). If you wish to have your program check for exceptions. //. As well. double y) { if(y==0) { throw DivideByZero. } The function will throw DivideByZero as an exception that can then be caught by an exceptionhandling catch statement that catches exceptions of type int. }. you must enclose the code that may have exceptions thrown in a try block. You can. DivideByZero(double x). it would be more useful if you had a class to handle exceptions. It is often more useful for you to create a class that stores information on exceptions as they occur. it “throws” an object representing that error out of the function. for example. For example: try { divide(10. the program continues to run from the end of the catch.. once a catch statement is executed. the function generating the error can 'throw' an exception. For example.. } return x/y. Errors should not be ignored.. throw objects of a class to differentiate between several different exceptions. class DivideByZero { public: double divisor. For example. The necessary construction for catching exceptions is a try catch system. int y) . Throwing an exception When errors occur.

} } try { divide(12. because the exception is passed back up the stack of calling functions. This means that it is easier to structure the program code. . and it makes dealing with errors more centralized.) for the catch statement and print a general warning of some kind. simply use catch(. you can specify separate catch blocks for each type of exception.. To use it. The handy thing to remember about exception handling is that the errors can be handled outside of the regular code. It's also possible to have a general exception handler that will respond to any thrown exception. 0).divisor<<" by zero". you can handle errors at any place you choose. } catch (DivideByZero divZero) { cerr<<"Attempted to divide "<<divZero. Finally.{ if(y==0) { throw DivideByZero(x).. } If you wish to catch more than one possible exception.

for(int i=2.i++) { prime=0. cout<<"Prime Numbers are :". cout<<"Enter a number".prime.h> void main() { int n. break. } 2. Write a program which accepts a number from the user and generates prime numbers till that number Answer: //A C++ Program to generate Prime numbers till the input given number #include<iostream.h> #define size 100 class size 200 { int stck[size].j<=i/2.j++) { if(i%j==0) { prime=1.i<=n.h> #include<conio. } } if(prime==0) { cout<<i<<endl. } } getch(). cin>>n.h> #include<conio. for(int j=2.Assignment Set -2 1. Answer: // A class implementation of a stack #include< public : stack() { . Implement a class stack which simulates the operations of the stack allowing LIFO operations and also implement push & pop operations for the stack.

The default allocator. a. and return it. Allocators are very "low level" features in the STL (Standard Template Library) and are designed to encapsulate memory allocation and deallocation. top++ } int stack::pop() { if(top==0) { cout<<"Stack Underflow".pop()<<" ". return 0.{ top=0. int pop().pop()<<" ".push(3). cout<<a.push(2).push(1). b. alloc. } void main() { stack a.pop()<<" ". } } 3.pop()<<endl. What are allocators? Describe the sequence container adapters. This allows for efficient storage by use of different schemes for particular container classes. cout<<"Stack Initialized"<<endl. cout<<a. } stck[top]=i. return. } void push(int i).b. } void stack::push(int i) { if(top==size) { cout<<"Stack is FULL". They do not create or destroy objects. cout<<a. return stck[top]. a. } top--. cout<<a. b. . is thread-safe and has good performance characteristics. Answer: Allocators Allocators allocate raw memory.push(4).

and you cannot use iterators with adapters.let’s call it ListStack . Describe the extensibility mechanisms of UML. in other words. model elements. but based on the vector. 4. partly because their implementation is still in a state of change and also because the defaults work well for most applications. and specifying new semantics in order to make the language suitable for your specific problem domain. derived from existing ones. so that other programmers could choose a list or a vector based queue. There are three common extensibility mechanisms that are defined by the UML: stereotypes.g. Container adapters neatly solve this by presenting the same public interface irrespective of the underlying container. As another example. and constraints. Ideally you would only want to allow them to be thrown and caught. In addition. they avoid name proliferation. you might later decide that another container like a vector might be better suited to the task. empty() and top().On the whole. it is best to regard allocators as a "black box". this approach rules out the programmer using his or her own underlying class as the container. Provided the container type used supports the operations required by the adapter class (see the individual sections below) you can use any type for the underlying implementation. you might at first decide to base your stack class on the list container . . as shown below. Being templatized. tagged values. VectorStack. which you might sometimes have to model.  Stereotypes Stereotypes allow you to extend the vocabulary of the UML so that you can create new model elements. by marking them with a suitable stereotype you can make these classes into first class citizens in your model. You would then have to define a new stack class. Now. It is obvious that the number of names for what is essentially the same thing start to mushroom. For example.and define public member functions for push(). However. It is important to note that the adapters provide a restricted interface to the underlying container. you make them appear as basic building blocks. Sequence container adapters Sequence container adapters are used to change the "user interface" to other STL (Standard Template Library) sequence containers or to user written containers if they satisfy the access function requirements. but that have specific properties that are suitable for your problem domain. Answer: The extensibility mechanisms allow you to customize and extend the UML by adding new building blocks. By using stereotyped nodes you can make these things appear as primitive building blocks. e. with the same public interface. when modeling a network you might need to have symbols for representing routers and hubs. let us consider exception classes in Java or C++. nothing else. creating new properties. Stereotypes also allow you to introduce new graphical symbols for providing visual cues to the models that speak the vocabulary of your specific domain. if you wanted to implement a stack of items. or basic. They are used for classifying or marking the UML building blocks in order to introduce new building blocks that speak the language of your domain and that look like primitive. pop(). Why might you want to do this? Well.

or you can use it to denote the author and the version of a component. For example. One of the most common uses of a tagged value is to specify properties that are relevant to code generation or configuration management.  Constraints Constraints are properties for specifying semantics and/or conditions that must be held true at all times for the elements of a model. The string consists of a name (the tag). you can regard a tagged value as being a metadata.  Tagged Values Tagged values are properties for specifying keyword-value pairs of model elements. a separator (the symbol =). since its value applies to the element itself and not to its instances. They allow you to extend the semantics of a UML building block by adding new rules. a stereotype is rendered as a name enclosed by guillemots and placed above the name of another element. Instead. and deploying releases. or modifying existing ones. Tagged values can be defined for existing model elements. Alternatively. As another example of where tagged values can be useful. when modeling hard real time systems it could be useful to adorn the models with some additional information. which is placed below the name of another model element. and so one way of adding this information to the models is to use tagged values. where the keywords are attributes. consider the release team of a project. In such a case it might be feasible to keep track of the version number and test results for each main subsystem. and a value (of the tag). They allow you to extend the properties of a UML building block so that you create new information in the specification of that element. which is responsible for assembling. By making use of constraints these timing requirements can easily be captured. you can make use of a tagged value in order to specify the programming language to which you map a particular class. you can render the stereotyped element by using a new icon associated with that stereotype. Graphically. testing. for example. It is important to mention that a tagged value is not equal to a class attribute. So. as shown below. so that everything with that stereotype has that tagged value. such as time budgets and deadlines.Graphically. or for individual stereotypes. a tagged value is rendered as a string enclosed by brackets. .

Graphically. a constraint is rendered as a string enclosed by brackets. in order to visualize parts of an element’s specification that have no graphical cue. you can use constraint notation to provide some properties of associations. such as order and changeability. Refer to the diagram below to understand the use of constraints. For example. which is placed near the associated element(s). . or connected to the element(s) by dependency relationships. This notation can also be used to adorn a model element’s basic notation.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.