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

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. Answer: void main() { int m1[10][10],i,j,k,m2[10][10],add[10][10], printf("Enter number of rows and columns of first matrix MAX 10\n"); scanf("%d%d",&r1,&c1); printf("Enter number of rows and columns of second matrix MAX 10\n"); scanf("%d%d",&r2,&c2); if(r2==c1) { printf("Enter rows and columns of First matrix \n"); printf("Row wise\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&m1[i][j]); } printf("You have entered the first matrix as follows:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%d\t",m1[i][j]); printf("\n"); } printf("Enter rows and columns of Second matrix \n"); printf("Again row wise\n"); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) scanf("%d",&m2[i][j]); } printf("You have entered the second matrix as follows:\n"); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) printf("%d\t",m2[i][j]); printf("\n"); } if(r1==r2&&c1==c2) { printf("Now we add both the above matrix \n"); printf("The result of the addition is as follows;\n");

for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { add[i][j]=m1[i][j]+m2[i][j]; printf("%d\t",add[i][j]); } printf("\n"); } } else { printf("Addition cannot be done as rows or columns are not equal\n"); } printf("Now we multiply both the above matrix \n"); printf("The result of the multiplication is as follows:\n"); /*a11xA11+a12xA21+a13xA31 a11xA12+a12xA22+a13xA32 a11xA13+a12xA23+a13xA33*/ for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { mult[i][j]=0; for(k=0;k<r1;k++) { mult[i][j]+=m1[i][k]*m2[k][j]; /*mult[0][0]=m1[0][0]*m2[0][0]+m1[0][1]* } printf("%d\t",mult[i][j]); } printf("\n"); } getch(); } else { printf("Matrix multiplication cannot be done"); } }

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. #include <iostream> #include <string> using namespace std; int main() { char str[100]; cout << "Enter word :"; cin >> str; int x = strlen(str)-1; for(int i = 0; i <= x; i++) { if (str[i] == str[x-i]) { continue; } else { cout<<"Not a palidrome"<<endl; return 0; } } cout << "Indeed Palidrome"<<endl; return 0; }

3. What is 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 atleast 100 product data. A data 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 structures are declared in C++ using the following syntax: struct structure_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names; where structure_name is a name for the structure type, object_name can be a set of valid identifiers for objects that have the type of this structure. Within braces { } there is a list with the data members, each one is specified with a type and a valid identifier as its name. The first thing we have to know is that a data structure creates a new type: Once a data structure is declared, a new type with the identifier specified as structure_name is created and can be used in the rest of the program as if it was any other type. For example: struct product { int weight; float price; }; product apple; product banana, melon; Exception handling Purpose::

4. What is the purpose of exception handling? How do you infer from the phrase, Throwing an exception?. Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution. Programming languages differ considerably in their support for exception handling (as distinct from error checking, which is normal program flow that codes for responses to contingencies such as unsuccessful termination of invoked operations). In some programming languages there are functions which cannot be safely called on invalid input data or functions which return values which cannot be distinguished from exceptions. For example, in C the atoi (ASCII to integer conversion) function may return 0 (zero) for any input that cannot be parsed into a valid value. In such languages, the programmer must either perform error checking (possibly through some auxiliary global variable such as C's errno) or input validation (perhaps using regular expressions) or both. The degree to which such explicit validation and error checking is necessary is in contrast to exception handling support provided by any given programming environment. Hardware exception handling differs somewhat from the support provided by software tools, but similar concepts and terminology are prevalent. In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. Depending on the situation, the handler may later resume the execution at the original location using the saved information. For example, a page fault will usually allow the program to be resumed, while a division by zero might not be resolvable transparently. From the processing point of view, hardware interrupts are similar to resume-able exceptions, though they are typically unrelated to the user's program flow. From the point of view of the author of a routine, raising an exception is a useful way to signal that a routine could not execute normally. For example, when an input argument is invalid (e.g. a zero denominator in division) or when a resource it relies on is unavailable (like a missing file, or a hard disk error). In systems without exceptions, routines would need to return some special error code. However, this is sometimes complicated by the semipredicate problem, in which users of the routine need to write extra code to distinguish normal return values from erroneous ones. One mechanism for raising an exception is known as a throw. The exception is said to be thrown. Execution is transferred to a "catch". In runtime engine environments such as Java or .NET, there exist tools that attach to the runtime engine and every time that an exception of interest occurs, they record debugging information that existed in memory at the time the exception was thrown (call stack and heap values). These tools are called automated exception handling or error interception tools and provide 'root-cause' information for exceptions. Contemporary applications face many design challenges when considering exception handling strategies. Particularly in modern enterprise level applications, exceptions must often cross process boundaries and machine boundaries. Part of designing a solid exception handling strategy is recognizing when a process has failed to the point where it cannot be economically handled by the software portion of the process.[

Book ID: B0681 1. Write a program which accepts a number from the user and generates prime numbers till that number #include<iostream.h> #include<conio.h> main() { int n,i,f=1; cout<<"enter any no to check prime"; cin>>n; for(i=2;i<n;i++) { if(n%i==0) k=2; } if(k==2) cout<<"the no is not prime"<<endl; else cout<<"the no is prime"; } getch(); }

Book ID: B0715 2. What are allocators? Describe the sequence container adapters. Default allocator Allocators are classes that define memory models to be used by some parts of the Standard Library, and most specifically, by STL containers. This section describes the default allocator template allocator (lowercase). This is the allocator that all standard containers will use if their last (and optional) template parameter is not specified, and is the only predefined allocator in the standard library. Other allocators may be defined. Any class having the same members as this default allocator and following its minimum requirements can be used as an allocator -- notice that only under very specific circumstances this is needed. Technically, a memory model described by allocators might be specialized for each type of object to be allocated and even may store local data for each container they work with. Although this does not happen with the default allocator.

The class template of allocator is declared as: template < class T > class allocator; ----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 execution 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.

4. Write about the following with the help of suitable programming examples: A) Throwing an Exception B) Catching an Exception Answer: A) Throwing an Exception Using exceptions, one way to do this might be: #include <iostream.h> class DateException { char* err; public: DateException(char* s) {err = s;} void print() const {cerr << err << endl;} }; // a function that operates on dates void g(int date) { if (date < 1900) throw DateException("date < 1900"); if (date > 1999) throw DateException("date > 1999"); // process date ... } // some code that uses dates void f() { g(1879); } int main() { try {

f(); } catch (const DateException& de) { de.print(); return 1; } return 0;

The basic idea here is that we have a try block: try { f(); } Within this block, we execute some code, in this case a function call f(). Then we have a list of one or more handlers: catch (DateException de) { de.print(); return 1; } If an abnormal condition arises in the code, we can throw an exception: if (date < 1900) throw DateException("date < 1900"); and have it caught by one of the handlers at an outer level, that is, execution will continue at the point of the handler, with the execution stack unwound.

B) Catching an Exception Example using the exception handling functions (C++ only) The following example shows the flow of control and special functions used in exception handling: #include <iostream> #include <exception> using namespace std; class X { }; class Y { }; class A { }; // pfv type is pointer to function returning void typedef void (*pfv)(); void my_terminate() { cout << "Call to my terminate" << endl; abort(); } void my_unexpected() { cout << "Call to my_unexpected()" << endl; throw; } void f() throw(X,Y, bad_exception) { throw A(); } void g() throw(X,Y) {

throw A(); } int main() { pfv old_term = set_terminate(my_terminate); pfv old_unex = set_unexpected(my_unexpected); try { cout << "In first try block" << endl; f(); } catch(X) { cout << "Caught X" << endl; } catch(Y) { cout << "Caught Y" << endl; } catch (bad_exception& e1) { cout << "Caught bad_exception" << endl; } catch (...) { cout << "Caught some exception" << endl; } cout << endl; try { cout << "In second try block" << endl; g(); } catch(X) { cout << "Caught X" << endl; } catch(Y) { cout << "Caught Y" << endl; } catch (bad_exception& e2) { cout << "Caught bad_exception" << endl; } catch (...) { cout << "Caught some exception" << endl; }

} The following is the output of the above example: In first try block Call to my_unexpected() Caught bad_exception In second try block Call to my_unexpected()

Call to my terminate The output also includes a memory dump in the core file in the current directory because of a call to the abort() function. At run time, this program behaves as follows: 1. The call to set_terminate() assigns to old_term the address of the function last passed to set_terminate() when set_terminate() was previously called. 2. The call to set_unexpected() assigns to old_unex the address of the function last passed to set_unexpected() when set_unexpected() was previously called. 3. Within the first try block, function f() is called. Because f() throws an unexpected exception, a call to unexpected() is made. unexpected() in turn calls my_unexpected(), which prints a message to standard output. The function my_unexpected() tries to rethrow the exception of type A. Because class A has not been specified in the exception specification of function f(), my_unexpected() throws an exception of type bad_exception. 4. Because bad_exception has been specified in the exception specification of function f(), the handler catch (bad_exception& e1) is able to handle the exception. 5. Within the second try block, function g() is called. Because g() throws an unexpected exception, a call to unexpected() is made. The unexpected() throws an exception of type bad_exception. Because bad_exception has not been specified in the exception specification of g(), unexpected() calls terminate(), which calls the function my_terminate(). 6. my_terminate() displays a message then calls abort(), which terminates the program. In addition, the abort() function sends a SIGIOT signal, which terminates the process and produces a memory dump in the core file in the current directory. Note that the catch blocks following the second try block are not entered, because the exception was handled by my_unexpected() as an unexpected throw, not as a valid exception.

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