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

DATA STRUCTURES THROUGH C++ UNIT-1 Introduction to C++ y C++ is an object-oriented language developed by Bjarne stroustrup at AT&T Bell

laboratories in New Jersey, USA. y C++ is an extension of C with major addition of class construct features. Hence, initially the language was called C with classes. y However, later in 1983, the name was changed to C++. The idea of C++ comes from the C increment operator ++, there by suggesting that C++ is an increment version of C. y C++ is a superset of C. most of what we already know about C applies to C++ also. y C++ is an object oriented programming language. So it is well suited for developing the real world applications including development of editors, compilers, databases, communication systems and complex real-life application systems. A simple C++ program: // A C++ program which prints a string on the screen. Ex: #include<iostream> //include header file void main( ) { cout<< welcome to c++; } Program features: 1) Preprocessor directive: #include<iostream> This preprocessor directive caises the preprocessor to add the contents of iostream file to the program. The header file iostream should be included at the beginning of all programs that use input/output statements. 2) Comments: C++ introduces a new comment symbol //(double slash). A comment may start anywhere in the line, and whatever follows till the end of the line is ignored. The double slash comment is basically a single line comment. The C comment symbols /*, */ are still valid and are more suitable for multiline comments. C++ Input/Output operators: 1. Output operator: Ex: cout<< welcome to c++ programming; The above statement causes the string in quotation marks to be displayed on the screen. This statement as two new features cout and <<. The identifier cout is a predefines object that represents the standard output stream in C++ i.e., screen.

Screen

cout

<<

Variable

The operator << is called the insertion or put to operator. It inserts the contents of the variable on its right to the object on its left.

Jyothi

Page 1

2. Input operator: Ex: cin>>number1; The above is an input statement and causes the program to wait for the user to type n a number. The number keyed in is placed in the variable number1. The identifier cin is a predefined object in c++ that corresponds to the standard input stream. The operator >> is known as extraction or get from operator. It extracts the value from the keyboard and assign it to the variable on its right.

Screen

cin

>>

Variable

Cascading of I/O operators The multiple use of I/O operators in one statement is called Cascading. When cascading an output operator, we should ensure necessary blank spaces between different items. Cascading output operator Ex: cout <<sum= << sum <<\n ; In the above statement first sends the string sum= to cout and then sends the value of sum. Finally it sends the newline character so that the next output will be new line. Cascading input operator Ex: cin >> number1 >> number2; The values are assigned from left to right. i.e., if we key in two values, say, 10 and 20, then 10 will be assigned to number1 and 20 is assigned to number2. // write a C++ program to find out the average of two numbers. # include <iostream.h> #include<conio.h> int main( ) { clrscr(); float num1, num2, sum, avg; cout << enter two numbers; cin >> num1>> num2; sum = num1 + num2; avg =sum/2; cout << sum= << sum <<\n avg= << avg << \n ; getch( ); return 0; } C++ Tokens The smallest individual units in a program are known as tokens. C++ has the following tokens. 1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Operators. 1. Keywords: They are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements.
Jyothi Page 2

Ex: using, export, explicit, false, true, typename. 2. Identifiers and Constants: Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the programmer. The following are the rules common to C and C++. 1. Only alphabetic characters, digits and underscores are permitted. 2. The name cannot start with a digit. 3. Uppercase and lowercase letters are distinct. 4. A declared keyword cannot be used as a variable name. 5. Constants refer to fixed values that do not change during the execution of a program. Like C, C++ supports several kinds of literal constants. They include integers, characters, floating point numbers and strings. Basic Data Types Data types in C++ can be classified into various categories.
C++ Data Types User-defined type Structure Union Class Built-in Type Derived type Array Function Pointer Reference

enumeration
void Integral type Floating point double

int
Operators in C++

char

float

C++ has a rich set of operators. All C operators are valid in C++. In addition, C++ introduces some new operators. We have already seen two such operators, namely, the insertion operator << , and the extraction operator >>. Other new operators are: :: Scope resolution operator ::* Pointer-to-member declarator ->* Pointer-to-member operator .* Pointer-to-member operator delete Memory release operator endl Line feed operator new memory allocation operator setw Field width operator Scope Resolution Operator Like C, C++ is also block-structured language. Blocks and scope can be used in constructing programs. We know that the same variable name can be used to have different meanings in different

Jyothi

Page 3

blocks. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside a block is said to be local to that block. In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by introducing a new operator:: called the scope resolution operator. This can be used to uncover a hidden variable.

:: variable-name
This variable allows access to the global version of a variable. #include <iostream.h> #include <conio.h> int m=10; //global m void main( ) { clrscr(); int k=m; int m=30;//m declared again local to inner block cout << "k= "<< k << "\n"; cout << "m= " << m <<"\n"; cout<<"m="<< ::m <<endl; getch( ); } Output: k=10 m=30 m=10

Types of programming languages:


The high level programming languages are mainly divided into two types, procedure oriented, object oriented. Procedural oriented languages: Conventional programming , using high level languages such as COBOL, FORTRAN and C, is commonly known as procedure-oriented programming (POP). Procedure-oriented programming basically consists of writing a list of instructions (or actions) for the computer to follow, and organizing these instructions into groups known as functions. Drawbacks of procedural oriented languages: 1. Data security is not provided. 2. It is not suitable for real-world applications. Introduction to object-oriented programming OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The data of an object can be accessed only by the functions associated with that object.

Jyothi

Page 4

Object A

object B

Data

Data

Function

Communication

Function

Benefits of object oriented programming: y Data security is enforced. y Inheritance saves time. y User defined data types can be easily constructed. y Inheritance emphasizes inventions of new data types. y Large complexity in the software development cn be easily managed.

Differences between procedure vs object oriented languages: Procedure oriented Emphasis on doing things. Larger programs can be divided into smaller functions. Most of the share global data. Data moves freely around functions. object oriented 1. Emphasis on data rather than procedure. 2. Programs are divided into objects. 3. Functions and data tied together. 4. Data is hidden and cant accessed by outside Functions. 5. Easily added. 6. Follows bottom-up approach.

1. 2. 3. 4.

5. Difficult to add new data & functions 6. Employ top-down approach.

Basic concepts of object-oriented programming It is necessary to understand some of the concepts used extensively in object-oriented programming.  Objects  Classes  Encapsulation  Inheritance  Polymorphism  Dynamic binding  Message passing  Data abstraction Objects: Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. Classes: The most important feature of C++ is the class. The entire set of data and code of an object can be made a user-defined data type with the help of the class.
Jyothi Page 5

Ex: if fruit has been defined as a class, then the statement fruit mango; will create an object mango belonging to the class fruit. A class is an extension of the idea of structure used in C. Data Abstraction and Encapsulation: The wrapping up of data and functions in to a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access. This insulation of the data from direct access by the program is called data hiding. Abstraction : Abstraction refers to the act of representing essential features without including the background details or explanations. since the classes use the concept of data abstraction ,they are known as abstraction data type(ADT). Inheritance : Inheritance is the process by which objects of one class acquire the properties of objects of another class. for example: The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'. The concept of inheritance provides the idea of reusability. Polymorphism: Polymorphism is another important oop concept. Polymorphism means the ability to take more than one form. An operation may exhibit different instances. The process of making an operator to exhibit different behaviors in different instance is known as operator overloading. C Structures Revisited: They provide a method for packaging together data of different types. A structure is a convenient tool for handling a group of logically related data items. Once the structure type has been defined, we can create variables of that type using declarations that are similar to the built-in type declarations. Ex: struct student { char name[20]; int roll_number; float total_marks; };
Jyothi Page 6

The keyword struct declares student as a new data type that can hold three fields of different data types. These fields are known as structure members or elements. struct student A; //C declaration A is a variable of type student and has three member variables as defined by the template. Member variables can be accessed using the dot or period operator. strcpy(A.name,john); A.roll_number=999; A.total_marks=595.5; Final_total=A.total_marks+5; Limitations of C structure y y The standard does not allow the struct data type to be treated like built-in types. C structures does not provide the data hiding.

Extensions to C structures: C++ supports all the features of structures defined in C. in C++, a structure can have both variables and functions as members. It can also declare some of its members as private so that they cannot be accessed directly by the external functions. C++ incorporates all these extensions in another user-defined type known as class. There is a little syntactical difference between structures and classes in C++. Specifying a class: A class is a way to bind the data and its associated functions together. Generally a class specification has two parts. 1. Class declaration. 2. Class function definition. The class declaration describes the type and scope of its members. The class function definition describes how the class functions are implemented. General form of class declaration: class class _name { private: Variable declarations; Function declarations; public: Variable declaration; Function declaration; }; A class declaration is similar to a struct declaration. The keyword class specifies that what follows is an abstract data type class_name. The body of a class is enclosed within braces and terminated by a semicolon. The class body contains the declarations of variables and functions. These functions and
Jyothi Page 7

variables are collectively called class members. The keywords private & public are known as visibility labels. The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. By default, the members of a class are private. The variables declared inside the class are known as data members and the functions are known as member functions. Creating objects: The declaration of an object is similar to that of a variable of any basic type. The necessary memory space is allocated to an object at the stage. Since class is a user defined data type memory is not allocated directly. In order to allocate memory for the class members a reference variable is created, that is called as object. So object is called as instance of the variable. <class name> <object name> Accessing the class members The data members of the class can be accessed through the object if they are public. <object name>.<variable name> Dot operator is called as member access operator. Private data members can accessed only by the member function. Defining member functions: Member functions can be define in two places 1. outside the class definition 2. inside the class definition Outside the class definition: Member functions that are declared inside a class have to be defining separately outside the class. Their definitions are very much like the normal functions. They should have a function header and a function body. Syntax: return- type class-name::function-name(argument declaration) { Function body } //program to demo member function outside the class #include<iostream.h> class sample { private: int x; public: void getdata( ); void display( ); };
Jyothi Page 8

void sample::getdata( ) { cout <<enter x value\n; cin>>x; } void sample::display( ) { cout <<x=<<x; } void main( ) { clrscr( ); sample s; s.getdata( ); s.display( ); getch( ); } Inside the class definition: Another method of defining a member function is to replace the function declaration by the actual function definition inside the class. class sample { private: int x; public: void getdata( ) { cout<<enter x value\n; cin>>x; } void display( ) { cout<<x=<<x<<endl; } }; void main( ) { clrscr( ); sample s; s.getdata( ); s.display( ); getch( ); } Access Control The classes in C++ have 3 important access levels. They are Private, Public and Protected. The explanations are as follows.
Jyothi Page 9

Private: The members are accessible only by the member functions or friend functions. Protected: These members are accessible by the member functions of the class and the classes which are derived from this class. Public: Accessible by any external member.

//program to demo member functions with arguments #include<iostream.h> #include<conio.h> class sample { private: int x,y; public: void getdata(int a, int b ) { x=a; y=b; } void display( ) { cout<<x=<<x<<endl<<y=<<y<<endl; } }; void main( ) { clrscr(); sample s; s.getdata(10,20); s.display( ); getch(); }

Constructors & Destructors


C++ provides special member function called the constructor which enables an object to initialize itself when it is created. It also provides another member function called destructor that destroys the objects when they are no longer required. Constructors: Constructors in C++ are special member functions of a class. They have the same name as the Class Name . There are some important qualities for a constructor to be noted. *
Jyothi

Are used to initialize the member variables of the class when the objects of the class are created
Page 10

* * *

Must have the same name as that of class name Cannot return any value, not even a void type Class can have more than one constructors defined in it (known as overloaded constructors).

Constructors are 3 types 1. Default constructor. 2. Parametric constructor. 3. Copy constructor. Default constructor: Default constructors accept no parameters and are automatically invoked by the compiler. When we declare the object without parameters the default constructor will be invoked.. //program to demo default constructor class sample { private: int x,y; public: sample( ) { x=10; y=20; } void display( ) { cout<<x=<<x<<endl; cout<<y=<<y<<endl; } }; void main( ) { sample s; s.display( ); getch( ); } Parametric constructor: These constructors accept general variables as arguments such as ordinary type, array type and pointer type etc.are called as parametric constructors. //program to demo parametric constructor class sample { private: int x,y; public:sample( int a,int b) { x=a;y=b; } void display( ) {
Jyothi Page 11

cout<<x=<<x<<endl<<y=<<y<<endl; } }; void main( ) { sample s(10,20); s.display( ); getch( ); } Copy constructor: A constructor which accept object of class as argument is called as copy constructor. Generally a copy constructor is used to declare and initialize an object from another object. The process of initializing through a copy constructor is known as copy initialization. //program to demo copy constructor class sample { private: int x; public: sample( ) { x=10; } sample( int a) { x=a; } sample( sample &obj) { x=obj.x; } void display( ) { cout<<x=<<x<<endl; } }; void main( ) { sample s1; s1.display( ); sample s2(100); s2.display( ); sample s3(s2); s3.display( ); getch( ); }

Jyothi

Page 12

Destructors * * * * * * Are used to de-initialize the objects when they are destroyed Are used to clear memory space occupied by a data member when an object goes out of scope Must have the same name as that of the class, preceded by a ~ (For example: ~sample()) Are automatically invoked. Can also be explicitly invoked when required. Cannot be overloaded.

class sample { private: int x; public: sample( ) { x=10; } sample( int a) { x=a; } sample( sample &obj) { x=obj.x; } void display( ) { cout<<x=<<x<<endl; } ~sample( ) { cout<<destructor is called; } }; void main( ) { sample s1; s1.display( ); sample s2(100); s2.display( ); sample s3(s2); s3.display( ); getch( ); }

Jyothi

Page 13

Functions
A function is a self contained block of statements that perform a specified task. It is a basic building block of the program. A function is a set of instructions that can be processed independently. Note: any C++ program contain at least one function main( ). There is no limit for the no of functions in a C++ program.

Advantages: 1. It makes a program easier to understand and maintain. 2. Functions can be reused in many programs. 3. One large project can be divided into small functions. 4. It is easier to debug programs. 5. Reduce work and time.
Defining function in C++: 1. Function prototype 2. Function call. 3. Function definition.

Function prototype:
Prototype is used to inform compiler in advance such a function will occur in a program. When compiler is called , compiler uses the prototype to check that proper arguments are passed or not. Syntax: Return-type function_name(arg_list); Ex: int add(int,int);

Function call:
Function call include function name and arguments without data type. Executing the call statement causes the function to execute, control is transferred to the function ,the statements in the function definition are executed and then control returns to calling function.

Function definition:
Function definition contains actual code for the function . Return statement: It serves two purposes. 1. On executing return statement it immediately transfers the control back to the calling program. 2. It returns the value present in the parenthesis after return, to the calling program. Note: a function can return only one value at a time.

Parameter passing methods


Call by value:
In this function, information is passed to the called function by passing the values of parameters. This is the default mechanism for argument passing. The call by value mechanism does not change the content of the arguments in the calling function even if they are changed in the called function. this means that any changes made to the formal arguments within the function do not affect the actual arguments.
Jyothi Page 14

//write a C++ program to implement call by value mechanism void swap(int, int); void main() { int a,b; cout<<enter a,b values\n; cin>>a>>b; cout<<before swap\n; cout<<a=<<a<<\nb=<<b; swap(a,b); cout<<after swap\n; cout<<a=<<a<<\nb=<<b; getch(); } void swap(int x, int y) { int temp; temp=x; x=y; y=temp; } o/p: enter a,b values 10 20 Before swap a=10 b=20 after swap a=10 b=20

CALL BY REFERENCE:
In the Call by reference mechanism the function is allowed to access the actual memory locations of the caller variables. This is possible only with pointers because pointers are special variables which can store the address of the other variables. This is a mechanism of invoking a function by passing reference of actual parameters.

reference variable:
C++ reference variables enable to create a second name for a variable that can be used to read or modify the original data stored in that. Syntax: <type> &<name> Ex: int &ref; It creates a reference variable called ref of the type integer. Using reference variable: int x; int &ref=x; in the above declaration reference variable ref becomes an alias for variable x. both x and ref refer to the same memory location.

Jyothi

Page 15

//write a C++ program to implement call by reference mechanism


void swap(int *, int *); void main() { int a,b; cout<<enter a,b values\n; cin>>a>>b; cout<<before swap\n; cout<<a=<<a<<\nb=<<b; swap(&a,&b); cout<<after swap\n; cout<<a=<<a<<\nb=<<b; getch(); } void swap(int *x, int *y) { int temp; temp=*x; *x=*y; *y=temp; } o/p: enter a,b values 10 20 Before swap a=10 b=20 after swap a=20 b=10

Return by reference: A function call can also return a reference. Ex: int & max(int &x, int &y) { if( x>y) return x; else return y; } Since the return type of max() is int &, the function returns reference to x or y. then a function call such as max(a,b) will yield a reference to either a or b depending on their values. This means that the function call can appear on the left-hand side of an assignment statement. Max(a,b)=-1; Is legal and assigns -1 to a if it is no larger, otherwise -1 to b.

Jyothi

Page 16

Inline functions
One of the objectives of using the functions in a program is to save some memory space. However, every time a function is called, it takes a lot extra time in executing a series of instructions for tasks such as jumping to the function, saving registers and returning to the calling function especially for small functions. C++ has a solution to this problem. To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function. An inline function is a function that is expanded in line when it is invoked. That is, the compiler replaces the function call with the corresponding function code. The inline functions are defined as follows. inline function header { Function body } I It is easy to make a function inline. All we need to is to prefix the keyword inline to the function definition. All inline functions must be defined before they are called. //program to demo inline functions #include<iostream.h> #include<conio.h> class inline_demo { int a,b; public: inline void get( ) { cout<<"enter a,b values"<<endl; cin>>a>>b; } inline void display( ) { a=a+10; b=b+20; cout<<"a="<<a<<endl<<"b="<<b<<endl; } }; void main( ) { clrscr(); inline_demo i; i.get( ); i.display( ); getch( ); } We should exercise care before making a function inline. The speed benefits of inline functions diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function, and the benefits of inline functions may be lost. In such cases, the use of normal functions will be more meaningful.
Jyothi Page 17

Static class members Static data members: A data member of a class can be qualified as static. The properties of a static member variable are similar to that of a C static variable. The properties of a static member variable are as follows y It is initialized to zero when the first object of its class is created. No other initialization is permitted. y Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter of how many objects are created. y It is visible only within the class, but its lifetime is the entire program. y Static variables are normally used to maintain values common to the entire class. //program to demo static data members. #include<iostream.h> #include<conio.h> class item { static int count; int number; public: void getdata(int a) { number=a; count++; } void getcount(void) { cout<<"count:"; cout<<count<<"\n"; } }; int item::count; int main() { item a,b,c; a.getcount(); b.getcount(); c.getcount(); a.getdata(100); b.getdata(200); c.getdata(300); cout<<"after reading data\n"; a.getcount(); b.getcount(); c.getcount(); getch();
Jyothi Page 18

return 0; } Static member functions: Like static member variable, we can also have static member functions. A member function that is declared static has the following properties. A static function can have access to only other static members declared in the same class. A static member function can be called using the class name as follows: Class-name :: function-name;

this pointer
C++ uses a unique keyword called this to represent an object that invokes a member function. this is a pointer that points to the object for which this function was called. This unique pointer is automatically passed to a member function when it is called. The pointer this acts as an implicit argument to all the member functions. Ex: class ABC { int a; .. . }; The private variable a can be used directly inside a member function , like a=123; we can use the following statement to do the same job. this->a=123; when a binary operator is overloaded using a member function , we pass only one argument to the function. the other argument is implicitly passed using the pointer this. one important application of the pointer this is to return the object it points to. Ex: return *this; inside a member function will return the object that invoked the function. this statement assumes importance when we want to compare two or more objects inside a member function and return the invoking object as a result. Ex: //write a program to demonstrate this pointer class person { char name[20]; float age; public: person(char *s, float a) { strcpy(name,s); age=a; }

Jyothi

Page 19

person &person : : greater(person & x) { if ( x.age>age) return x; else return *this; } void display() { Cout<<name:=<<name<<\nage=<<age; } }; int main() { person p1(jyo,42.44),p2(jyothi,23.22), p3(jj,53.21); person p=p1.greater(p3); cout<<elder person is\n; p.display(); p=p1.greater(p2); cout<<elder person is\n; p.display(); return 0; }

Friend function
A non-member function cannot have an access to the private data of a class. In situations where we would like two classes to share a particular function we could declare that function as a friend function. it is possible to grant the non member function access to the private members of the class using a keyword friend. Declaration of a friend: To declare a friend function, include its prototype within the class, preceding it with the keyword friend. Syntax: friend return-type function_name(arguments); Characteristics of friend functions: 1. It is not in the scope of the class to which it has been declared as a friend. This means it is not a member of the class in which it is declared. 2. It cannot be called by using the object of the class because it does not belongs to any class. 3. It cannot access the member function directly 4. It can be declared in the private or public section. 5. Usually it has objects as arguments. //write a program to demo friend function #include<iostream.h> #include<conio.h> class book { private:
Jyothi Page 20

int x,y; public: book(int a,int b) { x=a; y=b; } void showdata() { cout<<" \n value of x :"<<x<<endl; cout<<"\n value of y:"<<y<<endl; } friend book operator ++(book &abc); friend book operator --(book &abc); }; book operator ++(book &abc) { abc.x++; abc.y++; return abc; } book operator -(book &abc) { abc.x--; abc.y--; return abc; } void main() { book b1(5,25); clrscr(); b1.showdata(); ++b1; b1.showdata(); --b1; b1.showdata(); getch(); }

Dynamic memory allocation and deallocation


C++ provides 2 special memory management operators which are used to allocate memory to the variable and releases memory from the variable dynamically. they are 1. new operator 2. delete operator. new operator: it is a memory management operator provided by C++ i.e., used to allocate requested size of memory to a pointer. It allocates single block and several blocks of memory at a time to a variable.
Jyothi Page 21

delete operator: is a memory management operator provided by C++ i.e., used to release the memory from a pointer Using new operator with different styles: a new operator is used to create objects of any type. Syntax-1: data type *ptr=new data type; The above syntax is allocate memory dynamically for ordinary type variables. ex: int *ptr=new int; Syntax-2: data type *ptr=new data type[size]; The above syntax is used to allocate memory dynamically for array type variables ex: int *ptr=new int[size of(int)*10]; the above declaration allocates memory to be allocated for single dimensional array type variable called ptr. syntax-3: data type *ptr[size 2]=new data type[size1][size2]; The above syntax is required to for allocating memory dynamically for 2 dimensional arrays. Ex: int *ptr[sizeof(int) *2]=new int [sizeof(int)][2*size of(int)]; //program to demo a new and delete operator with single dimensional arrays for n integers. void main( ) { int n; cout<<enter no of elements\n; cin>>n; int *ptr=new int[n]; cout<<enter <<n<<elements\n; int i; for(i=0;i<=n-1;i++) { cin>>ptr[i]; } cout<<elements are\n; for(i=0;i<=n-1;i++) { cout<<\t<<ptr[i]; } delete[ ] ptr; getch( ); }

Jyothi

Page 22

Exception Handling
an exception is an error or an unexpected event. the exception handler is set of code that executes when an exception occurs. generally exceptions occur due to logic failure or h/w problems. Exceptions are divided into two types 1. synchronous exception 2. Asynchronous exception. Synchronous error raise due to logic failure of the program. Ex: out of range error, out of boundaries, invalid data type errors etc. Asynchronous error raise due to h/w problems are known as asynchronous errors. ex: Keyboard failure, mouse failure etc. C++ provides a mechanism called exception handling that handles only synchronous exceptions. Exception handling is one of the most recently added features, so it may not be supported by much earlier versions of c++ compilers. the main purpose of exception handling mechanism is to detect and report an exceptional circumstances, so that an appropriate action can be taken. Exception handling mechanism: The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program using 3 keywords namely try, throw, catch to handle exception. so the exception handler consists of 3 blocks 1. try block handler 2. throw block handler 3. catch block. The try, catch, and throw Statements try { // it contains a function that causes an exception throw Exception() } catch(Exception e) { //it caontains the code that handles the exception } The code after the try clause is the guarded section of code. The throw expression throws (raises) an exception. The code block after the catch clause is the exception handler, and catches (handles) the exception thrown by the throw expression. //program to demo exception handling void main() { int a,b,c; cout<<enter the values of a and b\n;
Jyothi Page 23

cin>>a>>b; try { if(b==0) throw b; c=a/b; cout<<value of a/b=<<c<<endl; } catch(int i) { cout<<Exception divided by zero caught<<endl; } } o/p: enter the values of a and b 20 0 Exception divided by zero caught ******************************

Jyothi

Page 24

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