Assignment Set - 1
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() {
char c[]; int i,j,length,flag=0; cout<<"Enter a text to search"; cin>>a; length=strlen(a); // This is going to save the length of the string of a to the variable length for(i=0;j<length-1;i<len/2;i++;j--) { if(a[i]!=a[j]) { flag=1; break; } } if(flag==0) cout<<"The text entered is a Palindrome"; else cout<<"The text entered is not a Palindrome"; getch(); } 3. Define a structure in C++? Define a structure named product with elements productcode, description, unitprice and qtyinhand. Write a C++ Program that implements the structure and enables to store at least 100 Product data. Answer: A structure is a user defined data type. A structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. Data that are of different types but are logically related can be grouped together. This can be done through structures. For example.. struct product { int weight; float price; }; product apple; product banana, melon; We have first declared a structure type called product with two members: weight and price, each of a different fundamental type. We have then used this name of the structure type (product) to declare three objects of that type: apple, banana and melon as we would have done with any fundamental data type. To access members of the structure dot operators can be used. For example to access weight of a product, we should address melon.weight
// A C++ program defining structure #include<iostream.h> #include<conio.h> struct product { int productcode,qtyinhand; char description; float unitprice; }p[100]; void main() { int i; for(i=0;i<100;i++) { cout<<"Enter Product Code"; cin>>p[i].productcode; cout<<"Enter Product Description"; cin>>p[i].description; cout<<"Enter Quantity in hand"; cin>>p[i].qtyinhand; } getch(); } 4. 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. 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. In C++, 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. Furthermore, exception handling in C++ propagates the exceptions up the stack; therefore, if there are several functions called, 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. One consequence is that functions don't need to return error codes, freeing their return values for program logic. Exception handling is a better way of handling errors. With exception handling: Error handling code is not nearly so tedious to write and it doesnt become mixed up with normal code. The code is written in a fashion where the problem is bound to be expected and cope up with that accordingly. If a call has been made to a particular function, handling errors from that function is one at one place.
Errors should not be ignored. If a function needs to send an error message to the caller of that function, it throws an object representing that error out of the function. If the caller doesnt catch the error and handle it accordingly, it goes to the next enclosing scope and so on until someone catches the error message.
Throwing an exception
When errors occur, the function generating the error can 'throw' an exception. For example, take a sample function that does division: const int DivideByZero = 10; //.... double divide(double x, double y) { if(y==0) { throw DivideByZero; } return x/y; } The function will throw DivideByZero as an exception that can then be caught by an exceptionhandling catch statement that catches exceptions of type int. The necessary construction for catching exceptions is a try catch system. If you wish to have your program check for exceptions, you must enclose the code that may have exceptions thrown in a try block. For example: try { divide(10, 0); } catch(int i) { if(i==DivideByZero) { cerr<<"Divide by zero error"; } } The catch statement catches exceptions that are of the proper type. You can, for example, throw objects of a class to differentiate between several different exceptions. As well, once a catch statement is executed, the program continues to run from the end of the catch. It is often more useful for you to create a class that stores information on exceptions as they occur. For example, it would be more useful if you had a class to handle exceptions. class DivideByZero { public: double divisor; DivideByZero(double x); }; DivideByZero::DivideByZero(double x) : divisor(x) {} int divide(int x, int y)
{ if(y==0) { throw DivideByZero(x); } } try { divide(12, 0); } catch (DivideByZero divZero) { cerr<<"Attempted to divide "<<divZero.divisor<<" by zero"; } If you wish to catch more than one possible exception, you can specify separate catch blocks for each type of exception. It's also possible to have a general exception handler that will respond to any thrown exception. To use it, simply use catch(...) for the catch statement and print a general warning of some kind. The handy thing to remember about exception handling is that the errors can be handled outside of the regular code. This means that it is easier to structure the program code, and it makes dealing with errors more centralized. Finally, because the exception is passed back up the stack of calling functions, you can handle errors at any place you choose.
Assignment Set -2
1. 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> #include<conio.h> void main() { int n,prime; cout<<"Enter a number"; cin>>n; cout<<"Prime Numbers are :"; for(int i=2;i<=n;i++) { prime=0; for(int j=2;j<=i/2;j++) { if(i%j==0) { prime=1; break; } } if(prime==0) { cout<<i<<endl; } } getch(); } 2. Implement a class stack which simulates the operations of the stack allowing LIFO operations and also implement push & pop operations for the stack. Answer: // A class implementation of a stack #include<iostream.h> #include<conio.h> #define size 100 class size 200 { int stck[size],top; public : stack() {
{ top=0; cout<<"Stack Initialized"<<endl; } void push(int i); int pop(); } void stack::push(int i) { if(top==size) { cout<<"Stack is FULL"; return; } stck[top]=i; top++ } int stack::pop() { if(top==0) { cout<<"Stack Underflow"; return 0; } top--; return stck[top]; } void main() { stack a,b; a.push(1); b.push(2); a.push(3); b.push(4); cout<<a.pop()<<" "; cout<<a.pop()<<" "; cout<<a.pop()<<" "; cout<<a.pop()<<endl; } } 3. What are allocators? Describe the sequence container adapters. Answer: Allocators Allocators allocate raw memory, and return it. They do not create or destroy objects. Allocators are very "low level" features in the STL (Standard Template Library) and are designed to encapsulate memory allocation and deallocation. This allows for efficient storage by use of different schemes for particular container classes. The default allocator, alloc, is thread-safe and has good performance 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 the defaults work well for most applications. 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. Why might you want to do this? Well, if you wanted to implement a stack of items, you might at first decide to base your stack class on the list container - lets call it ListStack - and define public member functions for push(), pop(), empty() and top(). However, you might later decide that another container like a vector might be better suited to the task. You would then have to define a new stack class, with the same public interface, but based on the vector, e.g. VectorStack, so that other programmers could choose a list or a vector based queue. It is obvious that the number of names for what is essentially the same thing start to mushroom. In addition, this approach rules out the programmer using his or her own underlying class as the container. Container adapters neatly solve this by presenting the same public interface irrespective of the underlying container. Being templatized, they avoid name proliferation. 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. It is important to note that the adapters provide a restricted interface to the underlying container, and you cannot use iterators with adapters. 4. Describe the extensibility mechanisms of UML. Answer: The extensibility mechanisms allow you to customize and extend the UML by adding new building blocks, creating new properties, and specifying new semantics in order to make the language suitable for your specific problem domain. There are three common extensibility mechanisms that are defined by the UML: stereotypes, tagged values, and constraints. Stereotypes Stereotypes allow you to extend the vocabulary of the UML so that you can create new model elements, derived from existing ones, but that have specific properties that are suitable for your problem domain. 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, or basic, model elements. For example, when modeling a network you might need to have symbols for representing routers and hubs. By using stereotyped nodes you can make these things appear as primitive building blocks. As another example, let us consider exception classes in Java or C++, which you might sometimes have to model. Ideally you would only want to allow them to be thrown and caught, nothing else. Now, by marking them with a suitable stereotype you can make these classes into first class citizens in your model; in other words, you make them appear as basic building blocks. Stereotypes also allow you to introduce new graphical symbols for providing visual cues to the models that speak the vocabulary of your specific domain, as shown below.
Graphically, a stereotype is rendered as a name enclosed by guillemots and placed above the name of another element.
Alternatively, you can render the stereotyped element by using a new icon associated with that stereotype.
Tagged Values Tagged values are properties for specifying keyword-value pairs of model elements, where the keywords are attributes. They allow you to extend the properties of a UML building block so that you create new information in the specification of that element. Tagged values can be defined for existing model elements, or for individual stereotypes, so that everything with that stereotype has that tagged value. It is important to mention that a tagged value is not equal to a class attribute. Instead, you can regard a tagged value as being a metadata, since its value applies to the element itself and not to its instances. One of the most common uses of a tagged value is to specify properties that are relevant to code generation or configuration management. So, for example, you can make use of a tagged value in order to specify the programming language to which you map a particular class, or you can use it to denote the author and the version of a component. As another example of where tagged values can be useful, consider the release team of a project, which is responsible for assembling, testing, and deploying releases. In such a case it might be feasible to keep track of the version number and test results for each main subsystem, and so one way of adding this information to the models is to use tagged values. Graphically, a tagged value is rendered as a string enclosed by brackets, which is placed below the name of another model element. The string consists of a name (the tag), a separator (the symbol =), and a value (of the tag), as shown below.
Constraints Constraints are properties for specifying semantics and/or conditions that must be held true at all times for the elements of a model. They allow you to extend the semantics of a UML building block by adding new rules, or modifying existing ones. For example, when modeling hard real time systems it could be useful to adorn the models with some additional information, such as time budgets and deadlines. By making use of constraints these timing requirements can easily be captured.
Graphically, a constraint is rendered as a string enclosed by brackets, 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 elements basic notation, in order to visualize parts of an elements specification that have no graphical cue. For example, 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.