<<

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT – I – PROGRAMMING IN and C++ SBSA1102

PROGRAMMING IN C and C++

UNIT – I

BASIC OF C PROGRAMMING

INTRODUCTION TO C

• C is a procedural programming language. • It was initially developed by Dennis Ritchie in the year 1972. • It was mainly developed as a system programming language to an operating system.

FEATURES OF C

• It is a robust language with rich of built-in functions and operators that can be used to write any complex program. • The C compiler combines the capabilities of an assembly language with features of a high-level language. • Programs Written in C are efficient and fast. This is due to its variety of and powerful operators. • It is many time faster than BASIC. • C is highly portable this means that programs once written can be run on another machines with little or no modification. • Another important feature of C program, is its ability to extend itself. • A C program is basically a collection of functions that are supported by C library. We can also create our own function and add it to C library. • C language is the most widely used language in operating systems and development today.

STRUCTURE OF A C PROGRAM

HEADER FILE # include

Main ( ) int main( ) {

Variable Declaration int a = 10;

Body of program printf (“%”, a);

Return return 0; }

HEADER FILE

• The first and foremost component is the inclusion of header file. It is a file with extension .h • Example : stdio.h  define input and output function • Syntax : # include

MAIN METHOD

• The next part of C program is to declare the main ( ) function • Syntax : int main ( ) { } VARIABLE DECLARATION

• The next part of any C program is variable declaration. • It refers to variables that are to be used in function • Syntax : int main ( ) { int a ; ….. BODY OF THE PROGRAM

• It refers to the operation that are performed in functions • Syntax: Int main ( ) { Int a; Printf (“%d”, a); ….

RETURN STATEMENT

• This is last part in any C program in return statement • It refers to returning of statement of values from function • Syntax: C - DATA TYPES

• The data-type in a programming language is the collection of data with values having fixed meaning as well as characteristics. Some of them are an , floating point, , etc. • A data-type in C programming is a set of values and is determined to act on those values. • C provides various types of data-types which allow the programmer to select the appropriate type for the variable to set its value.

C DATA TYPES ARE USED TO

• Identify the type of a variable when it declared. • Identify the type of the return value of a function. • Identify the type of a parameter expected by a function.

C PROVIDES THREE TYPES OF DATA TYPES

• Primary(Built-in) Data Types:

void, int, char, double and float.

• Derived Data Types:

Array, References, and Pointers.

• User Defined Data Types:

Structure, Union, and Enumeration.

PRIMARY (BUILT-IN) DATA TYPES

DERIVED DATA TYPES

USER DEFINED DATA TYPES

• C allows the feature called type definition which allows programmers to define their identifier that would represent an existing data type. There are three such types:

C – TOKENS

• The compiler breaks a program into the smallest possible units and proceeds to the various stages of the compilation, which is called token.

IDENTIFIERS

• Identifiers are names given to different names given to entities such as constants, variables, structures, functions etc.

Rules for Identifiers

• An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters & digits) and underscore( _ ) symbol. • Identifier names must be unique • The first character must be an alphabet or underscore. • You cannot use a keyword as identifiers. • Only first thirty-one (31) characters are significant. • Must not contain white spaces. • Identifiers are case-sensitive. KEYWORDS

• The C Keywords must be in your information because you cannot use them as a variable name.

CONSTANTS

• Constants are like a variable, except that their value never changes during execution once defined. • C Constants is the most fundamental and essential part of the C programming language. • Constants in C are the fixed values that are used in a program, and its value remains the same during the entire execution of the program. • Constants are also called literals. • Constants can be any of the data types. • It is considered best practice to define constants using only upper-case names.

CONSTANTS TYPES

• Constants are categorized into two basic types, and each of these types has its subtypes/categories.

OPERATORS

• C operators are symbols that are used to perform mathematical or logical manipulations. • The C programming language is rich with built-in operators. • Operators take part in a program for manipulating data and variables and form a part of the mathematical or logical expressions.

TYPES

C - INPUT AND OUTPUT

• Input means to provide the program with some data to be used in the program • Output means to display data on screen or write the data to a printer or a file. • C programming language provides many built-in functions to read any given input and to display data on screen when there is a need to output the result. scanf() and printf() functions

• The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf(), which are used to display output on screen and to take input from user respectively.

getchar() & putchar() functions

• The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. • The putchar() function displays the character passed to it on the screen and returns the same character. This function too displays only a single character at a time.

gets() & puts() functions

• The gets() function reads a line from stdin (standard input) into the buffer pointed to by str pointer, until either a terminating newline or EOF (end of file) occurs. • The puts() function writes the string str and a trailing newline to stdout (standard output)

Difference between scanf() and gets()

• The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as character too. DECISION MAKING IN C

• Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met. • C language handles decision-making by supporting the following statements, o if statement o switch statement o conditional operator statement (? : operator) o goto statement

Decision making with if statement

• The if statement may be implemented in different forms depending on the complexity of conditions to be tested. • The different forms are, o Simple if statement o if....else statement o Nested if. .. else statement o Using else if statement

Simple if statement

• The general form of a simple if statement is, • If the expression returns true, then the statement-inside will be executed, otherwise statement-inside is skipped and only the statement-outside is executed.

if...else statement

• The general form of a simple if...else statement is, • If the expression is true, the statement-block1 is executed, else statement-block1 is skipped and statement-block2 is executed.

Nested if. .. else statement

• The general form of a nested if. else statement is,

• if expression is false then statement-block3 will be executed, otherwise the execution continues and enters inside the first if to perform the check for the next if block, where if expression 1 is true the statement-block1 is executed otherwise statement-block2 is executed.

else if ladder

• The expression is tested from the top(of the ladder) downwards. As soon as a true condition is found, the statement associated with it is executed.

SWITCH STATEMENT IN C

• Switch statement is a control statement that allows us to choose only one choice among the many given choices. • The expression in switch evaluates to return an integral value, which is then compared to the values present in different cases. • It executes that block of code which matches the case value. • If there is no match, then default block is executed (if present).

• The general form of switch statement is,

Rules for using switch statement

• The expression (after switch keyword) must yield an integer value i.e the expression should be an integer or a variable or an expression that evaluates to an integer. • The case label values must be unique. • The case label must end with a colon (:) • The next line, after the case statement, can be any valid C statement. • break statements are used to exit the switch block. It isn't necessary to use break after each block, but if you do not use it, then all the consecutive blocks of code will get executed after the matching block. EXAMPLE

Difference between switch and if

• if statements can evaluate float conditions. switch statements cannot evaluate float conditions. • if statement can evaluate relational operators. switch statement cannot evaluate relational operators i.e they are not allowed in switch statement. LOOPING STATEMENTS IN C

• In any programming language including C, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

• As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the execution breaks out of the loop. • After the loop is successfully executed the execution again starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.

TYPES OF LOOP

• There are 3 types of Loop in C language, namely: o while loop o for loop o do while loop

The for loop is executed as follows:

• It first evaluates the initialization code. • Then it checks the condition expression. • If it is true, it executes the for-loop body. • Then it evaluate the increment/decrement condition and again follows from step 2. • When the condition expression becomes false, it exits the loop.

Jumping Out of Loops

• Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true. This is known as jumping out of loop. • break statement o When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.

• continue statement o It causes the control to go directly to the test-condition and then continue the loop process. o On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.

FUNCTIONS IN C

• A function is a block of code that performs a particular task • C language provides an approach in which you can declare and define a group of statements once in the form of a function and it can be called and used whenever required. • C functions can be classified into two categories, o Library functions o User-defined functions

• Library functions are those functions which are already defined in C library, example printf(), scanf(), strcat() etc. We just need to include appropriate header files to use these functions. These are already declared and defined in C libraries. • User-defined functions on the other hand, are those functions which are defined by the user at the time of writing program. These functions are made for code reusability and for saving time and space.

BENEFITS OF USING FUNCTIONS

• It provides modularity to your program's structure. • It makes your code reusable. You just have to call the function by its name to use it, wherever required. • In case of large programs with thousands of code lines, debugging and editing becomes easier if you use functions. • It makes the program more readable and easy to understand.

FUNCTION DECLARATION

• Like any variable or an array, a function must also be declared before its used. • Function declaration informs the compiler about the function name, parameters is accept, and its return type. • The actual body of the function can be defined separately. It's also called as Function Prototyping. • Function declaration consists of 4 parts. o returntype o function name o parameter list o terminating semicolon returntype

• When a function is declared to perform some sort of calculation or any operation and is expected to provide with some result at the end, in such cases, a return statement is added at the end of function body. • Return type specifies the type of value (int, float, char, double) that function is expected to return to the program which called the function.

functionName

• Function name is an identifier and it specifies the name of the function. • The function name is any valid C identifier and therefore must follow the same naming rules like other variables in C language.

parameter list

• The parameter list declares the type and number of arguments that the function expects when it is called. • Also, the parameters in the parameter list receives the argument values when the function is called. They are often referred as formal parameters. Example

FUNCTION DEFINITION

• The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as function header and the statement(s) within curly braces is called function body.

Syntax

Note: While defining a function, there is no semicolon(;) after the parenthesis in the function header, unlike while declaring the function or calling the function. functionbody

• The function body contains the declarations and the statements(algorithm) necessary for performing the required task. • The body is enclosed within curly braces { ... } and consists of three parts. o local variable declaration (if required). o function statements to perform the task inside the function. o a return statement to return the result evaluated by the function (if return type is void, then no return statement is required).

CALLING A FUNCTION

• When a function is called, control of the program gets transferred to the function.

Syntax

• In the example above, the statement multiply(i, j); inside the main() function is function call.

PASSING ARGUMENTS TO A FUNCTION

• Arguments are the values specified during the function call, for which the formal parameters are declared while defining the function.

RETURNING A VALUE FROM FUNCTION

• A function may or may not return a result. But if it does, we must use the return statement to output the result. • return statement also ends the function execution, hence it must be the last statement of any function. • If you write any statement after the return statement, it won't be executed. • The datatype of the value returned using the return statement should be same as the return type mentioned at function declaration and definition. If any of it mismatches, you will get compilation error.

TYPE OF USER-DEFINED FUNCTIONS IN C

• There can be 4 different types of user-defined functions, they are: o Function with no arguments and no return value o Function with no arguments and a return value o Function with arguments and no return value o Function with arguments and a return value Function with no arguments and no return value

• Such functions can either be used to display information or they are completely dependent on user inputs.

EXAMPLE

Function with no arguments and a return value

• We have modified the above example to make the function greatNum() return the number which is greater amongst the 2 input numbers.

EXAMPLE

Function with arguments and no return value

• We are using the same function as example again and again, to demonstrate that to solve a problem there can be many different ways. • This time, we have modified the above example to make the function greatNum() take two int values as arguments, but it will not be returning anything

EXAMPLE

Function with arguments and a return value

• This is the best type, as this makes the function completely independent of inputs and outputs, and only the logic is defined inside the function body.

EXAMPLE

NESTING OF FUNCTIONS

• C language also allows nesting of functions i.e to use/call one function inside another function's body.

RECURSION

• Recursion is a special way of nesting functions, where a function calls itself inside it.

Syntax

TYPES OF FUNCTION CALLS IN C

• Functions are called by their names • If the function does not have any arguments, then to call a function you can directly use its name. • Functions with arguments, we can call a function in two different ways, based on how we specify the arguments, and these two ways are: o Call by Value o Call by Reference

Call by Value

• Calling a function by value means, we pass the values of the arguments which are stored or copied into the formal parameters of the function. • Hence, the original values are unchanged only the parameters inside the function changes.

Call by Reference

• In call by reference we pass the address(reference) of a variable as argument to any function. • When we pass the address of any variable as argument, then the function will have access to our variable, as it now knows where it is stored and hence can easily update its value.

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT – II – PROGRAMMING IN C and C++ SBSA1102

UNIT 2

ARRAYS, STRINGS AND STRUCTURES

ARRAYS IN C

• In C language, arrays are referred to as structured data types. • An array is a group (or collection) of same data types. For example an int array holds the elements of int types while a float array holds the elements of float types. • An array is defined as finite ordered collection of homogenous data, stored in contiguous memory locations. • Finite means data range must be defined. • Ordered means data must be stored in continuous memory addresses. • Homogenous means data must be of similar data type.

DECLARING AN ARRAY

• Like any other variable, arrays must be declared before they are used. General form of array declaration is,

SYNTAX

• Here int is the data type, arr is the name of the array and 10 is the size of array. • It means array arr can only contain 10 elements of int type.

INITIALIZATION OF ARRAY

• After an array is declared it must be initialized. Otherwise, it will contain garbage value (any random value). • An array can be initialized at either compile time or at runtime.

COMPILE TIME ARRAY INITIALIZATION

• Compile time initialization of array elements is same as ordinary variable initialization. • One important thing to remember is that when you will give more initializer (array elements) than the declared array size than the compiler will give an error. • The general form of initialization of array is,

SYNTAX

EXAMPLE

RUNTIME ARRAY INITIALIZATION

• An array can also be initialized at runtime using scanf() function. • This approach is usually used for initializing large arrays, or to initialize arrays with user specified values.

EXAMPLE

TYPES OF ARRAYS

• One/Single Dimensional Array • Two/Multi-dimensional Array

TWO DIMENSIONAL – 2D ARRAY

• The simplest form of a multidimensional array is the two-dimensional array. Both the row's and column's index begins from 0.

SYNTAX

EXAMPLE

INITIALIZATION OF 2D ARRAY

• There are two ways to initialize a two Dimensional arrays during declaration.

Why we need Array in C Programming?

• Consider a scenario where you need to find out the average of 100 integer numbers entered by user. In C, you have two ways to do this: 1) Define 100 variables with int data type and then perform 100 scanf() operations to store the entered values in the variables and then at last calculate the average of them. 2) Have a single integer array to store all the values, loop the array to store all the entered values in array and later calculate the average.

How to declare Array in C?

ONE DIMENSIONAL ARRAY

Why do we need arrays?

• We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. • The idea of an array is to represent many instances in one variable.

ADVANTAGES OF AN ARRAY IN C

• Random access of elements using array index. • Use of less line of code as it creates a single array of multiple elements. • Easy access to all the elements. • Traversal through the array becomes easy using a single loop. • Sorting becomes easy as it can be accomplished by writing less line of code.

DISADVANTAGES OF AN ARRAY IN C

• Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic. • Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation. ARRAYS AS FUNCTION ARGUMENTS

PASSING A SINGLE ARRAY ELEMENT TO A FUNCTION

PASSING A COMPLETE ONE-DIMENSIONAL ARRAY TO A FUNCTION

PASSING A MULTI-DIMENSIONAL ARRAY TO A FUNCTION

C - STRINGS

• String is a sequence of characters that is treated as a single data item and terminated by null character '\0'. • C language does not support strings as a data type. • A string is actually one-dimensional array of characters in C language. • These are often used to create meaningful and readable programs.

DECLARING AND INITIALIZING A STRING VARIABLES

• There are different ways to initialize a character array variable.

SYNTAX

NOTE: Remember that when you initialize a character array by listing all of its characters separately then you must supply the '\0' character explicitly. STRING INPUT AND OUTPUT

• Input function scanf() can be used with %s format specifier to read a string input from the terminal.

• Another method to read character string with white spaces from terminal is by using the gets() function.

STRING HANDLING FUNCTIONS

• C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. • These functions are packaged in string.h library. • Hence, you must include string.h header file in your programs to use these functions.

C - STRUCTURES

• Structure is a user-defined datatype in C language which allows us to combine data of different types together. • Structure helps to construct a which is more meaningful. • It is somewhat similar to an Array, but an array holds data of similar type only. • But structure on the other hand, can store data of any type, which is practical more useful.

DEFINING A STRUCTURE

• struct keyword is used to define a structure. • struct defines a new data type which is a collection of primary and derived datatypes.

• Member variables are nothing but int, float, char….. • NOTE: The closing curly brace in the structure type declaration must be followed by a Semicolon (;)

EXAMPLE

• Here struct Student declares a structure to hold the details of a student which consists of 4 data fields, namely name, age, branch and gender. • These fields are called structure elements or members. • Each member can have different datatype, like in this case, name is an array of char type and age is of int type etc. • Student is the name of the structure and is called as the structure tag.

DECLARING STRUCTURE VARIABLES

• It is possible to declare variables of a structure, either along with structure definition or after the structure is defined. • Structure variable declaration is similar to the declaration of any normal variable of any other datatype. • Structure variables can be declared in following two ways: o Declaring Structure variables separately o Declaring Structure variables with structure definition

ACCESSING STRUCTURE MEMBERS

• Structure members can be accessed and assigned values in a number of ways. • Structure members have no meaning individually without the structure. • In order to assign a value to any structure member, the member name must be linked with the structure variable using a dot . operator also called period or member access operator EXAMPLE

STRUCTURE INITIALIZATION

ARRAY OF STRUCTURE

• We can also declare an array of structure variables. in which each element of the array will represent a structure variable. • Example : struct employee emp[5];

EXAMPLE

• The below program defines an array emp of size 5. • Each element of the array emp is of type Employee.

NESTED STRUCTURES

• Nesting of structures, is also permitted in C language. • Nested structures means, that one structure has another stucture as member variable.

STRUCTURE AS FUNCTION ARGUMENTS

• We can pass a structure as a function argument just like we pass any other variable or an array as a function argument. EXAMPLE

in C

• typedef is a keyword used in C language to assign alternative names to existing datatypes. • Its mostly used with user defined datatypes, when names of the datatypes become slightly complicated to use in programs. • Following is the general syntax for using typedef

APPLICATION OF typedef

• typedef can be used to give a name to user defined data type as well.

SYNTAX

STRUCTURE DEFINITION USING typedef

C – UNIONS

• Unions are conceptually similar to structures. • The syntax to declare/define a union is also similar to that of a structure. • The only differences is in terms of storage. • In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member.

• This implies that although a union may contain many members of different types, it cannot handle all the members at the same time. • A union is declared using the union keyword.

• This declares a variable It1 of type union item. This union contains three members each with a different data type. ACCESSING A UNION MEMBER IN C

EXAMPLE

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT – III – PROGRAMMING IN C and C++ SBSA1102

UNIT III

POINTERS AND FILE PROCESSING

POINTERS

• A Pointer in C language is a variable which holds the address of another variable of same data type. • Pointers are used to access memory and manipulate the address. • Pointers are one of the most distinct and exciting features of C language. • It provides power and flexibility to the language.

ADDRESS IN C

• Whenever a variable is defined in C language, a memory location is assigned for it, in which it's value will be stored using the & symbol. • If var is the name of the variable, then &var will give it's address.

EXAMPLE

• You must have also seen in the function scanf(), we mention &var to take user input for any variable var.

• This is used to store the user inputted value to the address of the variable var. CONCEPT OF POINTERS

• Whenever a variable is declared in a program, system allocates a location i.e an address to that variable in the memory, to hold the assigned value. • This location has its own address number • Let us assume that system has allocated memory location 80F for a variable a. (above mentioned)

POINTER VARIABLES

• The memory addresses are also just numbers, they can also be assigned to some other variable. • The variables which are used to hold memory addresses are called Pointer variables. • A pointer variable is therefore nothing but a variable which holds an address of some other variable.

BENEFITS OF USING POINTERS

• Pointers are more efficient in handling Arrays and Structures. • Pointers allow references to function and thereby help in passing of function as arguments to other functions. • It reduces length of the program and its execution time as well. • It allows C language to support Dynamic Memory management. DECLARING, INITIALIZING AND USING A POINTER VARIABLE IN C

DECLARATION OF C POINTER

Syntax

• Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. • pointer works with all data types, but is not often used.

Examples

INITIALIZATION OF C POINTER VARIABLE

• Pointer Initialization is the process of assigning address of a variable to a pointer variable. • Pointer variable can only contain address of a variable of the same data type. • In C language address operator & is used to determine the address of a variable. • The & (immediately preceding a variable name) returns the address of the variable associated with it.

NULL Pointer

• The variable's address to assign to a pointer variable while declaration, it is recommended to assign a NULL value to your pointer variable. • A pointer which is assigned a NULL value is called a NULL pointer.

EXAMPLE FOR POINTERS

#include

int main() { int i = 10; // normal integer variable storing value 10 int *a; // since '*' is used, hence its a pointer variable a = &i; /* below, address of variable 'i', which is stored by a pointer variable 'a' is displayed */ printf("Address of variable i is %u\n", a); /* below, '*a' is read as 'value at a' which is 10 */ printf("Value at the address, which is stored by pointer variable a is %d\n", *a); return 0; }

Output

Address of variable i is 2686728 (The address may vary) Value at an address, which is stored by pointer variable a is 10 POINTERS USING ARRAYS

Example 1

#include const int MAX = 3; int main () {

int var[] = {10, 100, 200}; int i;

for (i = 0; i < MAX; i++) { printf("Value of var[%d] = %d\n", i, var[i] ); }

return 0; }

Output

Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200

Example 2

#include const int MAX = 4; int main () {

char *names[] = { "ABCD", "EFGH", "IJKL", "MNOP" };

int i = 0;

for ( i = 0; i < MAX; i++) { printf("Value of names[%d] = %s\n", i, names[i] ); }

return 0; } Output

Value of names[0] = ABCD Value of names[1] = EFGH Value of names[2] = IJKL Value of names[3] = MNOP

POINTERS USING STRUCTURES Example

Output

POINTERS USING FUNCTIONS

Example 1

#include void salaryhike(int *var, int b) { *var = *var+b; } int main() { int salary=0, bonus=0; printf("Enter the employee current salary:"); scanf("%d", &salary); printf("Enter bonus:"); scanf("%d", &bonus); salaryhike(&salary, bonus); printf("Final salary: %d", salary); return 0; }

Output

Enter the employee current salary:10000 Enter bonus:2000 Final salary: 12000

Example 2

Swapping two numbers using Pointers

• This is one of the most popular example that shows how to swap numbers using call by reference.

#include void swapnum(int *num1, int *num2) { int tempnum;

tempnum = *num1; *num1 = *num2; *num2 = tempnum; } int main( ) { int v1 = 11, v2 = 77 ; printf("Before swapping:"); printf("\nValue of v1 is: %d", v1); printf("\nValue of v2 is: %d", v2);

/*calling swap function*/ swapnum( &v1, &v2 );

printf("\nAfter swapping:"); printf("\nValue of v1 is: %d", v1); printf("\nValue of v2 is: %d", v2); }

Output

Before swapping: Value of v1 is: 11 Value of v2 is: 77

After swapping: Value of v1 is: 77 Value of v2 is: 11 DYNAMIC MEMORY ALLOCATION

• The process of allocating memory at runtime is known as dynamic memory allocation. • Library routines known as memory management functions are used for allocating and freeing memory during execution of a program. • These functions are defined in stdlib.h header file. • Dynamic memory allocation in c language is possible by 4 functions o malloc() o calloc() o realloc() o free()

OR

MEMORY ALLOCATION PROCESS

• Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in a memory area called Stack • The memory space between these two region is known as Heap area. • This region is used for dynamic memory allocation during execution of the program. • The size of heap keep changing.

DIFFERENCE BETWEEN static memory allocation and dynamic memory allocation

DIFFRENCE BETWEEN malloc() and calloc() malloc() function in C

• The malloc() function allocates single block of requested memory. • It doesn't initialize memory at execution time, so it has garbage value initially. • It returns NULL if memory is not sufficient.

Syntax of malloc()

ptr = (cast-type*) malloc (-size)

Example

Output

calloc() function in C

• The calloc() function allocates multiple block of requested memory. • It initially initialize all to zero. • It returns NULL if memory is not sufficient.

Syntax

ptr = (cast-type*) calloc (number, byte-size)

Example

Output

realloc() function in C

• If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Syntax

ptr = realloc (ptr, new-size)

Example

Output

free() function in C

• The memory occupied by malloc() or calloc() functions must be released by calling free() function. • Otherwise, it will consume memory until program exit.

Syntax

free (ptr)

SMART POINTER

• Smart Pointer is used to manage the lifetimes of dynamically allocated objects. • They ensure proper destruction of dynamically allocated objects. • Smart pointers are defined in the memory header file. • Smart pointers are built-in pointers, we don't have to worry about deleting them, they are automatically deleted. • By using the delete keyword we can delete the memory allocated

Example STORAGE CLASSES IN C

• In C language, each variable has a storage class which decides the following things: • Scope - where the value of the variable would be available inside a program. • Default initial value - if we do not explicitly initialize that variable, what will be its default initial value. • Lifetime of that variable - for how long wills that variable exist.

Storage classes are most often used in C programming

• Automatic variables • External variables • Static variables • Register variables

AUTOMATIC VARIABLES

Keyword : auto

• Scope: Variable defined with auto storage class are local to the function block inside which they are defined. • Default Initial Value: Any random value i.e garbage value. • Lifetime: Till the end of the function/method block where the variable is defined

AUTOMATIC VARIABLES

• A variable declared inside a function without any storage class specification, is by default an automatic variable. • They are created when a function is called and are destroyed automatically when the function's execution is completed. • Automatic variables can also be called local variables because they are local to a function. • By default they are assigned garbage value by the compiler Example

#include void main() { int detail; // or auto int details; //Both are same }

EXTERNAL OR GLOBAL VARIABLE

Keyword : extern

• Scope: Global i.e everywhere in the program. These variables are not bound by any function, they are available everywhere. • Default initial value: 0(zero). • Lifetime: Till the program doesn't finish its execution, you can access global variables.

GLOBAL VARIABLE

• A variable that is declared outside any function is a Global Variable. • Global variables remain available throughout the program execution. • By default, initial value of the Global variable is 0 (zero).

Example

#include int number; // global variable void main() { number = 10; printf("I am in main function. My value is %d\n", number); fun1(); //function calling, discussed in next topic fun2(); //function calling, discussed in next topic } /* This is function 1 */ fun1() { number = 20; printf("I am in function fun1. My value is %d", number); } /* This is function 1 */ fun2() { printf("\nI am in function fun2. My value is %d", number); } Output

I am in function main. My value is 10 I am in function fun1. My value is 20 I am in function fun2. My value is 20 extern KEYWORD

• The extern keyword is used with a variable to inform the compiler that this variable is declared somewhere else. • The extern declaration does not allocate storage for variables.

Problem when extern is not used int main() { a = 10; //Error: cannot find definition of variable 'a' printf("%d", a); } Example : using extern in same file int main() { extern int x; //informs the compiler that it is defined somewhere else x = 10; printf("%d", x); } int x; //Global variable x

STATIC VARIABLES

Keyword : static

• Scope: Local to the block in which the variable is defined • Default initial value: 0(Zero). • Lifetime: Till the whole program doesn't finish its execution

STATIC VARIABLE

• A static variable tells the compiler to persist/save the variable until the end of program. • Instead of creating and destroying a variable every time when it comes into and goes out of scope, static variable is initialized only once and remains into existence till the end of the program. • A static variable can either be internal or external depending upon the place of declaration. • Scope of internal static variable remains inside the function in which it is defined. • External static variables remain restricted to scope of file in which they are declared

Example

#include void test(); //Function declaration (discussed in next topic) int main() { test(); test(); test(); } void test() { static int a = 0; //a static variable a = a + 1; printf("%d\t",a);

} Output

1 2 3

REGISTER VARIABLE

• Scope: Local to the function in which it is declared. • Default initial value: Any random value i.e garbage value • Lifetime: Till the end of function/method block, in which the variable is defined.

Keyword : register

Syntax

register int number;

REGISTER VARIABLE

• Register variables inform the compiler to store the variable in CPU register instead of memory. • Register variables have faster accessibility than a normal variable.

FILE HANDLING IN C

• In any programming language it is vital to learn file handling techniques. • Many applications will at some point involve accessing folders and files on the hard drive. • In C, a is associated with a file. • Special functions have been designed for handling file operations. • The header file stdio.h is required for using these functions

Opening a file

• The function fopen() for opening a file. • Once this is done one can read or write to the file using the fread() or fwrite() functions • The fclose() function is used to explicitly close any opened file.

SYNTAX

FILE*fopen(“filename” , “mode”); EXAMPLE

#include main () { FILE *fp; fp = fopen("data.txt", "r"); if (fp == NULL) { printf("File does not exist, please check!\n"); } fclose(fp); }

fopen()

• This function accepts two arguments as strings. • The first argument denotes the name of the file to be opened and the second signifies the mode in which the file is to be opened. • The second argument can be any of the following:

fclose()

• The fclose() function is used for closing opened files. • The only argument it accepts is the file pointer. • If a program terminates, it automatically closes all opened files. • fclose(p1); fscanf() and fprintf()

• The functions fprintf() and fscanf() are similar to printf() and scanf() except that these functions operate on files and require one additional and first argument to be a file pointer

fprintf()

Example

fscanf()

EXAMPLE

#include main () { FILE *fp; float total; fp = fopen("data.txt", "w+"); if (fp == NULL) { printf("data.txt does not exist, please check!\n"); exit (1); } fprintf(fp, 100); fscanf(fp, "%f", &total); fclose(fp); printf("Value of total is %f\n", total); } getc() and putc()

• The functions getc() and putc() are equivalent to getchar() and putchar() functions • Input and Output, except that these functions require an argument which is the file pointer. • Function getc() reads a single character from the file which has previously been opened using a function like fopen(). • Function putc() does the opposite, it writes a character to the file identified by its second argument. • The format of both functions is as follows getc(in_file); putc(c, out_file);

getc() putc()

EXAMPLE

Using getc() and putc()

#include main () { char in_file[30], out_file[30]; FILE *fpin, *fpout; int c; printf("This program copies the source file to the destination file \n\n"); printf("Enter name of the source file :"); scanf("%30s", in_file); printf("Enter name of the destination file :"); scanf("%30s", out_file); if((fpin=fopen(in_file, "r")) == NULL) printf("Error could not open source file for reading\n"); else if ((fpout=fopen(out_file, "w")) == NULL) printf("Error could not open destination file for reading\n"); else { while((c =getc(fpin)) != EOF) putc(c, fpout); printf("Destination file has been copied\n"); } } BINARY STREAM INPUT AND OUTPUT

• The functions fread() and fwrite() are a somwhat complex file handling functions used for reading or writing chunks of data containing NULL characters ('\0') terminating strings • The function prototype of fread() and fwrite() is as below

size_t fread (void *ptr, size_t sz, size_t n, FILE *fp)

size_t fwrite (const void *ptr, size_t sz, size_t n, FILE *fp);

• The return type of fread() is size_t which is the number of items read. • Function fread() reads it as a stream of bytes and advances the file pointer by the number of bytes read. • Function fwrite() works similarly, it writes n objects of sz bytes long from a location pointed to by ptr, to a file pointed to by fp, and returns the number of items written to fp

Description for fread() and fwrite() declaration (above mentioned) fread()

Example for fread()

fwrite()

Example for fwrite()

EXAMPLE using fread() and fwrite() functions

#include #define MAX_SIZE 1024 main () { FILE *fp, *gp; char buf[MAX_SIZE]; int i, total = 0; if ((fp = fopen("data1.txt", "r") ) == NULL) printf("Error in data1.txt file \n"); else if ((gp=fopen("data2.txt", "w")) == NULL) printf("Error in data2.txt file \n"); else { while(i=fread(buf, 1, MAX_SIZE, fp)) { fwrite(buf, 1, MAX_SIZE, gp); total +=i; } printf("Total is %d\n", total); } fclose(fp); fclose(gp); } ftell()

• Functions ftell() and fseek() are important in a program performing file manipulations. • Function ftell() returns the current position of the file pointer in a stream. • The return value is 0 or a positive integer indicating the byte offset from the beginning of an open file • A return value of -1 indicates an error. • Prototype of this function is as shown below : long int ftell(FILE *fp);

fseek()

• This function positions the next I/O operation on an open stream to a new position relative to the current position. int fseek(FILE *fp, long int offset, int origin); • Here fp is the file pointer of the stream on which I/O operations are carried on, offset is the number of bytes to skip over • The offset can be either positive or negative, denting forward or backward movement in the file.

EXAMPLE

#include #include char buffer[11]; int position; main () { FILE *file_ptr; int num; if ((file_ptr = fopen("test_file", "w+f 10"))== NULL) { printf("Error opening test_file \n"); exit(1); } fputs("1111111111", file_ptr); fputs("2222222222", file_ptr); if ( (position = fseek(file_ptr, 10, SEEK_SET)) != 0) { printf("Error in seek operation: errno \n"); exit(1); } num = 11; fgets(buffer, num, file_ptr); printf("The record is %s\n", buffer); fclose(file_ptr); } OUTPUT : The record is 2222222222.

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT – IV – PROGRAMMING IN C and C++ SBSA1102

UNIT IV

OBJECT ORIENTED PROGRAMMING CONCEPTS

INTRODUCTION TO OBJECT ORIENTED PROGRAM

PROCEDURE ORIENTED PROGRAMMING (POP)

• The high level languages, such as BASIC, COBOL, C, FORTRAN are commonly known as Procedure Oriented Programming. • Using this approach, the problem is viewed in sequence of things to be done, like reading, processing and displaying or printing. To carry out these tasks the function concepts must be used. • This concept basically consists of number of statements and these statements are organized or grouped into functions.

• While developing these functions the programmer must care about the data that is being used in various functions. • A multi-function program, the data must be declared as global, so that data can be accessed by all the functions within the program & each function can also have its own data called local data. • The global data can be accessed anywhere in the program. In large program it is very difficult to identify what data is accessed by which function. In this case we must revise about the external data and as well as the functions that access the global data. At this situation there are so many chances for an error.

OBJECT ORIENTED PROGRAMMING (OOP)

• This programming approach is developed to reduce the some of the drawbacks encountered in the Procedure Oriented Programming Approach. • The Object Oriented Programming approach treats data as critical element and does not allow the data to freely around the program. • It bundles the data more closely to the functions that operate on it; it also protects data from the accidental modification from outside the function. • The object oriented programming approach divides the program into number of entities called objects and builds the data and functions that operates on data around the objects. • The data of an object can only access by the functions associated with that object.

COMPARISON BETWEEN C AND C++ (OOPS)

CONCEPTS OF OOPS

• The general concepts of OOPS comprises the following. o Object o Class o Data abstraction o Inheritance o Polymorphism o Encapsulation o o Message passing

OBJECT

• Concept for understanding : My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we just mean a , you, your friend, me we are the forms of these classes. We have a physical existence while a class is just a logical definition. We are the objects. • Definition : o Objects are the basic unit of OOP. o They are an instance of class, which have data members and uses various member functions to perform tasks.

CLASS

• Concept for understanding : Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its properties and its functions. Like Human Being, having body parts, and performing various actions. • Definition : o It is similar to structures in C language. o Class can also be defined as user defined data type but it also contains functions in it. o So, class is basically a blueprint for object. o It declare & defines what data variables the object will have and what operations can be performed on the class's object.

ABSTRACTION

• Concept for understanding : Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world. We can take our skin as the Abstraction factor in our case, hiding the inside mechanism. • Definition : o Abstraction refers to showing only the essential features of the application and hiding the details. o In C++, classes can provide methods to the outside world to access & use the data variables, keeping the variables hidden from direct access, or classes can even declare everything accessible to everyone, or maybe just to the classes inheriting it. o This can be done using access specifier.

INHERITANCE

• Concept for understanding : Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat, see etc. Male and Female are also classes, but most of the properties and functions are included in HumanBeing, hence they can inherit everything from class HumanBeing using the concept of Inheritance. • Definition : o Inheritance is a way to reuse once written code again and again. The class which is inherited is called the Base class & the class which inherits is called the Derived class. They are also called parent and child class. o So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base class, hence making code reusable. POLYMORPHISM

• Concept for understanding : Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done or by changing the parts using which it is done. Both the ways have different terms for them. If we walk using our hands, and not legs, here we will change the parts used to perform something. Hence this is called Overloading. • Definition : o It is a feature, which lets us create functions with same name but different arguments, which will perform different actions. o That means, functions with same name, but functioning in different ways. Or, it also allows us to redefine a function to provide it with a completely new definition.

ENCAPSULATION or DYNAMIC BINDING

• Concept for understanding : Our Legs are binded to help us walk. Our hands, help us hold things. This binding of the properties to functions is called Encapsulation. • Definition : o It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class.

EXCEPTION HANDLING

• Definition : o Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime.

MESSAGE PASSING

• Definition : o An object oriented program consists of a set of objects that communicate with each other. Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as long as it is alive. BENEFITS OR ADVANTAGES OF OOPS

• The complexity of software can be managed easily. • Data hiding concept help the programmer to build secure programs • Through the class concept we can define the user defined data type • The inheritance concept can be used to eliminate redundant code • The message-passing concept helps the programmer to communicate between different objects. • New data and functions can be easily added whenever necessary. • OOPS ties data elements more closely to the functions that operates on.

STRUCTURE OF C++ PROGRAM

Section 1 : Header File Declaration Section

• Header files used in the program are listed in this section. • Header File provides Prototype declaration for different library functions. • We can also include user define header file. • Basically all preprocessor directives are written in this section. • Include files provides instructions to the compiler to link functions from the system library. Eg: #include #include – Preprocessor Directive iostream.h – Header File Section 2 : Global Declaration Section

• Global Variables are declared here. • Global Declaration may include o Declaring Structure o Declaring Class o Declaring Variable

Section 3 : Class Declaration Section

• Actually this section can be considered as sub section for the global declaration section. • Class declaration and all methods of that class are defined here. • A class is a way to bind and its associated functions together. • It is a user defined datatype. It must be declared at class declaration part.

Section 4 : Main Function

• Each and every C++ program always starts with main function. • This is entry point for all the function. Each and every method is called indirectly through main. • We can create class objects in the main. • Operating system call this function automatically. main( ) { ...... } • Program execution begins at the opening brace and ends at the closing brace. • The closing brace of the main function is the logical and of the program. Section 5 : Method Definition Section

• This is optional section. Generally this method was used in C Programming. • Member function definition describes how the class functions are implemented. • This must be the next part of the C++ program.

OPERATORS

• An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. • Types o Arithmetic Operators o Relational Operators o Logical Operators o Assignment Operators o Increment & decrement Operators o Conditional Operators o Bitwise Operators o Special Operators o Manipulators o Memory allocate / delete Operators

ARITHMETIC OPERATORS

C++ has both unary & binary arithmetic operators.

• Unary operators are those, which operate on a single operand.

• Whereas, binary operators on two operands +, -, *, /, %

Examples for Unary Operators: int x = 10; int y = -x; (The value of x after negation is assigned to y ie. y becomes –10.) int x = 5; int sum = -x; Examples for binary Operators: int x = 16, y=5; x+y = 21; (result of the arithmetic expression), x-y = 11; x*y=80;

/ - Division Operator

Eg: x = 10, y = 3; x/y=3; (The result is truncated, the decimal part is discarded.)

% - Modulo Division

The result is the remainder of the integer division only applicable for integer values. x=11, y = 2 x%y = 1

Relational Operators

• A relational operator is used to make comparison between two expressions.

• All relational operators are binary and require two operands.

• <, <=, >, >=, ++, !=

Relational Expression

Expression1 relational operator Expression2

Expression1 & 2 – may be either constants or variables or arithmetic expression.

Eg: a < b (Compares its left hand side operand with its right hand side operand) 10 = = 15 a != b

An relational expression is always return either zero or 1, after evaluation.

Eg: (a+b) <= (c+d) arithmetic expression

Here relational operator compares the relation between arithmetic expressions. LOGICAL OPERATORS

Logical operators are used when we want to test more than one condition and make decisions.

Eg: (a

An expression of this kind, which combines two or more relational expressions, is termed as a logical expression. Like simple relational expressions, a logical expression also yields a value of one or zero, according to the truth table.

ASSIGNMENT OPERATORS

Assignment operators are used to assign the result of an expression to a variable.

Eg: a = 10; a = a + b; x = y;

Chained Assignment:

Syntax: Variable operator = operand

OP = is called as shorthand assignment operator.

VOP = exp is equivalent to v = v op exp Eg: x+=y;  x = x+y; INCREMENT & DECREMENT OPERATORS

Increment ++, this operator adds 1 to the operand

Decrement --, this operator subtracts 1 from the operand

Both are unary operators

Eg: m = 5; y = ++m; (adds 1 to m value) x = --m; (Subtracts 1 from the value of m)

TYPES

• Pre Increment / Decrement OP • Post Increment / Decrement OP

If the operator precedes the operand, it is called pre increment or pre decrement. Eg: ++i, --i;

If the operator follows the operand, it is called post increment or post decrement. Eg: ++i, --i;

In the pre Increment / Decrement the operand will be altered in value before it is utilized for its purpose within the program.

CONDITIONAL OPERATOR

? :

General Form is

Conditional exp ? exp 1 : exp 2;

Conditional exp - either relational or logical expression is used. Exp1 & exp 2 : are may be either a variable or any statement.

Eg:

(a>b)?a:b;

• Conditional expression is evaluated first.

• If the result is ‘1’ is true, then expression1 is evaluated.

• If the result is zero, then expression2 is evaluated.

Eg: lar = (10>5)?10:5; BITWISE OPERATORS

SPECIAL OPERATORS comma(,) size of operators returns the size the variable occupied from system memory.

Eg: var = sizeof(int)

cout<

x = size of (float);

cout << x; Ans: 4

int y; x = sizeof (y);

cout<

PRECEDENCE OF OPERATORS

MANIPULATORS

• Manipulators are operators used to format the data display. The commonly used manipulators are endl, setw. • endl manipulators o It is used in output statement causes a line feed to be inserted, it has the same effect as using the newline character “\n” in ‘C’ language.

SETW MANIPULATOR

• The setw manipulator is used or specify the field width for printing, the content of the variable. We need to include a header file “iomanip.h” in order to use setw in the program.

OVERLOADING

• If we create two or more members having the same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload o methods, o constructors, and o indexed properties • It is because these members have parameters only. • Types of overloading o Function overloading o Operator overloading

FUNCTION OVERLOADING

• Function refers to a segment that groups code to perform a specific task • In other words two functions can have same name if number and/or type of arguments passed are different • These functions having different number or type or both of parameters are known as overloaded functions • Function Overloading is defined as the process of having two or more function with the same name, but different in parameters is known as function overloading in C++. • In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. • It is only through these differences compiler can differentiate between the functions. • The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for the same action.

INHERITANCE

DEFINITION

• The mechanism of deriving the new class from an old one is called inheritance. • The old class is called as base class and the new class is called as derived class. • SUB CLASS / DERIVED CLASS o The class that inherits properties from another class is called Sub class or Derived Class. • SUPER CLASS / BASE CLASS o The class whose properties are inherited by sub class is called Base Class or Super class.

TYPES OF INHERITANCE

• Single inheritance • Multiple inheritance • Multilevel inheritance • Hierarchical inheritance • Hybrid inheritance

DEFINING DERIVED CLASS

• A derived class is defined by specifying its relationship with the base class in addition to its own details • A Derived class is defined as the class derived from the base class

MODES OF INHERITANCE

• PUBLIC MODE : If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. • PROTECTED MODE : If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class. • PRIVATE MODE : If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class.

// C++ Implementation to show that a derived class // doesn’t inherit access to private data members. // However, it does inherit a full parent object class A { public: int x; protected: int y; private: int z; };

class B : public A { // x is public // y is protected // z is not accessible from B };

class C : protected A { // x is protected // y is protected // z is not accessible from C };

class D : private A // 'private' is default for classes { // x is private // y is private // z is not accessible from D };

SINGLE INHERITANCE

• In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only.

MULTIPLE INHERITANCE

MULTILEVEL INHERITANCE

• In this type of inheritance, a derived class is created from another derived class.

SYNTAX

Class A { //body of base class A }; Class B : public A { //body of intermediate base class B }; Class C : public B { //body of derived class };

EXAMPLE

#include using namespace std;

// base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } };

class fourWheeler: public Vehicle { public: fourWheeler() { cout<<"Objects with 4 wheels are vehicles"<

// sub class derived from two base classes class Car: public fourWheeler { public: car() { cout<<"Car has 4 Wheels"<

// main function int main() { //creating object of sub class will //invoke the constructor of base classes Car obj; return 0; }

HIERARCHICAL INHERITANCE

• In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than one derived class is created from a single base class.

EXAMPLE #include using namespace std;

// base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } }; // first sub class class Car: public Vehicle { …………… }; // second sub class class Bus: public Vehicle { ………… };

// main function int main() { // creating object of sub class will // invoke the constructor of base class Car obj1; Bus obj2; return 0; }

HYBRID (VIRTUAL) INHERITANCE

• Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. • Below image shows the combination of hierarchical and multiple inheritance

EXAMPLE

#include using namespace std;

// base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } };

//base class class Fare { public: Fare() { cout<<"Fare of Vehicle\n"; } };

// first sub class class Car: public Vehicle { ……………. };

// second sub class class Bus: public Vehicle, public Fare { …………. };

// main function int main() { // creating object of sub class will // invoke the constructor of base class Bus obj2; return 0; }

POLYMORPHISM

• The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation, and polymorphism. • Real Life Example Of Polymorphism o Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom, mother or daughter in a home and customer in a market. Here, a single person is behaving differently according to the situations.

There are two types of polymorphism in C++:

Compile time polymorphism: The overloaded functions are invoked by matching the type and number of arguments. This information is available at the compile time and, therefore, compiler selects the appropriate function at the compile time. It is achieved by function overloading and operator overloading which is also known as static binding or early binding. Now, let's consider the case where function name and prototype is same. Run time polymorphism: Run time polymorphism is achieved when the object's method is invoked at the run time instead of compile time. It is achieved by method overriding which is also known as dynamic binding or late binding.

Differences b/w compile time and run time polymorphism.

C++ Runtime Polymorphism Example

VIRTUAL FUNCTION

• A virtual function a member function which is declared within a base class and is re- defined (Overriden) by a derived class. • When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. • When we use the same function name in base and derived classes, the function in the base classes is declared as virtual using keyword ‘virtual’ preceding its normal declaration. • The member function that can be changed at runtime is called virtual function. CHARACTERISTICS

• Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. • They are mainly used to achieve Runtime polymorphism • Functions are declared with a virtual keyword in base class. • The resolving of function call is done at Run-time.

RULES FOR VIRTUAL FUNCTION

• Virtual functions cannot be static and also cannot be a friend function of another class. • Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism. • The prototype of virtual functions should be same in base as well as derived class. • They are always defined in base class and overridden in derived class. It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used. • A class may have virtual destructor but it cannot have a virtual constructor.

SYNTAX

Class classname { public: . . . . . virtual returntype functionname (arguments) { ...... } }; EXAMPLE

// concept of Virtual Functions #include using namespace std;

class base { public: virtual void print () { cout<< "print base class" <

class derived:public base { public: void print () { cout<< "print derived class" <

int main() { base *bptr; derived d; bptr = &d;

//virtual function, binded at runtime bptr->print();

// Non-virtual function, binded at compile time bptr->show(); }

VIRTUAL BASE CLASS

• The duplication of inherited members due to the multiple paths can be avoided by making the common base class as virtual base class while declaring the direct or intermediate base classes as shown below. • Need for Virtual Base Classes o Consider the situation where we have one class A .This class is A is inherited by two other classes B and C. Both these class are inherited into another in a new class D as shown in figure below.

SYNTAX class A {

}; class B1:virtual public A {

}; class B2:public virtual A {

}; class C:public B1,public B2 {

}; EXAMPLE

class A { public: int a; A() // constructor { a = 10; } };

class B : public virtual A { …………… };

class C : public virtual A { ……………. };

class D : public B, public C { ……………….. };

int main() { D object; // object creation of class d cout << "a = " << object.a << endl; return 0; }

OUTPUT a = 10 ABSTRACT CLASS AND PURE VIRTUAL FUNCTION

• ABSTRACT CLASS o A class with at least one pure virtual function or abstract function is called abstract class. • A PURE VIRTUAL FUNCTION (or ABSTRACT FUNCTION) in C++ is a virtual function for which we don’t have implementation, we only declare it. • The virtual function doesn’t have any operation is called “do-nothing” function or pure virtual function. • A pure virtual function is declared by assigning 0 in declaration. • Pure virtual function is also known as abstract function. • We can't create an object of abstract class b'coz it has partial implementation of methods. • Abstract function doesn't have body • We must implement all abstract functions in derived class. • This is represented as

o virtual void display()=0;

EXAMPLE

#include #include

class BaseClass //Abstract class { public: virtual void Display1()=0; //Pure virtual function or abstract function virtual void Display2()=0; //Pure virtual function or abstract function

void Display3() { cout<<"\n\tThis is Display3() method of Base Class"; } };

class DerivedClass : public BaseClass { public: void Display1() { cout<<"\n\tThis is Display1() method of Derived Class"; }

void Display2() { cout<<"\n\tThis is Display2() method of Derived Class"; } };

void main() { DerivedClass D;

D.Display1(); // This will invoke Display1() method of Derived Class D.Display2(); // This will invoke Display2() method of Derived Class D.Display3(); // This will invoke Display3() method of Base Class }

OUTPUT

This is Display1() method of Derived Class This is Display2() method of Derived Class This is Display3() method of Base Class

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT – V – PROGRAMMING IN C and C++ SBSA1102 UNIT 5

TEMPLATES AND EXCEPTION HANDLING

Function Templates and Class Templates – Name spaces – Standard Template Library - Casting – Exception Handling –case study.

TEMPLATES: Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can create a single function or a class to work with different data types using templates. Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs. The concept of templates can be used in two different ways: • Function Templates • Class Templates

FUNCTION TEMPLATES A function template works in a similar to a normal function, with one key difference. A single function template can work with different data types at once but, a single normal function can only work with one set of data types. Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration. However, a better approach would be to use function templates because you can perform the same task writing less and maintainable code. A function template starts with the keyword template followed by template parameter/s inside < > which is followed by function declaration. Declaration of Function Template: template T someFunction(T arg) { ...... } In the above code, T is a template argument that accepts different data types (int, float), and class is a keyword. You can also use keyword typename instead of class in the above example. When, an argument of a data type is passed to someFunction( ), compiler generates a new version of someFunction() for the given data type. Example 1: Function Template to find the largest number #include // template function template T Large(T n1, T n2) { return (n1 > n2) ? n1 : n2; } int main() { int i1, i2; float f1, f2; char c1, c2; cout << "Enter two integers:\n"; cin >> i1 >> i2; cout << Large(i1, i2) <<" is larger." << endl; cout << "\nEnter two floating-point numbers:\n"; cin >> f1 >> f2; cout << Large(f1, f2) <<" is larger." << endl; cout << "\nEnter two characters:\n"; cin >> c1 >> c2; cout << Large(c1, c2) << " has larger ASCII value."; return 0; } Output: Enter two : 5 10 10 is larger. Enter two floating-point numbers: 12.4 10.2 12.4 is larger. Enter two characters: z Z z has larger ASCII value.

In the above program, a function template Large() is defined that accepts two arguments n1 and n2 of data type T. T signifies that argument can be of any data type. Large() function returns the largest among the two arguments using a simple conditional operation. Inside the main() function, variables of three different data types: int, float and char are declared. The variables are then passed to the Large() function template as normal functions. During run-time, when an integer is passed to the template function, compiler knows it has to generate a Large() function to accept the int arguments and does so. Similarly, when floating-point data and char data are passed, it knows the argument data types and generates the Large() function accordingly. This way, using only a single function template replaced three identical normal functions and made your code maintainable.

Example 2: Swap Data Using Function Templates Program to swap data using function templates.

#include template void Swap(T &n1, T &n2) { T temp; temp = n1; n1 = n2; n2 = temp; } int main() { int i1 = 1, i2 = 2; float f1 = 1.1, f2 = 2.2; char c1 = 'a', c2 = 'b'; cout << "Before passing data to function template.\n"; cout << "i1 = " << i1 << "\ni2 = " << i2; cout << "\nf1 = " << f1 << "\nf2 = " << f2; cout << "\nc1 = " << c1 << "\nc2 = " << c2; Swap(i1, i2); Swap(f1, f2); Swap(c1, c2); cout << "\n\nAfter passing data to function template.\n"; cout << "i1 = " << i1 << "\ni2 = " << i2; cout << "\nf1 = " << f1 << "\nf2 = " << f2; cout << "\nc1 = " << c1 << "\nc2 = " << c2; return 0; } Output: Before passing data to function template. i1 = 1 i2 = 2 f1 = 1.1 f2 = 2.2 c1 = a c2 = b After passing data to function template. i1 = 2 i2 = 1 f1 = 2.2 f2 = 1.1 c1 = b c2 = a In this program, instead of calling a function by passing a value, a call by reference is issued. The Swap() function template takes two arguments and swaps them by reference.

CLASS TEMPLATES Like function templates, you can also create class templates for generic class operations. Sometimes, you need a class implementation that is same for all classes, only the data types used are different. Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class. This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function should be performed on all classes/functions. However, class templates make it easy to reuse the same code for all data types. Declaration class template : class className {

public: T var; T someOperation(T arg); ...... }; In the above declaration, T is the template argument which is a placeholder for the data type used. Inside the class body, a member variable var and a member function someOperation() are both of type T. creation of class template object: To create a class template object, you need to define the data type inside a < > when creation. className classObject; For example: className classObject; className classObject; className classObject;

Example 3: Simple calculator using Class template Program to add, subtract, multiply and divide two numbers using class template #include template class Calculator { private: T num1, num2; public: Calculator(T n1, T n2) { num1 = n1; num2 = n2; } void displayResult() { cout << "Numbers are: " << num1 << " and " << num2 << "." << endl; cout << "Addition is: " << add() << endl; cout << "Subtraction is: " << subtract() << endl; cout << "Product is: " << multiply() << endl; cout << "Division is: " << divide() << endl; }

T add() { return num1 + num2; } T subtract() { return num1 - num2; } T multiply() { return num1 * num2; } T divide() { return num1 / num2; } }; int main() { Calculator intCalc(2, 1); Calculator floatCalc(2.4, 1.2); cout << "Int results:" << endl; intCalc.displayResult(); cout << endl << "Float results:" << endl; floatCalc.displayResult(); return 0; } Output Int results: Numbers are: 2 and 1. Addition is: 3 Subtraction is: 1 Product is: 2 Division is: 2 Float results: Numbers are: 2.4 and 1.2. Addition is: 3.6 Subtraction is: 1.2 Product is: 2.88 Division is: 2

In the above program, a class template Calculator is declared. The class contains two private members of type T: num1 & num2, and a constructor to initalize the members. It also contains public member functions to calculate the addition, subtraction, multiplication and division of the numbers which return the value of data type defined by the user. Likewise, a function displayResult() to display the final output to the screen. In the main() function, two different Calculator objects intCalc and floatCalc are created for data types: int and float respectively. The values are initialized using the constructor. Notice we use and while creating the objects. These tell the compiler the data type used for the class creation. This creates a class definition each for int and float, which are then used accordingly. Then, displayResult() of both objects is called which performs the Calculator operations and displays the output. NAMESPACES: Namespace is a container for identifiers. It puts the names of its members in a distinct space so that they don't conflict with the names in other namespaces or global namespace. Creating a Namespace Creating a namespace is similar to creation of a class. namespace MySpace { // declarations }

int main() { // main function } This will create a new namespace called MySpace, inside which we can put our member declarations. Rules to create Namespaces: The namespace definition must be done at global scope, or nested inside another namespace. Namespace definition doesn't terminates with a semicolon like in class definition. You can use an alias name for your namespace name, for ease of use. Example for Alias: namespace Study { void study(); class Learn { // class defintion }; }

// St is now alias for Study namespace St = Study You cannot create instance of namespace. There can be unnamed namespaces too. Unnamed namespace is unique for each translation unit. They act exactly like named namespaces. Example for Unnamed namespace: namespace { class Head { // class defintion }; // another class class Tail { // class defintion }; int i,j,k; }

int main() { // main function } A namespace definition can be continued and extended over multiple files, they are not redefined or overriden. For example, below is some header1.h header file, where we define a namespace: namespace MySpace { int x; void f(); } We can then include the header1.h header file in some other header2.h header file and add more to an existing namespace:

#include "header1.h"; namespace MySpace { int y; void g(); } Using a Namespace in C++ There are three ways to use a namespace in program, • Scope resolution operator (::) • The using directive • The using declaration With Scope resolution operator (::) Any name (identifier) declared in a namespace can be explicitly specified using the namespace's name and the scope resolution :: operator with the identifier. namespace MySpace { class A { static int i; public: void f(); }; // class name declaration class B; //gobal function declaration void func(); } // Initializing static class variable int MySpace::A::i=9; class MySpace::B { int x; public: int getdata() { cout << x; } // Constructor declaration B(); }

// Constructor definition MySpace::B::B() { x=0; } Using Directive: using keyword allows you to import an entire namespace into your program with a global scope. It can be used to import a namespace into another namespace or any program.

Conside a header file Namespace1.h: namespace X { int x; class Check { int i; }; } Including the above namespace header file in Namespace2.h file:

include "Namespace1.h"; namespace Y { using namespace X; Check obj; int y; } We imported the namespace X into namespace Y, hence class Check will now be available in the namespace Y.

Hence we can write the following program in a separate file, let's say program1.cpp

#include "Namespace2.h"; void test() { using Namespace Y; // creating object of class Check Check obj2; } Hence, the using directive makes it a lot easier to use namespace, wherever you want.

The using declaration When we use using directive, we import all the names in the namespace and they are available throughout the program, that is they have a global scope. But with using declaration, we import one specific name at a time which is available only inside the current scope.

NOTE: The name imported with using declaration can override the name imported with using directive

Consider a file Namespace.h:

namespace X { void f() { cout << "f of X namespace\n"; } void g() { cout << "g of X namespace\n"; } }

namespace Y { void f() { cout << "f of Y namespace\n"; } void g() { cout << "g of Y namespace\n"; } } Now let's create a new program file with name program2.cpp with below code:

#include "Namespace.h"; void h() { using namespace X; // using directive using Y::f; // using declaration f(); // calls f() of Y namespace X::f(); // class f() of X namespace } Output: f of Y namespace f of X namespace

In using declaration, we never mention the argument list of a function while importing it, hence if a namespace has overloaded function, it will lead to ambiguity.

STANDARD TEMPLATE LIBRARY: STL is an acronym for standard template library. It is a set of C++ template classes that provide generic classes and function that can be used to implement data structures and algorithms .STL is mainly composed of :

1. Algorithms 2. Containers 3. Iterators

STL provides numerous containers and algorithms which are very useful in completive programming , for example you can very easily define a linked list in a single statement by using list container of container library in STL , saving your time and effort. STL is a generic library , i.e a same container or algorithm can be operated on any data types , you don’t have to define the same algorithm for different type of elements. For example , sort algorithm will sort the elements in the given range irrespective of their data type , we don’t have to implement different sort algorithm for different datatypes. C++: Algorithms in STL STL provide number of algorithms that can be used of any container, irrespective of their type. Algorithms library contains built in functions that performs complex algorithms on the data structures. For example: one can reverse a range with reverse() function, sort a range with sort() function, search in a range with binary_search() and so on. Algorithm library provides abstraction, i.e you don't necessarily need to know how the the algorithm works. C++: Containers in STL Container library in STL provide containers that are used to create data structures like arrays, linked list, trees etc. These container are generic, they can hold elements of any data types, for example: vector can be used for creating dynamic arrays of char, integer, float and other types. C++: Iterators in STL Iterators in STL are used to point to the containers. Iterators actually acts as a bridge between containers and algorithms. For example: sort() algorithm have two parameters, starting iterator and ending iterator, now sort() compare the elements pointed by each of these iterators and arrange them in sorted order, thus it does not matter what is the type of the container and same sort() can be used on different types of containers. Use and Application of STL STL being generic library provide containers and algorithms which can be used to store and manipulate different types of data thus it saves us from defining these data structures and algorithms from the scratch. Because of STL, now we do not have to define our sort function every time we make a new program or define same function twice for the different data types, instead we can just use the generic container and algorithms in STL. This saves a lot of time, code and effort during programming, thus STL is heavily used in the competitive programming, plus it is reliable and fast. Containers: Containers Library in STL gives us the Containers, which in simplest words, can be described as the objects used to contain data or rather collection of object. Containers help us to implement and replicate simple and complex data structures very easily like arrays, list, trees, associative arrays and many more. The containers are implemented as generic class templates, means that a container can be used to hold different kind of objects and they are dynamic in nature! Following are some common containers : vector : replicates arrays queue : replicates queues stack : replicates stack priority_queue : replicates heaps list : replicates linked list set : replicates trees map : associative arrays Classification of Containers in STL: Containers are classified into four categories :

• Sequence containers : Used to implement data structures that are sequential in nature like arrays(array) and linked list(list).

• Associative containers : Used to implement sorted data structures such as map, set etc. • Unordered associative containers : Used to implement unsorted data structures.

• Containers adaptors : Used to provide different to the sequence containers.

Using Container Library in STL Below is an example of implementing linked list, first by using structures and then by list containers.

#include

struct node { int data; struct node * next; }

int main () { struct node *list1 = NULL; } The above program is only creating a list node, no insertion and deletion functions are defined, to do that, you will have to write more line of code.

Now lets see how using Container Library simplifies it. When we use list containers to implement linked list we just have to include the list header file and use list constructor to initialize the list.

#include #include int main () { list list1; } And that's it! we have a list, and not just that, the containers library also give all the different methods which can be used to perform different operations on list such as insertion, deletion, traversal etc.

Thus you can see that it is incredibly easy to implement data structures by using Container library

PAIR Template in STL Although Pair and Tuple are not actually the part of container library but we'll still discuss them as they are very commonly required in programming competitions and they make certain things very easy to implement. SYNTAX of pair is: pair pair1, pair2 ; The above code creates two pairs, namely pair1 and pair2, both having first object of type T1 and second object of type T2. Now T1 will be referred as first and T2 will be referred as second member of pair1 and pair2. Example of Pair Pair Template: Some Commonly used Functions Here are some function for pair template : Operator = : assign values to a pair. swap : swaps the contents of the pair. make_pair() : create and returns a pair having objects defined by parameter list. Operators( == , != , > , < , <= , >= ) : lexicographically compares two pairs. Program demonstrating PAIR Template #include int main () { pair pair1, pair3; //creats pair of integers pair pair2; // creates pair of an integer an a string

pair1 = make_pair(1, 2); // insert 1 and 2 to the pair1 pair2 = make_pair(1, "Studytonight") // insert 1 and "Studytonight" in pair2 pair3 = make_pair(2, 4) cout<< pair1.first << endl; // prints 1, 1 being 1st element of pair1 cout<< pair2.second << endl; // prints Studytonight

if(pair1 == pair3) cout<< "Pairs are equal" << endl; else cout<< "Pairs are not equal" << endl;

return 0; }

TUPLE in STL Tuple and Pair are very similar in their structure. Just like in pair we can pair two heterogeneous object, in tuple we can pair three heterogeneous objects. SYNTAX of a tuple is: // creates tuple of three object of type T1, T2 and T3 tuple tuple1; Tuple Template Tuple Template: Some Commonly used Functions Similar to pair, tuple template has its own member and non-member functions, few of which are listed below : A Constructor to construct a new tuple Operator = : to assign value to a tuple swap : to swap value of two tuples make_tuple() : creates and return a tuple having elements described by the parameter list. Operators( == , != , > , < , <= , >= ) : lexicographically compares two pairs. Tuple_element : returns the type of tuple element Tie : Tie values of a tuple to its refrences.

Program demonstrating Tuple template #include int main () { tuple tuple1; //creates tuple of integers tuple tuple2; // creates pair of an integer an 2 string

tuple1 = make_tuple(1,2,3); // insert 1, 2 and 3 to the tuple1 tuple2 = make_pair(1,"Studytonight", "Loves You"); /* insert 1, "Studytonight" and "Loves You" in tuple2 */ int id; string first_name, last_name; tie(id,first_name,last_name) = tuple2; /* ties id, first_name, last_name to first, second and third element of tuple2 */ cout << id <<" "<< first_name <<" "<< last_name; /* prints 1 Studytonight Loves You */ return 0; } TYPE CASTING: Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

Implicit conversion Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example: short a=2000; int b; b=a; Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This warning can be avoided with an explicit conversion. Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions For example: class A {}; class B { public: B (A a) {} }; A a; B b=a; Here, an implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed. Explicit conversion C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit : functional and c-like casting: short a=2000; int b; b = (int) a; // c-like cast notation b = int (a); // functional notation The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct: // class type-casting #include class CDummy { float i,j; }; class CAddition { int x,y; public: CAddition (int a, int b) { x=a; y=b; } int result() { return x+y;} }; int main () { CDummy d; CAddition * padd; padd = (CAddition*) &d; cout << padd->result(); return 0; }

DYNAMIC_CAST Dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class. Therefore, dynamic_cast is always successful when we cast a class to one of its base classes: class CBase { }; class CDerived: public CBase { }; CBase b; CBase* pb; CDerived d; CDerived* pd; pb = dynamic_cast(&d); // ok: derived-to-base pd = dynamic_cast(&b); // wrong: base-to-derived

STATIC_CAST: Static_Cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided. class CBase {}; class CDerived: public CBase {}; CBase * a = new CBase; CDerived * b = static_cast(a); This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced. static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types: double d=3.14159265; int i = static_cast(d); Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

reinterpret_cast reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked. It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer. The conversions that can be performed by reinterpret_cast but not by static_cast are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example: class A {}; class B {}; A * a = new A; B * b = reinterpret_cast(a); This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe. const_cast: This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter

EXCEPTION HANDLING: • The exception refers to unexpected condition in a program. • The unexpected conditions could be faults, causing an error which in turn causes the program to fail. • The error handling mechanism of C++ is generally referred to as exception handling. • Types of Exceptions 1. Synchronous Exception 2. Asynchronous Exception

• Synchronous Exception The exception which occurs during the program execution, due to some fault in the input data or technique that is not suitable to handle the current class of data, with in the program are known as synchronous exception. Example: out of range, divide by zero, overflow, underflow

• Asynchronous Exception The errors that are caused by events beyond the control of the program are called asynchronous exceptions. Example: disk failure Exception handling Mechanism: The purpose of the exception handling mechanism is to provide means to detect and report an “exceptional circumstance” so that appropriate action a\can be taken. The exception handling mechanism consists of the following task or operations: 1 Find the problem ( hit the exception) 2 Inform that an error has occurred (throw the exception) 3 Receive the error information ( catch the exceptions) 4 Take corrective actions( handle the exceptions) Error handling basically consists of two segments; • One to detect and to thro exceptions • Other to catch the exceptions and to take appropriate actions. Exception Handling Model: The exception handling mechanism uses three blocks try, throw, catch. The relationship of those three exception handling model shown below

Detects and Catches and throws an handles the exception exception try block catch block

Exception

• The keyword try is used to preface a block of statements (surrounded by braces) which may generate exceptions. This block of statements known as try bock. • When an exception is detected, it is thrown using a throw statement in the try block. • A catch block defined by the keyword catch catches the exception thrown by the throw statement in the try block, and handle it appropriately. • General format: ………… ………… try { ………. // block of statements which detects and throw exception // throws an exception ………. ………. } catch ( type arg) { ……… // block of statements that handles the exception ……… ……… } …….. ……..

• When the try block throws an exception, the program control leaves the try block and enters the catch statement of the catch block. • Exceptions are objects or variables used to transmit information about a problem. • If the type of object thrown matches the arg type in the catch statement, then catch block is executed for handling the exception. • If they do not match, the program is aborted with the help of the abort() function which is invoked automatically. • The catch block may have more than one catch statements, each corresponding to a particular type of exception. • For example if the throw block is likely to throw two exception, the catch block will have two catch statements one for each type of exception. Each catch statement is called is exception handler. • When no exception is detected and thrown, the control goes to the statement immediately after the catch block. That is catch block is skipped. • Example: divide by zero #include void main( ) { int x, y, z; cout<<”enter the values of x, y, z”; cin>>x>>y>>z; try { if(x= =y) throw y; else

int d= z / ( x- y);

cout<<”the result of z/ (x-y )is:”<< d; } catch( int y) { cout<<”exception caught x-y is “<< x-y ; } }

RUN 1: enter the values of x , y, z 50 30 20 the result of z/ (x-y ) is: 1 RUN 2: Enter the values of x, y, z 30 30 20 exception caught x-y is : 0

Using function that generate exceptions: #include void divide ( int x, int y,int z) { cout<<”we are inside the function”; if(x= =y) throw (x-y); else

int d= z / ( x- y);

cout<<”the result of z/ (x-y )is:”<< d; } void main( ) { try

{ cout<<” we are inside the try block”;

divide( 10, 20, 30); // invoke divide () divide( 10, 10, 20); // invoke divide () } catch( int i) // catches the exception { cout<<”exception caught x-y is : “< class positive { }; class negative { }; class zero { }; void greater ( int num) { if( num >0) throw positive( ); else if (num < 0) throw negative( ); else

throw zero( );

} void main( ) { int num; cout<<”enter any number”; cin>>num; try { greater ( num); } catch( positive) { cout<<”+ve exception”; } catch(negative) { cout<<”-ve exception”; } catch (zero) { cout<<”0 exception”; } }