Vous êtes sur la page 1sur 90

1) Explain various programming paradigms?

(E) Ans) Programming paradigms: Programming paradigms means the way of writing a program depending upon the requirements. These requirements mainly focus the task of development team to develop programs for the small-scale projects to the large-scale projects. The programming paradigms is categorized into the following way 1. Monolithic programming 2. Procedural programming 3. Structural programming 4. Object oriented programming Monolithic programming: The programs written in these languages exhibit relatively flat physical structure; they consist of only global data and sequential code. Program control is achieved through the use of jump statements and the program code is duplicated each time it is to be used. It is having no support of subroutines hence it is suitable to develop small and simple programs. It is very difficult to enhance the program code. Ex Assembly language

goto 100 ----goto 200 ----goto 300

Global data

Procedural programming: In the procedural programming approach the problem is divided into sequence of functions. The primary focus in this approach is on functions. Number of functions are written to accomplish the task of a project. In a multifunction program important data items are placed as global data and they may be accessed by all the functions. Each function is also having a set of local data items.

Global data

F1

F2

F3

F4

The following are the important features: 1. 2. 3. 4. 5. Programs are organized in the form of subroutines and all data items are global Program control chive by call to subroutines Code reusability occurs Suitable for medium sized software application Difficult to maintain and enhance the program code

The drawback is there is no data security for global data Structured programming Structure programming is used to develop large-scale projects. The large-scale project consists of large development team, developing different parts of the same project independently. The separately compiled program modules are grouped together to create big projects. In this multiple module program, each module is having a separate set of related functions. The following are important features of structures programming

Global data

M1

Module 2 F1 F2

M3

1. 2. 3. 4. 5. 6.

Importance given to algorithm rather than data Projects can be broken up into modules and programmed independently Each module is divided into individual procedures that perform separate tasks. Module are independent of each other as far as possible Modules have their own local data and processing logic User defined data types are introduced

Object oriented programming: Object oriented programming is a methodology that allows the connection of data structures with operation similar to the way it is planned in the human mind. They connect a specific set of actions with a given type of objects based upon these connections. Object oriented language support data abstractions. They can be classified as Object based language = encapsulation + object identity and Object oriented language = object based + inheritance + polymorphism

Object 1

Object 2

Object 3

The following are the important features of object-oriented programming. Importance given to data rather than algorithm Data abstraction is introduced in addition to procedural abstraction. Data and associated operations are unified into a single unit The objects are grouped with common attribute operation and semantics. Programs are designed around the data being operated rather than operate themselves. Relation ships can be created between similar, yet distinct data types.

2) What is object oriented programming? Explain its feature? (E) Ans) Object oriented programming language:The object-oriented technology defines OOP s as follows: OOP is a method of implementation in which programs are organized as co-operative collections of objects, each of which represents an instance of some class and whose classes are all members of a hierarchy of classes united through the property called inheritance . Object oriented programming is an extension for the basic structured programming language. In this technique more importance is given to the data. Using this technique we can combine data as well as operations that can be performed on data as a single unit using Class data type. The class is a user-defined data type, which holds both data and functions. The internal data of a class is called data member and the operations applied on data member is called member functions. The member function manipulates the data members of a class. The data members of a class cannot be utilized by other functions except member functions. The variables of class data type is called object Features of object-oriented paradigm (Elements of Object-oriented programming): The fundamental features of the oops are the following Encapsulation Message passing Data abstraction Extensibility Inheritance Persistence Polymorphism Delegation Genericity

Encapsulation: Encapsulation is a mechanism of grouping of data and functionality in to single object. If a change is made to a class object, all instances of that class are changed. Encapsulation hides detailed internal specification of an object, and provides only its external interfaces to keep them safe from misuse. Data abstraction: The technique of creating new data types that are well suited for an application to be programmed is known as data abstraction. It provides the ability to create user defined data types. In C++ class is used to create user-defined data types called abstract data types (ADT) Inheritance: It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance involves the creation of new classes from the existing classes. The new derived class inherits the members of the base class and also adds its own member functions, data members. Polymorphism: In polymorphism a single name or operator to be associated with different operations depending on the type of data passed to it. In C++ polymorphism can be achieved by using function overloading, operator overloading and dynamic binding (Virtual functions). Message passing: It is the process of invoking an operation on an object. It is used to transfer data between objects of same or different family. Extensibility: It allows the extension of the functionality of the existing software components. In C++ it can be achieved by using abstract classes and inheritance. Persistence: Persistence means the ability to retain previous versions of a data structure after it is modified. All database systems support persistence. C++ does not support persistence. It can be achieved by explicit use of file streams in a program. Delegation: It is alternative to class inheritance. In delegation two objects are involved in handling request. In C++ delegation can be achieved by making an object of one class as a data member of other class. Genericity: It is a technique of defining software components that have more than one interpretation depending on the data types of parameters. It allows the declaration of data items without specifying their exact data types. Such unknown data types are resolved at the time of their usage based on data type of parameters. The following are the important characteristics of OOP : Improvement over the structured programming paradigm Importance given to data rather than algorithm (Function) Data abstraction is introduced Data and associated operations are unified (combined) into a single unit Objects are grouped with common attributes and operations. Programs are designed around the data being operated Relation ships can be created between different data types also.

3). Explain various data types in C++?(s) Abs) Data types: C++ data types can be classified as 1. Standard data types 2. Derived (extended data types) 3. User defined data types

The following figure represents the detail of c++ data type classification

C++ DATA TYPES User defined Data type Structure Union Class Enum Standard data types Derived Data type Array Pointer Function

void Integral type int char Floating type float double

Standard data types: Standard data types are used to tell the compiler what type of data to be handeled by an identifier. These data types give complete details of the behavior of a data type. It is possible to handle only one value at a time. Derived data types (extended data types): Derived data types are used to extend the behavior of an existing simple data type to get more functionality. It is possible to handle more than one value at a time using a single identifier. For example arrays User defined data types: User defined data types are created by a user by using simple, derived, user defined data types as per the user requirement. The user has to decide the functionality and behavior of these data types. By using these data types to handle more than one data type using single identifier For example structures and classes The following table gives the details regarding various data types Data Type 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) Void: 1) 2) Char Unsigned Char Signed Char int Unsigned int Signed int Short int long int float double long double Size Range 1 1 1 2 2 2 2 4 4 8 10 in -128 to 127 0 to 255 -128 to 127 -32768 to 32767 0 to 65,535 -32768 to 32767 -32768 to 32767 -2147483648 to 2147483647 1.2e-38 to 3.4e38 2.2e-308 to 1.8e308 3.4e-4932 to 1.1e+4932 bytes

The Void is used to represent the following things To specify the return type of a function when it is not returning any value. To indicate an empty argument list to a function

Qualifier: qualifiers are used to extend the behavior of standard data type. There are two qualifiers namely size and sign. Size qualifier is used to extend the size of an existing data type and sign qualifier used to make the data type as a signed number or unsigned numbers. Size qualifier: there are two size qualifiers they are short and long. Short is used to decrees the size and ling is used to extend the size to maximum. For example short int size is only 2 bytes irrespective of operating system. It is not possible to apply size qualifier on char

Sign qualifier: there are two sign qualifiers they are signed and unsigned. Unsigned qualifier is used to make the number as a positive number. By default all number are positive. It is not possible to apply sign qualifier on long, double. 4) Explain about operator precedence in CPP? (E) Ans) Operator precedence: Operator precedence determines how to evaluate an expression. Each and every operator has a priority and that priority is decided by precedence of an operator. To evaluate an expression always evaluate the operators with high precedence at first and continue the process to low precedence. Parentheses can be used to override the precende and force some parts of an expression should be evaluated first. Operators within the parentheses are evaluated first. Evaluation of expression depends on two things they are 1. Operator precedence: Every operator has a precedence associated with it. Precedence rules help in removing the ambiguity about the order of evaluation of operators while evaluating an expression. 2. Operator Associativity: Association of operators specifies the direction of evaluation. The precedence and Associativity of the entire operators are shown in the figure. C++ does not specify the order of evaluation of &&, ||, ?: , and () operator. For example, the statement such as x = g () + h (); where g(),h() are function. Suppose g () may be evaluated before h () or vice versa. Thus if g () or h () alters a variable on which the other depends, then the resultant value of x is dependent on the order of evaluation. Similarly the order in which function arguments are evaluated is not specified. Category Highest precedence Unary Member access Multiplication Additive Shift Relational Equality Bit wise AND Bit wise XOR Bit wise OR Logical AND Logical OR Conditional Assignment Comma Operator () ,[] ,-> , :: , . !, ~, *, -, ++, --, &, +, sizeof, new, delete .* , ->* *, /, % +, <<, >> <, <=, >, >= ==, != & ^ | && || ?: =, *=, /=, %=, +=,-=,&=, ^=, !=, <<=, >>= , Precedence 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Left to right

5) Explain about input, output statements in CPP? (s) Ans) C++ I/O statement:C++ I/O operations are called streams. There are two types of streams in c++ they are 1. Input streams 2. Output streams Input streams: input streams are used to read data from input devices like keyboard, hard disc, etc. by using a predefined input stream object cin and >> extraction operator to read data from input devices. Syntax: cin >> var; example: cin >> x ; Hear cin represents stream object and >> operator is called extraction operator For example in the above statement the compiler wait for input data for variable x the input data is then take from input device and then assigned to variable x. It is possible to read any type of data using cin statement. The header file iostream.h must be included to use this statement in a program. Input cascading operation: Input cascading means read values of more than one variable of different data types using single input statement.

Syntax: cin >> var1 >> var2>> var3; Example: cin >> x>>y>>z; where x, y, z may be of different data type Output streams: output streams are used to print data on output devices like monitor, discs etc. by using a predefined output stream object cout and << insertion operator to read data from output devices. Syntax: cout << var; example: cout << x; Hear cout represents stream object and << operator is called insertion operator For example in the above statement the compiler prints value of variable x on output device. It is possible to print any type of data using cout statement. The header file iostream.h must be included to use this statement in a program. Output cascading operation: Output cascading means print values of more than one variable of different data types using single output statement. Syntax cout << var1 <<var2<<var3: Example cout << x << y <<z; where x, y, z may be of different data type Advantages of streams 1. Streams do not require explicit data types specification in I/O statement 2. Streams do not require explicit address operator prior to the variable in the input statement 6). Write about C++ control structures? Ans) Control structures determine the direction or order in which statements within the block are executed. Control statements are used to design control structures. In CPP control statements can be classified as 1. Conditional control statements (if, if else, ladder if, switch .. case ) 2. Iterative control statements ( for, while, do .. while) 3. Unconditional control statements (goto, continue, break, exit) Conditional control statements: Conditional control statements are used to control the flow of control based on condition statement. For example if , if else, switch etc. If statement: Syntax:

1. if (condition) statement; // simple if statement 2. if (condition ) // if else statement Statement else Statement for example if (a > b) a = b; or if (a> b) cout << a is big ; else cout <<b is big;

In if statement the value of the condition is equal to true or 1 then the statement in the true block are executed and if the value of a condition is false the statements in the false block are executed. In simple if statement only true block is available. Iterative control statements: Iterative control statement is used to repeatedly execute a finet set of statement for a finet number of times depends upon a condition. There are two types of iterative control statements they are 1. Entry control statement and 2. Exit control statements. Entry control statements: in entry control statements if the condition value is equal to true or 1 then only the control enters in to the block. If the condition value is equal to false or 0 the control goes to the next executable statement. For example for, while. For statement: Syn for (initialization; condition; step value ) Statement; Example for (int i=1; I < 10; i++) Cout << I;

For statement is having three parts namely initialization, condition, step value among these there first the initialization part is executed only once and check the condition if the condition value is true or 1 the control enters in to the loop and come back to third part step value to get the next value and check the condition. The above process is repeated until the condition is false. The minimum number of time the loop executed is 0. While statement: Syn while (condition) statements; Example while (I ++> 0) cout << I; If the condition value is true or 1 the statements in the while loop are executed and if the condition is false the control come out of loop. The minimum number of times a loop execute is zero. Exit control statements: in exit control statements first the control enters in to the loop and checks the condition. If the condition value is equal to true or 1 repets the statements other wise break the loop. The minimum number of times the exit control loop executed is 1. For example do.. while. Unconditional statements: Unconditional statements are used to transfer the control from one place to other with out any condition. They are generally used to branch or termination process. For example goto, break, continue, and exit; Syntax: goto used to branch the control to a particular place Break to terminate the iterative statements Continue to get the next iterative value Exit terminate the entire program

6) Define function? How it is to be created in CPP? (or) Explain components of a function? (E) Ans) Functions in C++: A function is a set of executable statements having well defined specific task that can be processed independently. The function can be designed, developed, and implemented independently by different programmers. Functions are independent because variable names and labels defined within its body are local to it. The following are the advantages of functions. 1. 2. 3. 4. 5. 6. 7. Modular programming. Reduction in the amount of work and development time Program and function debugging is easier. Division of work is simplified due to the use of divide and conquer principle Reduction in size of the program due to code reusability Functions can be accessed repeatedly without redevelopment. Which in turn promotes reuse of code Library of functions cab be implemented by combining well-designed, tested, and proved functions.

When the function is called, control is transferred to the first statement in the function body. The other statements in the function body are then executed and the control returns to the calling program. Function components: Every function has the following components associated with it: Function declaration or prototype Function definition Function call Return Function prototyping: When a function call is occurred the compiler checks the function calls with its prototype so that correct argument types are used. The prototype tells the compiler function name, return data type, number of arguments and their data types. Function prototype should be declared as a first line of a statement. It must be terminated by semincolon (;). The function prototype is compulsory in c++ because it supports strict binding. To eliminate prototype, the function should be declare before function calling. Syntax: Return_type function name (argument-list);

Example

int add (int a , int b)

or int add (int , int);

The variable names are optional in prototype declaration. It should be terminated by semicolon. Each parameter must be declared independently inside the parenthesis. A combined declaration is not allowed. Function definition / declaration:The body of the function that defines the task of the function can be called as function definition . The first line of the function definitions is known as function declaration and is followed by the function body. The declaration must use the same functions name, same number of arguments, the arguments type and the return type. No other function definitions are allowed within a function definition. float volume (int a, float b, float c) { float v; v= 12.23; } The function volume can be invoked or called as follows x= volume (10,10.5,8.6); We can also declare a function with an empty argument list and without having a return value. void display ( ); (or) void display (void) ; Function call: A function gets life only when a call to the function is made . A function call is specified by the function name followed by the arguments enclosed in parentheses and terminated by a semicolon. The return type is not mentioned in the function call. For example: float x = volume (1,2.2, 3.4); return: The return statement is used to return the control back to the main program. It always returns only one value at a time. There is no limitation for the number of return statements in a function body. Once a return statement is executed control automatically transferred to the calling program and leaves the remaining statements after the return statement in the function body. Syntax return (variable or expression or value); 7) Explain about pointers in CPP? (s) Ans) Pointers A pointer is a variable which holds the address of any variable or a function . A pointer can refer to an object of any one of the data type. Syntax : data type *variable; for example : int *x; Address of operator (&): syntax : pointer_variable = & varible; As soon as we declare a variable, the amount of memory needed is assigned for it at a specific location in memory. Address of operator is used to get the address of any variable. Value at address operator or dereference operator (*) Syntax : *pointer_varible; Using a pointer we can directly access the value stored in the variable which it points to. Value at address operator is used to access the value pointed by a pointer. Pointer initialization: Syntax : pointer_variable = & variable; Pointers are always initialized with an address of any variable by using & symbol. As in the case of arrays the compiler allocate the required memory and return the base address back. For example: char *x = hello In this case, memory space is reserved to contain "hello" and then a pointer to the first character of this memory block is assigned to variable x. The pointer x points to a sequence of characters and can be read as an Array Some common uses for pointers are: To access dynamic data structures such as linked lists, trees, and queues.

To access elements of an array or members of a structure or C++ class. To access an array of characters as a string. To pass the address of a variable to a function by referencing a variable through its address, a function can change the contents of that variable. Two pointers with the same type qualifiers are compatible if they point to objects of compatible types The size of any pointer variable is 2 bytes

Limitations of pointer variables: It is not possible to use pointers to refer objects that are declared with the register storage class specifier. It is not possible to refer to a bit field or reference A pointer can hold only one value at a time The general form of pointer variable is data type *pointer_variable; Where pointer_varible is the name of the pointer and * Represent the declared variable is of type pointer For ex: int *x; char *y; float *z; 8). what is pointer arithmetic? What are the different types of pointers? (s) Pointer arithmetic: Only addition and subtraction operations are allowed to be conducted on pointers, the others are not allowed on pointers. Both addition and subtraction have a different behavior with pointers according to the size of the data type to which they point. For example: assume that *x is of type char pointer and *y is of type integer then If x++ is equal to the address of x + 1* sizeof (char); Similarly y - - is equal to the address of y-1* sizeof (int); Pointers to pointers C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or even to other pointers). In order to do that, we only need to add an asterisk (*) for each level of reference in their declarations: Syntax: data type * * variable; For example int **x; Void pointer: Syntax: void *variable for example: void *x; The void type of pointer is a special type of pointer; void pointers are pointers that point to a value that has no type. This allows void pointers to point to any data type, from an integer value or a float to a string of characters. Limitation: the data pointed by them cannot be directly dereference (which is logical, since we have no type to dereference to), and for that reason we will always have to change the type of the void pointer to some other pointer type that points to a concrete data type before dereferencing it by using type-castings . For example #include <iostream> using namespace std; void increase (void* data, int size) { switch (size) { case sizeof(char) : (*((char*)data))++; break; case sizeof(int) : (*((int*)data))++; break; } } int main () { char a = 'x'; int b = 1602;

increase (&a,sizeof(a)); increase (&b,sizeof(b)); cout << a << ", " << b << endl; return 0; } Output: y, 1603 Null pointer: A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type. Syntax: data type * variable = NULL or data type *variable = 0 For example int *x = 0 or int *x = NULL:

9) Explain about reference variables in CPP? (s) Ans) Reference Variables: C++ introduces a new kind of variable known as the reference variable. A reference is an alias or an alternative name for an existing variable. All operations applied on reference variables are also applied on original variable. The address of a reference variable is same as the address of the original variable. Reference variable looks like ordinary variable and behaves like pointer variable. A reference variable can be defined as Datatype &ref_varible = ori_varible; All reference variables must be initialized at the time of declaration. Once defined, a reference cannot be reassigned. The following points can be noted about reference parameters. A reference can never be null. It must always refer to a valid object or variable Once defined, a reference cannot be reassigned. A reference does not require any explicit mechanism to dereference the memory address and access the actual data value. For example we can make the reference variable declaration as follows. Datatype & reference name= variable name; float total = 100; float & sum= total; /*total is the float type of variable that has already been declared */ Sum is alternative name or alias declared to represent the variable total. Here both the variables refer to the same data object in the memory. The following statements cout << total; cout<< sum; Both print the value 100 The statement total = total+10; Will change the value of both total and sum to 110 Like wise the assignment statement. Sum = 0; Will change the value of both the variables to0 10) Explain parameter-passing technique in CPP? (E) Ans) Parameter passing mechanisms in C++:The parameters can be passed in 3 ways in C++. They are 1) Call by value 2) Call by address 3) Call by reference Call by value: In C++ by default a function call passes parameters by value In this mechanism the values of actual parameters will be passed to a separate set of variables known as formal parameters The formal parameters of type value parameters Ex :

Any changes made to formal parameters will not affect the corresponding actual parameters . Only one value to be return from function

The following ex: gives an idea of call by value. Here the purpose of the function swap() is to interchange the values of the given 2 variables. But this issue will not be achieved by call by value technique. void main () { void swap (int, int); // function prototype int a=10,b=50; swap(a,b); // function call as call by value cout<<a<<b; } void swap (int x, int y) // function definition. { int t; t=a; a=b; b=t; } The purpose of writing swap is to interchange the variables, but it is not achieved with call by value thus the output is 10 50 Call by address:In C++ it is possible to call a function by passing address this technique is known as call by address. In call by address technique the formal parameters must be a pointer type and they receive the addresses of actual parameters. Any changes to the formal parameters are automatically reflected back to the actual parameters in the main program. It is possible to make a function to return more than one value to the calling program The address can be generated by using address operator & Thus the following is the example for calling a function by passing addresses swap (&a, &b); Thus the following is the function prototype void swap (int *, int *) Thus the complete program of swapping 2 numbers using call by address is as follows. void main ( ) { void swap (int * , int * ); // prototype int a,b; a=50; b=30; swap(&a,&b);/*call by address*/ cout <<a<<b<<endl; } void swap (int*p1, int*p2)/ *Receiving the addresses in pointers*/ { int t; t=*p1; *p2= *p1; *p2=t; } From the above example, it is clear that the main() function can display the swapped values of a and b Call by Reference: The formal parameters must be of type reference When we pass parameters by reference the formal parameters becomes like an alias variable to the formal parameters To pass arguments by reference, the function call is similar to that of call by value. Ex swap(a,b) In the function decelerator the formal parameters are preceded by the & operator. It is possible to return more than one value from a function to the main program Any changes to the formal parameters are automatically reflected back to the actual parameters in the main program. Using this method no duplicate set of variables are crated Hence the complete program of swapping 2numbers using call by reference can be shown as follows. void main ( ) { void swap (int &x, int & y); int a,b; a=50; b=30;

swap(a,b); // function calling. cout<<a<<b<<endl; void swap(int&x, int&y) { int t; t=x; x=y; y=t;

} }

11) Explain about inline functions? (s) Ans) Inline functions: Inline functions are those whose function body is inserted in place of the function call statement during the compilations process. An inline function definition is similar to an ordinary function except that the keyword inline precedes the function definition. The syntax for defining an inline function is as follows inline function- header ( ) { Body of the function; } The inline functions are similar to macros in c language. But the major drawback with macros is that the error checking does not occur during compilation. The following are the situations where inline functions may not work properly 1. Functions returning values, having a loop, a switch or a go to exists 2. If the function contains static variables 3. If inline functions are recursive Benefits: 1. Inline function makes a program to run faster, because the over head of function call and return is eliminated 2. For the small functions it is always convenient to use inline functions. Disadvantages: 1. In line functions may require more memory in the program as they are basically expanded while compiling the program 2. The speed benefits of inline functions diminish as the functions grows in size 3. The inline key word sends a request but not a command to the compiler. Hence the compiler can ignore the request if the function definition is too long The following is an example program for defining inline functions inline float getdata (int a, float b) { return (a+b); } void main () { int a= 35; float b= 18.5; cout <<The sum is <<getdata (a,b); } 12) Explain about function default arguments in CPP? (s) Ans) Default arguments: In c++ default arguments are used to call a function without specifying all of its arguments. Function prototype or function declaration used to declare default arguments. The compiler checks the function prototype with the arguments in the function call to provide default values, if the argument having default value they are omitted . The arguments specified in the function call explicitly always override the default values specified in the function prototype. In the function call all the trailing missing arguments are replaced by default arguments. A default argument can appear either in the function prototype or definition. Once it is defined, it cannot be redefined. Some points regarding default arguments; 1) A default argument is checked at the time of declaration and evaluated at the time of call. 2) We must add the default parameters from right to left. 3) We cannot provide a default parameter in the middle of an argument list 4) Default arguments are useful where some arguments always have the same value For example: float amount (float principle, int period, float rate = 0.15); Note: - principle, period are general formal parameters, rate is Default argument.

The default value of rate is specified similar to a variable initialization. The above prototype declares a value of 0.15 to the default argument rate. For ex: the function call Value= amount (5000, 7); // one argument missing hence default value will be taken. The above function call passes 5000 principle 7 periods Then the function use the default value for rate parameter as 0.15 rates For example the following sample programs give the details. #include <iostream.h> #include<iomanip.h> void main() { void printline(char ch=*, int len=40); // function prototype with default arguments. printline ( ); // missing 2 parameters printline (==);// missing 1 parameter printline (-, 60); // no missing. } void printline (char ch, int len) { int i; for (i=1;i<=len;i++) cout <<ch <<endl; } See the workout example at the end. 13) Explain about Function overloading? (or) Explain about function polymorphism? (E) Ans) Function overloading:Function overloading can be defined as define a set of functions having same name and different signatures . The same function name will be used with different number of parameters and parameters of different type. We can use the same function name to create function that performs a variety of different tasks. This is known as function overloading (function polymorphism) in OOP. The function can perform different operations depending on the argument list in the function call. At the time of calling correct function to be invoked is determinates by checking the number and type of the argument but not on the function return type. For ex an overloaded add( ) function handles different types of data as follows. int int double double double add (int a, int b); // prototype 1 add(int a, int b, int c); // prototype 2 add (double x, double y);// prototype 3 add (int p, double eq); // prototype 4 add (double p, int q); // proto type 5

The following function calls can be given in the program x= add (0.75,5);//uses prototype 5 y= add (5,10,15);// uses prototype 2 z= add (5,10);//uses prototype 1 p= add (12.5,17.5); // uses prototype 3 Q= add (5,12.5); // uses prototype 4 Rules that govern the usage of function over loading 1. The compiler first tries to find an exact match, in which the type of actual parameters are the same and use that function. 2. If an exact match is not found then the compiler converts the arguments as follows. i. char to int ii. float to double iii. int to float or double iv. All these conversions take place to find a match. 3. Some times compiler generate ambiguity errors because the compiler may not be able to decide what signature function should be called. If the conversion is possible to have multiple matches then the compiler generates an error message. Suppose we use the following 2 functions. long square (long n);

double square (double x); A function call such as square (100) will cause an error because int argument 100 can be converted to either long or double. The following is an ex: program that shows the usage of function overloading

#include <iostream.h> #include <iomanip.h> void main() {float area (int r); // over loaded function int area (int l, int b); //over loaded function. float a; int a1,l,b,r , a1 ; cout <<enter the radius of the circle <<endl; cin>>r; a=area(r);

cout << area of the circle is <<a<,endl; cout <<enter the length and breadth of the rectangle; cin>>l>> b; a1= area(l,b); cout<<area of the rectangle is <<a1<endl; } float area (int r) { return (3.141*r*r); } int area (int l, int b) { return (l*b); }

14) What is recursion? Explain? (s) Ans) Recursion: - Calling a function into itself is known as recursion. When a function calls itself, a new copy of that function is run. The local variables in the second version are independent of the local variables in the first, and they cannot affect one another directly. The following are the requirements for writing a program using recursion. 1) The problem must be expressed in recursive nature 2) They should be one terminating condition to break the recursion. 3) We should not make use the iterative looping statements while writing recursive programs. 4) By using backtracking mechanism to evaluate recursive function. The following is an example program for calculating the factorial using recursion #include <iostream.h> #include<iomanip.h> void main() { int n,f; int fact(int n); cout<<"enter n value..."; cin>>n; f= fact (n); cout<<"factorial="<<f<<endl; } int fact (int n) { if (n==0) return (1); else return(n*fact(n-1)); } 15) Differentiate iteration and recursion? (s) Ans) Comparison of iteration and recursion:Any iterative function consists of 4parts. 1) Initialization 2) Decision 3) Computation 4) Update Initialization: - The loop control variable is initialized. And also other predefined variables are initialized. Decision:- The loop variable is compared against some predefined value. If the condition becomes true, it executes the body of the loop. This process will be continued until condition value becomes false. Computation: -The necessary computation is performed with in the loop. Update: - The loop control variable is incremented or decremented to continue the loop. For a recursive function the above 4 parts can be explained as follows. Initialization: - The variables in the form of parameters are passed to the function. Decision: - The arguments are used to determine whether further recursive calls are required or not.

Computation: The necessary computations are performed using local variables and parameters. Update: -The update is done, so that the parameters can be used for further recursive calls.

16) Explain about memory management operators in CPP? (E) Ans) Memory management operators :Memory management means the way of allocating part of a memory to program at their request, and freeing it for reuse when no longer needed. In C++ unary operators new and delete are used to allocate and free the dynamic memory, they are also called as free store operators. new: Pointer variable = new data type; Here pointers variable is a dynamic variable of type pointer. The unary operator new is used to allocate required memory at runtime. There are three stages to allocate required memory they are 1. 2. 3. Locates and reserves storage for the object or objects to be allocated. Initializes the object(s) using class constructor Returns a pointer to the object(s) of a pointer type derived from type-name.

The new operator allocates sufficient memory to hold data and return its address. If the object is of type array it returns the base address of an array. The memory allocated by using new operator is not initialized. If the required amount of memory is not allocated the operator new throws an exception to set_new_handler() function. The memory allocated by using new operator must be released by using delete operator only. Memory leak is cause due to the allotted memory is not released. Ex: 1) int *p,*q; p= new int; q= new int; We can combine the declaration of pointers and their assignments as follows. 2) int *p = new int; float *x = new float; Now we can use the above pointers as follows. *p =15; *x = 18.9; We can also initialize the memory using the new operator as follows 3) int *p = new int (10); Thus *p will contain value 10 We can also create one-dimensional array by using new operator as follows. 4) int *p = new int [10]; The above statement creates a memory space for an array of 10 integers hence p[0] will refer the first element. p[1] to the second element and so on. Delete: When a data object is no longer needed, it is destroyed to release the memory space for reuse. The unary operator delete is used to release the memory allotted by using new operator. The delete operator does not return any value. When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). The general form of delete operator is delete (ptrvarible); Where ptrvaribale is having a dynamic memory allocated using new For example: delete P - If P is a pointer variable then it will be destroyed after executing this statement To free a dynamically allocated array by using delete [size] pointer variable; the size specifies the Number of elements in the array to be free To free all the allocated memory location of an array by using

delete[](pointer variable) In this case it is not required to give the size of the array. At hear the [ ] tell the compiler the released memory is of type pointer. Only one pair of [ ] are sufficient to release memory for any dimension.

17) Difference between structures and class(s) Ans) Structure Structure can be defined as a collection of dissimilar data items. Contains only data member By default all members are public The size of the structure = size of the individual data items of a structure Separate copy of data members are created for all structure variables To create a structure variable use keyword struct It is Not possible to inherit structures Structure are called as Passive data item Class Class can be defined as combination of data items and functionality applied on that data Contains data members and member function applied on that data By default all members are private The size of the structure = size of the individual data items of a class Separate copy of data members and only one copy of member functions are created for class To create a class variable the keyword class is optional It is possible to inherit class Classes are called as Active data items

18) Define class? How to create a class in C++? (Or) What are the Tools for defining ADT? (E) Ans) Class can be defined as combination of data members and member functions applied on that data. It allows the data to be hidden from the external use. A class can also be called as an abstract data type (ADT) Abstract Data Type can be defined as the technique of creating new data types whose implementation details are hidden and can only be handled using the publicly accessible member function. In generally there are three stages to create and use a class they are 1) Class declaration it describes the data types and scope of its members 2) Class function definition it describes how the class functions are implemented 3) Creation of objects it describes how to create variable of type class (ADT) 1. Class declaration: The general form of a class declaration is as follows. Syntax: classclass_name { access specifier: member1; access specifier: member function; ... } [object_name]; for example class a { private; int x public : void show() {cout << a;} };

Where class_name is the name for a class (user defined type) and the optional field object_name is one, or several, valid object identifiers. The body of the declaration can contain members, which can be either data members or member functions. The following are the characteristics of a class The keyword class specifies abstract data type of type class name. The body of a class is enclosed with in braces and terminated by a semicolon The functions and variables with in the class are collectively called as members

The members that have been declared as private can be accessed only from with in the class. Class definition is only a template and does not create any memory space for a class By default all the members are of type private

The following figure shows the data hiding in classes.


Private A rea D ata N o entry Functions

Public A rea D ata Entry A llowed to public area Functions

Accessspecifiers: The access specifier tells the compiler the scope of data members and member function of a class. By default all the class members are treated as private.

1. 2. 3.

private members of a class are accessible only from other members of their same class or from their "friend" classes. protectedmembers are accessible from members of their same class and friend classes, and also from members of their derived classes. public members are accessible from anywhere the class is visible.

Private access specifier provides the data security. This phenomenon is called encapsulation or data hiding It is possible to access private data members of a class using friends, pointer so in C++ if is not possible to provide 100% data security. The scope of the access specifier keyword is up to the appearance of the next access specifier keyword

2) Classfunctiondefinition:Member functions can be defined in two places. 1) Outside the class definition 2) Inside the class definition Memberfunctiondefinedinsidethe classdefinition: Member function definition is similar to a normal function definition except that it is enclosed within the body of a class . By default all the member function defined within the body of a class are treated as inline There is no prototype in this method

Syntax: class classname { private : int age; int setage(int x) {age = x;}

// member function

public: void showage() {cout << age is <<age;} // member function void myfun() { setage(100);} // member function calling another member function }; Memberfunctiondefinedoutsidethe classdefinition: 1. To declare the member function of a class outside the class definition the function prototype declared within the body of a class and defined them out side the body of a class. 2. Member ship identity label (class_name :: ) differentiate member functions and non member function in a program. 3. By default the member function defined outside the class definition is non-inline. 4. To make it inline by explicitly adding inline as prefix to the member function in the definition. syntax class classname { access specifier: return data type functionname(arguments); //declaration }; return data type classname :: functionname(argument) // function definition { function body; } for example: class a { public; void show(); // prototype }; void a:: show() { cout << this is outside the class ; }

Here the membership label class_name:: tells the compiler that the function is the member of the specified class. The scope of the function is restricted to only the objects and other members of the class. To make the member function defined out side the class as an inline by adding inline as a prefix to the member function. Syntax Return data type inline class_name :: function name(arguments) { function body ; } The followingare the propertiesof a memberfunction. Several different classes can use the same function name; the membership label will resolve their scope A class can have multiple member functions with the same name as long as they differ in terms of argument specification (data type or number of arguments) Member functions can access the private data of the class, but a non-member function cannot. A member function can call another member function directly There is no need to used member of operator (.) to access data members or member function of a class within the class definition. 3). Creation of objects: answer Q 19. 19) What is an object? How to create an object? (E) Ans) Objects: Object can be defined as an Instance of a class. The process of creating objects (variables) of the class is called class instantiation. In C++ the class variables are called as objects. The complier allocates required memory for objects. The size of an object is equal to the sum of the sizes of the individual data items of a class. The following is the general syntax of declaring objects. Type1: class class_name ob1,ob2,ob3........obn; Type2: class_name obj1.obj2,obj3,objn;

Where

class_name is the name of the class for which we want to create objects. ob1, ob2,.... obn are the objects of class name.

Accessing class members:To access members of a class using the member off operator dot ( . ) It is not possible to access private data members of a class out side the class definition using dot operator The member access operator is not required to access data members within the class definition. Syntax for accessing members of a class: Access data members: object_name.datamember; Access member functions: object_name.memberfunction(actual_parameters); The following is an example of creating an object of type item and invoking its member function. void main ( ) { item x; // creating an object of type item x. getdata (20,20.5); x put data ( ); } Memory allocation for objects:At the time of creating an object of a class the compiler allocate required amount memory for a class definition. For each object of a class a separate copy of data members and one copy of member functions is created. For each object a separate memory is allocated and the address of that memory is stored in this pointer. By using this pointer the unique copy of member function of all the objects of a class are identified. This pointer is passed automatically to all the member functions of a class. Object 1 Variable 1 Variable 2 Common for all objects Member function -1 Member function -2 20) Explain about static data members, static member functions? (s) Ans) Static data members (or) static member variables:A data member of a class can be qualified as static. A static member variable has the following special characteristics. 1. The static data member can be initialized during their definition outside all the member function, with in the same program. By default static data members are initialized to 0. 2. Only one copy of member variables is created and they are shared by all the objects of that class. No matter how many objects are created. 3. It is visible only with in the class but its scope is with in the entire program. 4. Each static data member must be defined outside the class with the identity label class name ::, before the main ( ) function as follows. datatype class name :: name of the variable ; // static data member definition The static member variables are associated with the class itself, rather than with an object, hence they are also known as class variables. The following is an example program #include <iostream.h> #include<iomanip.h> #include<iostream.h> class sample Object 2 Object 3

class sample { static int a; // declaration public: void getdata (int x) { a=x; } void incr( ) { a=a+1; } void putdata ( ) { cout <<"a="<<a<<endl; } }; int sample::a; void main ( ) { sample x,y,z; x.getdata (10); y. incr (); z.putdata( ); } Static member function:-

static int a; static int b; static int c; public : void getdata (int x,int y) { a=x; b=y; } void multi () { c=a*b; } void putdata( ) { cout<<"a="<<a<<endl; cout<<"b="<<b<<endl; cout<<"a*b="<<c<<endl; } }; int sample:: a;int sample:: b; int sample :: c; void main () { sample x,y,z; x.getdata (10,20); y.multi ( ) ; z.putdata ( ); }

Like static member variables we can also have static member functions. A member function that is declared as static has the following properties. 1) A static member function can have access to only other static members declared in the same class. 2) A static member function can be called using the class name a follows. a. Class_name : : function_name ( ) 3) A static member function also calls the class constructor explicitly. The following program given an idea regarding static member function: #include<iostream.h> class test { int code; static int count ; public: void setcode( ) { code =++ count; } void showcode ( ) {cout<<"objectnumber"<< code<<endl ; } static void showcount ( ) // static member function. { cout <<" count" <<count<<" \n"; } }; int test :: count; void main ( ) { test t1,t2,t3; t1. setcode (); t2. setcode (); test :: showcount ( ); t3. setcode ( ); test:: showcount ( ); t1. showcode ( ); t2. showcode ( ); t3. showcode ( ); } Output: count : 2 count : 3 object number :1object number : 2 object number : 3

21) What is the difference between static member function and non-static member functions? (s) Ans) The differences between a static member function and non-static member functions are as follows. A static member function can access only static member data, static member functions and data and functions outside the class. A non-static member function can access all of the above including the static data member. A static member function can be called, even when a class is not instantiated, a non-static member function can be called only after instantiating the class as an object. A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual A static member function cannot have access to the 'this' pointer of the class.

The static member functions are not used very frequently in programs. But nevertheless, they become useful whenever we need to have functions, which are accessible even when the class is not instantiated. 22) Explain about friend in C++? Or Friend function violate data hiding in C++ Justify your answer? (E) Ans) Friend functions: Friend functions are functions declared out side the class as a non member and behave like a private member of a class. The keyword friend at function declaration within the class makes a non member function as a member of a class. Friend functions can access the private data members of a class out side the class definition. The access specifiers having no control on friends so that it can be declared any ware in the class definition Syntax: Class ABC { -------public; friend void xyz (); //function declaration }; Here the keyword friend should precede the function. Characteristics of friend functions: 1. It is not in the scope of any class, in which it is declared as friend. 2. A friend function cannot be called using the object of that class 3. it can be called directly like a general functions 4. By using an object and dot operator to access data members of a class. 5. It can be declared either in public or private part of the class 6. Usually a friend function receives the object as arguments. The following is an example program using friend function. // friend functions #include <iostream.h> class CRectangle { int width, height; public: void set_values (int, int); int area (void) {return (width * height);} friend CRectangle duplicate (CRectangle); }; void CRectangle::set_values (int a, int b) { width = a; height = b; Crectangle duplicate(CRectangle rectparam) { CRectangle rectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres); } int main () { CRectangle rect, rectb; rect.set_values (2,3); rectb = duplicate (rect); cout << rectb.area(); } out put: 24

}
Friend classes (friend) A friend class is used to share all the data members of a class to its friend class . Define class_1 as a friend of class_2 by putting the word friend in class_2. Class_2 access all the protected and private members of the class_1. Class_1 is friend of class_2 then it is not possible to access any private and protected data members of class_2 from class_1. Friendship is always a one-way relation. Syntax class class_1 { }; class class_2 { friend class_1; }; //one way relation.

Suppose if you want to create a two-way relation between two classes, the keyword friend is placed in both the classes. The second class should be declared as a forward declaration. The classes contain only prototypes of member functions. All the definitions of the member functions are declared after declaring all the prototypes of both the classes. Syntax: class class_2 ; // forward declaration. class class_1 { friend class_2; Member function prototypes; }; class class_2{ friend class_1; Member function prototypes: }; Example: class PartNode{ public: friend class PartList; // declares PartList to be a friend of PartNode }; If you want to expose your private member data or functions to another class, you must declare that class to be a friend. The friendship is a one-way relation i.e. class a is the friend of class b but the class b is not a friend of class a. The friendship is not inherited. // Friend class #include <iostream.h> class CSquare; class CRectangle { int width, height; public: int area (void) {return (width * height);} void convert (CSquare a); }; class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle; }; void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); return 0; } output : 16

23) Define constructor? Explain different types of constructors? (E) Ans) Constructors Constructor is a special member function which is used to initialize the objects of a class at the time of creating objects. This is a special member function because its name is same as the class name and it is not possible to call using member of operator (.). They should be declared in the public section They are invoked automatically when the object is created They do not have return data type; i.e. not even void. Hence they cannot return values. Like other CPP functions they can have default arguments Constructor cannot be virtual We cannot refer the address of constructor. They make use the operator new when memory allocation is required. Constructors cannot be inherited, but a derived class can call the base class constructor. The following is an example of defining constructor class integer { int m,n; public; integer ( ) ; // constructor ---------}; integer : : integer ( )

{ m=0; n=0; } Now for example the following declaration integer i; Creates the object i of type integer and also initializes its data members m and n to zero Types of constructors: 1. Default constructor: Constructor that accepts no parameters is called the default constructor. It is also called as no argument constructor. If no constructor is defined the compiler create default constructor Syntax class <classname> {public: classname ( ){ body;} }; If no such default constructor is defined then the compiler supplies it. 2. Parameterized constructors:The constructors that can take arguments are called parameterized constructors. Using this constructor it is possible to create an object for a specific initial value. The following is an example class integer { int m,n; public; integer(int x, int y); ---------}; integer : : integer (int x, int y) // parameterized constructor { m=x; n=y; } Now we must pass the initial values as argument to the constructor function. This can be done in 2 ways 1) Explicit Call: - integer i = integer (10,20); 2) Implicit Call: - integer i (10,20); The implicit method some times called the short hand method and it is very often used 3. Overloaded constructors (or) multiple constructors in a class : It is possible to have more than one constructor function with in the same class by varying the argument list. This concept allows overloading the constructor function. The following is an example class integer { int m,n; public: integer ( ) // constructor -1 { m=n=0; } integer (int i)// constructor - 2 { m=n=i; } integer (int x, int y) // constructor - 3 { m=x; n=y: } }; Thus the following declaration statements causes the appropriate constructors Integer i; // calls constructor-1 integer i(10); //calls constructor-2 integer i(10,20); // calls constructor -3 The following is an example program to illustrating default constructor, parameterized constructor, and overloaded constructor #include <iostream.h> class complex { private: float x,y; public: complex ( ){x=y=0; } complex (float r) {x=y=r;} complex (float r,float i) {x=r; y=i; } complex sum(complex c1, complex c2) { complex c3; void putdata ( ) { cout<< x<<"+i"<<y<<endl; } }; void main ( ) { complex a,b(10.5),c(10.5,2.5),d,e; d=e.sum (b,c);

c3.x=c1.x+c2.x; c3.y=c1.y+c2.y; return c3; }

d.putdata (); }

4. Constructors with default arguments:It is possible to define constructors with default arguments. For ex. The constructor complex can be defined as follows complex (float real, float imag=0); The default value of the argument imag is zero Then the following statements, complex C(5.0); Assigns the value 5.0 to the real variable and 0.0 to imag by default however the statement/ complex C(2.0,3.0); assigns 2.0 to real and 3.0 to imag. Here the actual parameter 3.0 overrides the default value (0.0) The following is an example program. #include <iostream.h> class complex { private : float x; float y; public :complex ( ) { x=0; y=0; } complex (float real, float imag=5.7) { x=real; y=imag;} complex sum (complex c1, complex c2) { complex c3; c3.x= c1.x+c2.x; c3.y=c1.y+c2.y; return c3; } void putdata ( ) { cout<<x<<"+1"<<y<<endl; } }; void main ( ) { complex a,b(2.5),c(2.8,8.6); a=a.sum(b,c); a.putdata( ); }

5. Copy constructor:A copy constructor is used to declare and initialize an object from another object. In this data members, which are dynamically allocated must be copied to the destination object explicitly. The following is the example for copy constructor of a class integer integer (integer &i); A copy constructor takes a reference to an object of the same class as itself an argument. The following are the examples of invoking a copy constructor integer i1; // default constructor integer i2(i1); // copy constructor integer i2=i1 // copy constructor The process of initializing through a copy constructor is known as copy initialization. In the above examples the i2 object is copy initialized of the object i1 The copy constructor gets invoked when the arguments are passed by value to functions, and when values are returns from functions, or an object is initialized at the time of creation . If a copy constructor is not defined in a class, the compiler itself defines one. The following is an example of using copy constructor #include <iostream.h> class code { private: int d; public: code( ){ } // default constructor code(int a) //constructor -2 { d=a; } code(code &x)//copy constructor { d=x.d; } void display( ) void main( ){ code A(100); //calls constructor - 2 code B(A); //calls copy constructor code C=A; //calls copy constructor code D; //calls no argument constructor D=A;// It is assignment not initialization hence no copy const. will be called A.display ( ); B.display ( );

{ };

cout<<d<<endl; }

C.display ( ); D.display ( ) ; }

6. Dynamic constructors: Dynamic constructors are used to allocate the require memory for the pointer data member of a class at the time of creating objects by the help of new operator. Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The following is an example program. #include <iostream.h> #include <string.h> class string { private: char * name; int length; public: string( ) // constructor -1 { length = 0; name = new char[length+1];//one extra for \0} string (char *s)// constructor - 2 { length = strlen(s); name= new char [length +1];// dynamic memory allocation strcpy(name,s); } void display () { cout<<name<<'\n'; } };

void main () { char*first="baba"; string name1(first), name2("louis"), name3("lagrange"); name1.display(); name2.display ( ); name3.display ( ); }

24) What is destructor? (s) Ans) Destructors: Destructor is a member function of an object that is executed whenever that object goes out of existence. They are used to deallocate memory allocated for an object. Destructors have the same name as their class, prefixed by a tilde ( ~ )symbol. They make use of operator delete to free the dynamically allotted memory of an object. For example the destructor for the class integer can be defined as follows ~integer ( ) { } A destructor never takes any arguments nor does it return any value. When new is used to allocated memory in the constructors, we should use delete to free that memory in the destructor. 25) What is operator overloading? Explain how to achieve operator overloading in c++?(E) Ans) Operator overloading Operator overloading means that redefining the behavior of an operator as per the user requirements i.e. the operator is having a same symbol with different signatures. It is to be achieved by using a special member function called operator. It is a special member function so that there is no need to use member of operator (.) to access these member function using an object of that class. The following are the operators in C++ that cannot be overloaded. OPERATOR MEANING Sizeof ( ) size of operator . Membership operator * Pointer to member operator :: scope resolution operator ?: Ternary (or)conditional operator it is possible to overload operators by using special member function operator or a friend function calling operator member function. The general form of overloaded operator member function is as follows return type class name : : operator op(argument list) { function body //task defined } Where

return type is the type of the value returned by the specified operation. op is the operator being overloaded and op is preceded by the key word operator operator functions must be either non static member functions or friend functions.

The following are the various operator functions prototypes complex operator + (complex c); // member function of a class complex vector operator - (); // member function that is over loading unary minus friend operator + (complex C1, complex C2); // friend function that is over loading binary plus friend int operator == (complex c1, complex c2); // friend function i.e overloading == operator Rules for overloading operators: Only existing operators can be overloaded. New operators cannot be created We cant change the basic meaning of an operator, i.e., we cant redefine the + to subtract one value from the other value. Unary operators overloaded by means of a member function take no arguments and return no values. But unary operators overloaded by means of a friend functions take one reference argument. Binary operators overloaded through a member functions take one argument and those, which are over loaded through a friend function, take 2 arguments. Overloaded operators follow the syntax rules of the original operators. They cant be overridden Binary arithmetic operators such as +, -, *, / must explicitly return a value. There are some operators that cant be overloaded (::, *, . , ?:, sizeof(). Using friend functions to overload >> and << operators The following is an example program of overloading relational operator == to compare the 2 given complex Nos #include <iostream.h> class complex { float x,y; public: complex ( ) {x=y=0;} complex (float real, float imag) {x=real; y=imag; } friend int operator == (complex, complex); }; int operator == (complex c1, complex c2) {if ((c1.x==c2.x) && (c1.y ==c2.y)) return (1); else return (0); } void main ( ) {complex a(2.5, 5.2), b(2.5, 5.3); if (a==b) cout <<"Equal" << endl; else cout <<"Not equal" << endl; }

26) What is inheritance? Explain different types of inheritance? (E) Ans) INHERITANCE (Extending Existing Classes) Reusability is an important feature of OOPS. This can be achieved in C++ by using inheritance. It can be defined as The ability of a class to derive data and behavior from another class or The mechanism of deriving a new class from an old class is called inheritance or derivation The old class is referred to as base class and the new one is called the derived class. The derived class inherits some or all the properties from the base class. The following are the various ways of deriving new classes. Single Inheritance: A B ase class

The mechanism of creating a new class from en existing base class is called single inheritance.
B

D erived class

Multiple Inheritance: -

B ase class

The mechanism of creating a new class from several base classes is called multiple inheritance.
C D erived class

Multilevel inheritance: A B ase class

The mechanism of deriving a class from another derived class is known as multi level inheritance. The following is an example.

D erived class D erived class from the derived class B

Hierarchical Inheritance: The mechanism of deriving more than one derived class from one base class. This process is known as hierarchical inheritance. The following is an example.
B C A Base class

Derived classes

Multipath inheritance: The mechanism of deriving a class from other derived classes, which are, derived from the same base class. The following is an example Grand parent Parent - 1 Child Hybrid inheritance: Parent - 2

A
The mechanism of deriving a new class involving more than one form of inheritance is known as hybrid inheritance

B D

27) What is a derived class? Explain how to create it? (s) Ans) Defining derived classes: - A class that uses inheritance to gain the behavior and data of another ('base') class is called derived class. A derived class is defined by specifying its relation ship with the base class in addition to its own details. The general form of defining a derived class is as follows. Class derived class_name : visibility-mode base-class-name { members of derived class; ----------}; The colon indicates that the derived class name is derived from the base class name. The visibility label is optional and if present it may be either private or public. The default visibility mode is private. If the visibility mode is private then it is said to be private derivation from the base class i.e., the base class is privately inherited by a derived class, public members of base class become private members of the derived class i.e. the base class public members can only be accessed by the member functions of the derived class in this private derivation.

If the visibility mode is public then it is said to be public declaration from the base class i.e. the public members of the base class become the public members of the derived class and hence they can be accessed with the object reference of derived class. In both the cases (public, private derivation) the private members of the base class are not inherited. 28) Explain about single inheritance? (E) Ans) Single Inheritance: - Derive a new class from only one base class is called single inheritance . The object of derived class is having an accessing capacity for both base class and derived class data members. Suppose if the base class members are overloaded in the derived class then the object of the derived class access only the derived class member functions. To access overloaded base class member functions using derived class object by prefixing the class name tag (derived_object.class_name::function). Inheritance only inherits the data members and member function of base class to the derived class. The constructors, destructors are not inherited to derived class. If you create an object of a derived class then first the base class constructor call and then call derived class constructor. Similarly if the object scope is over it first calls derived class destructor and then call base class destructor to destroy the derived class object. Let us consider a simple example to illustrate single inheritance. Consider the following class B as a base class; it contains one private data member, one public data members and 3 public member functions as shown below. class B { int a; // private not inheritable public: int b; // public ready for inheritance void getab ( ) { a=5; b=10; } int geta ( ) { return a;} void showa ( ) { cout <<a = <<a <<endl; } }; Consider derived class D publicly derived from the base class B, the class D contains one private data member and 2 public member functions. class D: public B // public derivation { int c ; public: void mul ( ) { c = b * geta(); } void display ( ) ( cout <<c = <<c <<endl<<b = <<b<<endl<<a = <<a<<endl; } }; Then the object of derived class D is having both class B and D data members. The following main () program shows the usage of single inheritance. void main ( ) { d. mul ( ); d. display ( ); } Output :-

D d; d. getab ( ); d. mul ( ); d. display ( ); d. showa ( ); d.b=20;

c=50 b=10 a=5 c=100

b=20 a=5 a=5

29) Explain about protected visibility label? (s) ns) Protected (Visibility label) :c++ provides a visibility modifier called protected which serve a limited purpose in inheritance. A member variable declared as protected is accessible by the member functions with in its class and any class immediately derived from it. It cannot be accessed by the functions out side these 2 classes. A class can now use all the 3 visibility modes as follows. class sample { private : // optional --------// visible to member functions with in the class protected : //visible to member functions --------// of its own derived class public : // visible to all the functions in the program

--------}; 1) When a protected member is inherited in public mode, it becomes protected in the derived class. 2) A protected member inherited in the private mode derivation, becomes private in the derived class. The following table shows the visibility of inherited members.
D e r i v e dc l a s sv i s i b i l i t y B a s ec la s s v i s i b i l i t y P u b l i cD e r i v a t i o n P r i v a t eD e r i v a t i o n P r i v a t e P r o t e c t e d P u b l ic N o ti n h e r i t e d P r o t e c t e d P u b l ic N o ti n h e r it e d P r i v a t e P r i v a t e

30) Explain about multilevel inheritance? (E) Ans) Multi level inheritance: The mechanism of deriving a new class from existing derived class is called multi level inheritance . The object of the derived class is having a capability to access base class and intermediate base class data members and member functions. Constructors, destructors are not inherited. If you create an object first the base class constructor call and then call intermediate base class constructor and then call derived constructor. Similarly the destructors called in reverse order. If you want to use parameterized constructors the required values are first passed to derived class then to intermediate base class then to base class to create an object. Suppose if the intermediate base class is of type virtual derivation then first intermediate base class constructor executed then the base class then the derived class constructor is executed. If any member function is overloaded in derived class the derived class object call derived class member function, if you call base class member function by using class nametag. The following figure shows.
A Base class

Intermediate class

Derived classes

The class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C. The class B is known as intermediate base class since it provides a link for the inheritance between A & C. The chain ABC is known as inheritance path. A derived class with multi level inheritance is declared as follows. class A {...............}; // Base class class B : public A {...............}; // B derived from A. class C : public B {...............}; // C derived from B. The above process can be extended to any number of levels. Let us consider a simple example. Assume that the test results of a batch of students are stored in 3 diff. classes. The class students store the roll. no. The class test stores the marks obtained in 2 subjects and The class result contains the total marks obtained in the test. The class result can inherit the marks from test class, which in turn can inherit the rno, from student class. This process is nothing but multi level inheritance.

student

Base class

Test

Intermediate class

result

Derived classes

Here is the example program. # include<iostream.h> class student { protected : int rno ; public: void getrno () { cout <<"enter roll no."; cin>>rno; } void putrno () { cout<<"Roll number:"<<rno<<endl; } }; class test : public student { protected :int sub1, sub2; public : void getmarks ( ) { cout<<"enter marks in 2 subjects"; cin>>sub1>>sub2; } 31) Explain about multiple inheritance? (E) Ans)

void putmarks ( ) { cout<< "subject1:"<<sub1; cout<<"subject 2:"<<sub2; } }; class result : public test { private : float total; public: void display () { total= sub1+sub2; putrno ( ); putmarks ( ) ; cout<<"Total:"<<total; } }; void main ( ) { result r; r.getrno( ); r. getmarks ( ); r.display ( ); }

Multiple inheritances: - Multiple-inheritance is a mechanism of deriving a new class from two or more base classes. In multiple-inheritance there will be only one derived class and more than one base classs. The following figure shows how to create multiple-inheritance.
A B C Base class

Derived class

Multiple-inheritance allows us to combine the feature of several existing classes for defining new classes. The syntax of a derived class with multiple base classes is as follows. Class D: Visiblity B-1, Visibility B-2... { .......... Body of D .......... }; Where D-derived class B-1, B-2, base classes and visibility may be either public, protected or private;

Using comma operator to separate the base classes, Suppose if you create an object of a derived class then first it call the constructor of class B-1 and then call constructor of class B-2 then call the constructor of derived class. Similarly the first the destructor of the derived class is called and then call the destructor of the class B-2 and then call destructor of class B-1 to destroy the object of the derived class. The order of calling is always depend on the order of derivation. Suppose if a base class is derived as virtual then at first the virtual class constructor is called then call the remaining class constructor declared in the order. For example: class m { protected : int m; public : void get m( ) { cout<<enter m value ; cin>>m; } }; class N { protected: int n; public : void getn( ) { cout<<enter n value; cin>>n; } }; Now class p is the derived class using multiple inheritance and has the following definition class P: public M, public N { public : void display ( ) { cout<<m=<<m endl; cout<<n=<<n<< endl; cout<<mxn=<<m*n<<endl; } }; Now the extended class p can be exactly given as follows (including the features of class M and class N) class P { protected: int m ;//derived from class M int n;// derived from class N public : void getm ( ); //derived from class M void getn ( );// derived from class N void display ( ); }; Now the main () function, which provides the user interface, can be written as follows void main( ) { P p; p.getm( ); p.getn(); p. display( ); getch( ); } input of the above program; enter m value = 20 enter n value =10 output of the above program m=20 n=10

m*n=200 32) Explain about Hybrid inheritance? (E) Ans) Hybrid inheritance:- The mechanism of deriving a new class from more than one form for inheritance is called hybrid inheritance. In some situations we need to apply 2 or more types of inheritances in the design of our program. For example consider the following hierarchy of classes.
student sports

Test

result

The above example involves the multi level & multiple inheritances. Multilevel inheritance: Student to test to result Multiple inheritance: test, sports to result. The sports class can be defined as follows class sports { protected : float score; public : void getscore ( ) { cout<<enter score; cin>>score; } void put score ( ) { cout <<SCORE=<<score<<endl;; } }; The declaration for the result class can be as follows. class result : public test, public sports { ----------------------}; Now the complete program can be given as follows. #include <iostream.h> class student { protected: int rno; public : void getrno ( ) {cout <<"enter rno"; cin>>rno; } void putrno ( ) { cout<<"ROLL.NO.="<<rno<<endl; } }; class test : public student { protected : int M1, M2; public : void getmarks() {cout<<"enter marks in 2 subjects"; cin>>M1>>M2; } class sports {protected : int score; public: void getscore ( ) {cout <<"enter the score"; cin>>score; } void putscore ( ) { cout <<"SCORE="<<score<<endl; } }; class result : public test, public sports {int tot; public : void display ( ) { tot = M1+M2+score; putrno (); putmarks (); putscore (); cout<<"TOTAL="<<tot<<endl; } }; void main ( )

void putmarks ( ) { cout<<"SUB-1:"<<M1<<endl; cout<<"SUB-2;"<<M2<<endl; } }; 33) Explain about virtual functions? (E) Ans)

result r; r.getrno ( ); r.getmarks ( ); r.getscore ( ); r.display ( );

Virtual functions: A virtual function is a function that can be overridden with specialized implementations in subclasses . A virtual function is a member function of a class, declared using the keyword "virtual". Only the declaration needs the keyword virtual, not the definition. Virtual function should be defined in the public section of a class to realize full potential benefits. Late binding occurs only with virtual functions. A pointer to a derived class object may be assigned to a base class pointer, and a virtual function called through the base class pointer then the right function will be picked up based on what the base class pointer "really" points at. Rules for virtual functions: 1. Run time polymorphism is achieved only when a virtual function is accessed through a pointer to the base class. 2. The virtual functions must be member of some class 3. Virtual functions cannot be static functions. 4. Virtual functions are accessed by using object pointers 5. A virtual function can be friend of another class. 6. A virtual function in a base class must be defined even though it may not be used. 7. The prototypes of the base class version of a virtual function and all the derived class versions must be identical. 8. We cannot have virtual constructors but we can have virtual destructors. 9. While a base pointer can point to any type of derived object, the reverse is not true. 10. If a virtual function is defined in the base class it need not be redefined in the derived class. In such cases base class function will be invoked. // virtual members #include <iostream.h> class Cpolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) { return (0); } }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); }}; int main () { CRectangle rect; CTriangle trgl; CPolygon poly; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; CPolygon * ppoly3 = &poly; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly3->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; cout << ppoly3->area() << endl; return 0;} Out put 20 10 0

34) What is binding? What are the different types of bindings? How late binding is to be achieved in C++?(E) Ans) Connecting a function call to a function body is called binding. When binding is performed before the program is run (by the compiler and linker), its called early binding. When binding occurs at runtime, based on the type of the object is called late binding. Late binding is also called dynamic binding or runtime binding. To accomplish this, the typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in

the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. When you make a virtual function call through a baseclass pointer (that is, when you make a polymorphic call), the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the correct function and causing late binding to take place. Setting up the VTABLE for each class, initializing the VPTR, inserting the code for the virtual function call happens automatically. With virtual functions, the proper function gets called for an object, even if the compiler cannot know the specific type of the object. 35) What is virtual base class? (E) Ans) Virtual base class: The mechanism of deriving a class from other derived classes, which are, derived from the same base class, is called multipath inheritance. An object of multipath inheritance having two sets of grand parent class members. They are one from parent -1 and the other form parent-2. The compiler generates ambiguity in function call if you try to call grand parent members using child object. The duplication of inherited members due to multiple paths can be avoided by making the common base class as virtual base class. Grand Parent Parent - 1 Child For example class grand parent { --------------------}; class parent-1:public virtual grand parent Student { ----------Test Sport ----------}; Result class parent-2 : virtual public grand parent { --------------------}; class child : public parent -1, public parent -2 { // it will contain only one --------------------// copy of members of ----------// grand parent }; When a class is made as virtual base class only one copy of that class is inherited. The key words virtual and public may be used in any order. When declaring a virtual base class, the virtual keyword appears in the base lists of the derived classes. Parent - 2

36). Explain about Multi-path inheritance? (E) Ans). Multi-path inheritance: - The mechanism of deriving a new class from other derived classes, which are, derived from the same base class. The order of calling constructors in Multi-path inheritance is, it first call virtual base class constructor followed by non-virtual constructor of the class derivation order. Destructors are called for in the exact reverse order of constructors. Explicit call to the base class constructor is compulsory when the base class is derived as virtual in any one of the derived classes 'or' the base class must have a no argument constructor. It is not applicable to any other type of derivation. The following is an example.

A B D
Example1: (ambiguity in function calls) #include<iostream.h> #include <conio.h> class a {int x; public: a(int y):x(y) {cout << "a constructor " <<endl;} ~a() {cout << "a distructor " <<endl;} void show() {cout <<"this is a data " << x<<endl;} }; class b : virtual public a {int y; public: b(int t,int x):a(t),y(x) {cout <<"b consturcot " <<endl;} ~b() {cout << "b distructor " <<endl;} void show() {cout << "this is b data "<< y<<endl;} }; class c : virtual public a {int z; public: c(int t,int x):a(t),z(x) {cout << "c constructor " <<endl;} ~c() {cout << "c distructor "<<endl;} void show() {cout <<"this is c data " <<z<<endl;} }; Example 2: (constructor calling) #include<iostream.h> #include <conio.h> class a {int x; public: a(){} a(int y):x(y) {cout << "a constructor " <<x<<endl;} ~a() {cout << "a distructor " <<endl;} }; class b : virtual public a {int y; public: b(int t, int s):a(t),y(s) {cout <<"b consturcot " <<y<<endl;} ~b() {cout << "b distructor " <<endl;} }; class d : public b,public c // public b,c means public b, privte c { public: d(int t, int x):b(t,x),c(t,x),a(t) {cout <<"d constructor " <<endl; ~d() {cout << "d distructor " <<endl;} };

void main() {clrscr(); d a(3,4); a.c::show(); a.b::show(); /* case 1: a.show(); virtual or non virtual or case 2 : a.a::show(); not a public base class of d if you derive class as non virtual this error is cause because all the class having same function name and as per overloading it always calls the derived class function ; */ a.a::show(); // working because it is virtual derivation }

class c : public a {int z; pu c(int t, int s):a(t),z(s) {cout << "c constructor " <<z<<endl;} ~c() {cout << "c distructor "<<endl;} }; class d : public b,c {int p; public: d(int t,int s, int r):b(t,s),c(t,r),p(r) {cout <<"d constructor " <<p<<endl;} ~d() {cout << "d distructor " <<endl;} }; void main() {clrscr(); d a(1,2,3);}

37) What is pure virtual function? Explain? (s) Ans) Pure virtual function:The virtual function having no body and initialized to zero is called pure virtual functions. A pure virtual function declared in a base class has no implementation as far as the base class is concerned. The classes derived from base classes having a pure virtual function have to define such a function or re-declare it as a pure virtual function. A class containing pure virtual function is called abstract classes or pure abstract

classes. Where as all other classes without pure virtual function and which are instantiated are called as concrete classes. Syntax: virtual return type function name (arguments) = 0 ; A pure virtual function is an unfinished placeholder that the derived class is expected to complete. The following are the properties of pure virtual functions: A pure virtual function has no implementation in the base class hence, a class with pure virtual function cannot be instantiated,. It acts as an empty bucket (virtual function is a partially filled bucket) that the derived class is supposed to fill A pure virtual member function can be invoked by its derived class. 38) Explain about abstract base class? (s) Ans) Abstract base classes: An abstract base class is a class that contains at least one pure virtual function. It is not possible to create an object of ABC but we can create pointers. ABC is used to represent some form of common functionality, but cannot really implement this functionality with respect to the base class. The derived class must implement the pure virtual function to utilize ABC. For example:

Polygon rectangle triangle

Abstract base class

Here we are not at all creating the objects of polygon class but it is possible to manipulate the members of polygon class with the object of triangle class. This is because of the multi level inheritance. // virtual members #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b){ width=a; height=b; } virtual int area (void) =0; }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; return 0; } Output 20 10

39) Explain how a derived class constructor is invoked? (E) Ans) Constructors in derived classes: - The constructors play an important roll in initializing objects. The constructors of base classes will not be inherited into derived classes and hence to invoke the base class constructors a separate mechanism will be used.

If any base class contains a constructor with one or more arguments, then it is compulsorily to have a constructor in the derived class otherwise it is optional to specify the constructors in the derived class. When the program execute first it execute base class constructor and then the derived class constructor. In the case of multiple inheritances, the base classes are constructed in the order in which they appear in the declaration of the derived class. The general form of defining derived constructor is as follows. Derived constructor (arglist 1arglist 2,arglist D) :base 1 (arglist 1), base 2 (arglist 2), . base n (arglist n) { body of derived constructor }; Here the derived class takes the responsibility of supplying initial values to its base classes. The constructor of the derived class receives the entire list of values and passes them to the base class constructors in the specified order. In the above general form, the header of derived constructor function contains 2 pairs separated by a colon. The first part provides (before clan) the declaration of the arguments and the second part contains the function calls to the base constructor. In the above general form arglist-1 to arglistn are the argument declarations for the base constructors base1 through base n. arglist D provides the parameters that are necessary to initialize the members of the derived class. The following is an example D (int a1, int a2, float b1, float b2, int d1) : A(a1, a2), B(b1, b2) { d=d1; } Here A(a1,a2) invokes the base constructor A and B(b 1,b2) invokes another base constructor B. The following is an example of creating the object of derived class D x (5, 12, 2.5, 7.5, 30); Now the parameters will be assigned as follows 5 a1 12 a2 2.5 b1 7.5 b2 30 d1 Now the following table gives the execution of base class constructors. Method of inheritance 1) class B : public A { -------}; 2) class A : public B, public C { --------------}; 3) class A : public B, virtual public C { --------------}; The following is an example program # include<iostream.h> class alpha class gama : public beta, public alpha // multiple inheritance. Order of execution A ( ); base constructor B ( ); derived constructor

B ( ); base (first) C ( ); base (2nd) A ( ); derived (3rd)

C ( ); virtual base (1st) B ( ); ordinary base (2nd) A ( ); derived (3rd)

{int x; public: alpha (int i) {x=i; cout<<"alpha is intialized"<<endl; } void showx ( ) {cout<<"x="<<x<<endl;} }; class beta {float y; public : beta (float J) { y=J; cout<<"bata is initialized"<<endl; } void showy ( ) { cout<<"y="<<y<<endl; } };

{int m,n; public : gama (int a, float b, int c, int d) : alpha (a), beta (b) {m=c; n=d; cout<<"gama is initialized"<<endl; } void showmn ( ) { cout<<"m="<<m<<endl; cout<<"n="<<n<<endl; } }; void main ( ) { gama g (5,10.75, 20, 30); g.showx ( ); g.showy ( ); g.showmn ( ); } Output: beta is initialized alpha is initialized gama is initialized x=5 y=10.75 m=20 n=30

40) Explain this pointer? (s) Ans) this pointer :- this pointer holds the address of the instantiated object. The member functions use this pointer to access the data members of a class. Internally, the address in this pointer is passed to the member functions through the global ecx register of the microprocessor. this pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class. this pointer is not counted for calculating the size of the object. this pointers are not accessible for static member functions. this pointers are not modifiable.

For example the function call A.max () will set the pointer this to the address of the object A this pointer is automatically passed to a member when it is invoked. That is this pointer act as an implicit argument to all the member function. Consider the following example class ABC {int a; public : void getdata (int x) { this.a=x; } }; in the above example private member variable a can be used directly inside a member function as follows. a=x; But internally it will be converted to the following form using this pointer as follows this.a=x; One important application of this pointer is to return the object it points to. For example the statement return & this; return the current object address.

The following is an example program of using this pointer # include<iostream.h> # include<iomanip.h> # include <string.h> class person { char name [20]; void main ( ) { person p1 ("Jophn", 37.5); person p2 ("Ahmed", 29.0); person p3 ("Hebba", 40.25);

float age; public : person (char *s, float a) { strcpy (name,s); age =a; } person & greater (person &x) { if (x.age>=age) return x; else return * this; } void display ( ) {cout<<"NAME="<<name<<endl; cout<<"AGE="<<age<<endl; } };

person p4; p4=p1.greater (p3); cout<<"elder person is"<<endl; p4.display (,0 ); p4=p1. greater (p2); cout<<"elder person is"<<endl; p4.display ( ); } Out put :elder person is NAME : Hebba AGE : 40.25 elder person is NAME : John AGE : 37.5

41) Explain virtual destructor? (s) Ans) Virtual destructor: Destructor is a member function of an object that is executed whenever that object goes out of existence . Suppose in up casting (i.e. when a derived class object pointed by base class pointer) by deleting base class pointer only call base class destructor. It never calls derived class destructor so that it create a memory leak. To make the destructor to call derived class destructor by making the base class destructor as virtual. A virtual destructor is not overridden when redefined in a derived class but it is extends its feature to derived classes. The lower-most destructor (derived class) first invokes the destructor of its base class and then calls the derived class destructor. Syntax; For example: virtual ~classname() {}

#include <iostream.h> class father { public:father () {cout << "father constructor "<<endl;} virtual ~father() {cout << "father destructor : " <<endl;} }; class son : public father { public: son() {cout << " son constructor "<<endl;} ~son() {cout <<"son destructor "<<endl;} };

void main() { father *fp; fp = new father; delete fp; cout << "this is test in reverse " <<endl; fp = new son; delete fp; } output father constructor father destructor this is test in reverse father constructor son constructor son destructor father destructor

42) What is polymorphism? Explain? (E) Ans) POLYMORPHISM; - Polymorphism is one of the important features of object oriented programming language. It can be defined as one name-multiple forms. The polymorphism can be divided into 2 types depending on the binding time. They are compile time polymorphism and runtime polymorphism

Polymorphism Compile time Polymorphism Function overloading Operator overloading Run time Polymorphism Virtual functions

Compile time polymorphism:- compile time polymorphism is implemented by using the overloaded functions and operators. The overloaded member functions are selected for invoking by matching arguments both type and number. This information is known by the complier to select the appropriate function at the compile time. This is called early binding or static binding or static linking and is also known as compile time polymorphism. Note: - Early binding simply means that an object is bound to its function call at compile time. Run time polymorphism: - Run time polymorphism achieved by using virtual functions. In this case the function is linked with a particular class at run time. This process is known as late binding. It is also known as dynamic binding, because the selection of appropriate function is done, dynamically at run time. Virtual functions (implementing run time polymorphism) ;1. Polymorphism is the ability to refer to objects of different classes. 2. A single pointer variable may be used to refer (base class pointer) to the objects of different classes. 3. A base pointer even made to contain the address of a derived class, but it always executes (links) the functions in the base class. 4. By using virtual functions to make the compiler to ignore the type of the pointer and choose the member function that matches the type of the object. . 5. When we use the same function name in both the base and derived classes the function in base class is declared as virtual C++ determines which function to use at run time, based on the type of the object pointed to by the base pointer rather than the type of the pointer. The following is an example program of using virtual function. #include <iostream.h> class base { public : void display ( ) { cout<<"base display"<<endl; virtual void show ( ) { cout<<"base show"<<endl; }; class derived : public base { public : void display ( ) { cout<<"derived display"<<endl; void show ( ) { cout<<"derived show"<<endl; }; void main ( ) { base b; derived d; base *p; p=&b; p->display( ); p->show ( ); p=&d; p->display ( ); p->show ( ); } Output :base display base show base display derived show

} }

} }

43) Explain about C++ manipulators? (E) Ans) Manipulator functions: Manipulators are special functions that are specifically designed to modify the working of a stream. They can be embedded in the i/o statements to modify the form parameters of a stream. there can be more than one

manipulator in a statement and they can be chained. The main advantage of using manipulator function is that they facilitate the formatting of input and output stream. Manipulators are categorized into two types. Non-parameterized manipulators Parameterized manipulators Non-parameterized manipulators are dec, hex, oct, ws, endl,ends,flush Parameterized manipulators: setw(int width), setprecision(int prec), setfill(int fchar), setbase (int base), setiosflags(long flags), resetiosflags(long flags). The following are the list of standard manipulators. To carry out the operations of these manipulator functions in a user program, the header file input and output manipulator <iomanip.h> must be included. endl: the endl is an out put manipulator to generate carriage return or line feed character. The endl may be used several number of times in a c++ statement For example: 1. cout << a << endl; A program to display a message on tow lines using the endl manipulator and the corresponding output is given below #include <iostream.h> void main() { cout << this is the test <<endl; cout << program ; } output this is the test program The endl is same as the non-graphic character to generate line feed (\n) setbase(): the setbase() manipulator is used to convert the base of one numeric value into another base. Following are the common base converters in C++ dec decimal base (base 10) hex hexadecimal base (base 16) oct octal base (base 8) In addition to the conversion facilities such as bases like dec, hex, oct, the setbase manipulator is also used to define the base of a number as a numeric value. The prototype setbase() manipulator is defined in the iomanip.h header file and it should be included in user program. The hex, dec, oct manipulators change the base of inserted or extracted integer values. The original default manipulator for stream input and output is dec. Example The program to show the base of a numeric value of a variable using setbase manipulator function #include <iosteam.h> #include <iomanip.h> void main() { int value; cout << enter the values <<endl; cin >> value; cout <<decimal base = << setbase(10)<< value <<endl; cout << hexadecimal base = <<setbase(16) <<value <<endl; cout << octal base <<setbase(8) <<value <<endl; } setw() The setw() stands for the setwidth. The setw manipulator is used to specify the minimum number of character positions consumed on the output field of a variable. The general format of the setw manipulator function is setw(int w) This changes the field width to w, only for the next insertion. The default field width is 0 For example: cout << setw() <<a <<endl cout << setw(10) <<a <<endl; setfill() The setfill() manipulator is used to specify a different character to fill the unused field width of the value.

The general syntax of the setfill(n) manipulator is setfill(char f) Which changes the fill character to f. the default fill character is a space. For example setfill(*) // fill a asterisk(*) character. setprecision(int prec) : sets the precision used for floating point output. The number of digits to be shown after the decimal point is given by the integer prec. For example: #include <iostream.h> #include <iomanip.h> void main() { float f = 123.23456; cout << setprecision(3) << f <<endl; } out put : 123.234 44) Explain about cpp file stream hierarchy? (E) Ans)

IOS ISTREAM
STREAMBUF

IOS OSTREAM
IOSTREAM.H

IFSTREAM

FSTREAM
FSTREAMBASE

OFSTREAM

FILEBUF
FSTREAM.H

Ios: input output stream file. It is also called as stream base class. Ifstream: ifstream class is derived from ios base class. It is called as input stream class. get(), getline() are the members of ifstream class Ostream: ostream is a class derived from the base class ios. It is called as output file stream class. . put(), putline() are the members of ostream class Filebuf : filebuf is also called as file buffer class which sets the file buffer to read and write data. It contains constant openprot used in open() of file stream class. It also contains close () as members. Fstreambuf: fstreambuf is also called as file stream buffer. This supports operations common to the file streams. It serves as a base class for the derived classes ifstream, ofstream and fstream and contains open() and close() as member function Ifstream: ifstream is also called as input file stream class, which supports input operations. It contains open() with default input mode and inherits get(), getline(). Read (), seekg(), tellg() functions from fstream class Ofstream: ofstream is also called as output stream which supports output operations. It contains open() with default output mode and inherits putg(), seekp(), tellp() and write() function from ostream class. Fstream: fstream is also called as file stream, which supports simultaneous input and output operations. It contains open with default input mode and inherits all the functions from ifstream and ofstream classes through iostream. 45) Explain how to create file stream CPP? Or Explain about file operation in CPP? (E) Ans)

File is a collection of records and record is a collection of data items. These data items may be any one of the valid information. File stream is a stream of information passing between i/o devices. This information may be a data or may be an object of a class.

Open a file stream: In c++ a file stream can be created in two ways they are 1. using constructor of a stream class 2. using class member function open() Opening file-using constructor of a stream class Syntax: stream class name file_handle (file name ); Ex : fstream file(abc.txt);

Hear stream class is any one of the fstream, ifstream, ostream File_handle is the file control object of class type; file name is any one of the valid file name with extension. The size of the file name is only 8 characters and an extension of 3 characters in DOS. It is varied in other OS. In this method the constructor of a stream class is called to create a particular stream and binds to a filename. It opens an appropriate file stream with a required format and binds to file name. Prototype of file stream class constructor: Ifstream class constructor: Ifstream(const char *path, int mode =ios::in, int prot = filebuf::openprot); ofstream class constructor: ofstream(const char *path, int mode =ios::out, int prot = filebuf::openprot); fstream class constructor: fstream(const char *path, int mode =ios::in|ios::out, int prot = filebuf::openprot); Hear Path: path represents path of a file followed by file name the path is not required if you create a file in the current directory. Mode: it specifies the mode in which the file is to be opened. The argument may be specified by, using enumerated constants declared in the ios class Prot: it specifies the access permission. It is not used if ios::nocreate is used in mode. The default permissions are set in the static variable filebuf:::openprot for both read and write permissions the access permission can be read only (S_IREAD) or write only (S_IWRITE). Opening the file Using class member function open() Syntax: stream class name file_handle; file_handle.open(file name ); In this method first it creates an object of the class and later by using the member function open () to open a file stream belongs to that stream. This mechanism is generally used when different files are to be associated with the same object at different times.

Close a file stream: In CPP all the opened file streams are to be close by using the member function close (). If the opened file stream is not closed by a user explicitly the destructor of a file stream class closes the file stream.

Write data to file stream: Syntax: file_handle << data item; For example file << this is test file <<endl;; file << 3434; in this file is a file handle object to a file stream class and the << operator indicated that it is an output operation to disk. It is possible to write any amount of data to file. These files are called as text files. At a time only one char, one line or value of one variable to be written on disk. It is not possible to write objects. After writing data on disk the file_handle pointer increment to next storage location of a file automatically. Read data from the stream: Syntax: file_handle >> variable; For example: file >> x; where x is variable; in this file is a file_handle object to a file stream class and the >> operator indicates that it is an input operation from disk. It is possible to read one character or one line of data at a time. After each successful data reading the file handle pointer increment automatically to the next accessible location of a file. End of file (eof) Syntax: file_handle.eof(); To read a data from a disk file you have to check weather it is reaching end of the stream or not. If you not check this it is not possible to terminate the data reading. To find the end of file marker using the function eof(). eof() function return 1 it reaches to the end of file other wise it return 0. For example: #include <fstram.h> void main() { ostream file(test.txt); // write data to disk file << this is test prgroma <<endl; file << this is stored in test.txt file under current directory <<endl; file.close. istream file (test.txt); char line[80]; while(!file.eof() ) { file.getline(line,0); // read one line at a time cout << line <<endl; } file.close; } 46) What are the different ways of opening a file in CPP? (Or) What are the different file opening modes of streams? (E) Ans) The following table shows different ways of opening a file in CPP.

Name ios::in ios::out ios::app ios::ate ios::trunc

Description Open file to read Open file to write All the date you write, is put at the end of the file. It calls ios::out All the date you write, is put at the end of the file. It does not call ios::out Deletes all previous content in the file.

ios::nocreate ios::noreplace ios::binary

(empties the file) If the file does not exists, opening it with the open() function gets impossible. If the file exists, trying to open it with the open() function, returns an error. Opens the file in binary mode.

Opening a file in ios::out mode also opens it in the ios::trunc mode by default. If the file already exists. It is truncated. ios::app sets pointers to the end of file, it allows to add data from the end-of-file, . File is created if it is non-existent. Where as ios::ate mode allows to add or modify the existing data any where in the file. file is created if it is non-existent. The mode ios:: app can be used only with output files. The stream classes ifstream and ofstream open files in read and write modes respectively by default For fstream class the mode parameter must be explicitly passed More than one value may be ORed to have a combined effect. For example the following statement opens a file for reading in binary mode. Istream file ()test.txt, ios::in|ios::out);

47) Explain about Binary files in CPP? (E) Ans) Binary file is a file containing information that is in machine-readable form; it can be read only by an application. Binary files usually use all 8 bits of each byte for read/write information. Text files usually use only 7 bits, leaving the 8th bit as 0. To create binary files in c++ by using special member functions to read and write data sequentially are write and read. The first one (write) is a member function of ostream , also inherited by ofstream . And read is member function of istream and it is inherited by ifstream . Objects of class fstream have both member functions. Their prototypes are: istream &read(char *buf, streamsize num); ostream &write(const char *buf, streamsize num); Where buffer should be an array of chars (address of a memory block), used to read or write data from where the data to be written are taken. The size parameter is an integer value that specifies the number of characters to be read/write from/to the buffer. Buffers and Synchronization When we operate with file streams, these are associated to a buffer of type streambuf . This buffer is a memory block that acts as an intermediary between the stream and the physical file. For example, with an out stream, each time the member function put (write a single character) is called, the character is not written directly to the physical file with which the stream is associated. Instead of that, the character is inserted in the buffer for that stream. When the buffer is flushed, all data that it contains is written to the physical media (if it is an out stream) or simply erased (if it is an in stream). This process is called synchronization and it takes place under any of the following circumstances:

Whenthe file is closed: before closing a file all buffers that have not yet been completely written or read are synchronized. When the buffer is full: Buffers have a certain size. When the buffer is full it is automatically synchronized. Explicitly with manipulators: When certain manipulators are used on streams synchronization takes place. These manipulators are: flush and endl . Explicitly with function sync(): Calling member function sync() (no parameters) causes an immediate syncronization. This function returns an int value equal to -1 if the stream has no associated buffer or in case of failure.

For examples, we assume a struct WebSites with two members as follows.

// Struct for C++ File I/O binary file sample struct WebSites { char SiteName[100]; int Rank; }; Write operations in C++ Binary File I/O: There are some important points to be noted while doing a write operation. The file has to be opened in output and binary mode using the flags ios::out (output mode) and ios::binary( binary mode) The function write takes two parameters. The first parameter is of type char * for the data to be written and the second is of type int asking for the size of data to be written to the binary file. File has to be closed at the end. // Sample for C++ File I/O binary file write void write_to_binary_file(WebSites p_Data) { stream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app); binary_file.write((char *)(&p_Data),sizeof(WebSites)); binary_file.close(); } The above C++ File I/O binary sample function writes some data to the function. The file is opened in output and binary mode with ios::out and ios::binary. There is one more specifier ios::app, which tells the Operating system that the file is also opened in append mode. This means any new set of data will be appended to the end of file. Also the write function used above needs the parameter as a character pointer type. So we use a type converter (char * ) to typecast the structure into char* type. Read operations in C++ Binary File I/O: This also has a similar flow of operations as above. The only difference is to open the file using ios::in, which opens the file in read mode. // Sample for C++ File I/O binary file read void read_from_binary_file() { WebSites p_Data; fstream binary_file("c:\\test.dat",ios::binary|ios::in); binary_file.read((char *)(&p_Data),sizeof(WebSites)); binary_file.close(); cout<<p_Data.SiteName<<endl; cout<<"Rank :"<< p_Data.Rank<<endl; } Most of the programs will usually go for ASCII text mode files only. But there will be some occasions where the C++ File I/O with binary files will be very useful.

Example 1: Using get() and put() #include <fstream.h> void main() { fstream File("test_file.txt",ios::out | ios::in | ios::binary); char ch; ch='o'; File.put(ch); //put the content of ch to the file File.seekg(ios::beg); //go to the beginning of the file

File.get(ch); //read one character cout << ch << endl; //display it File.close(); }

Example 2: Using read() and write() #include <fstream.h> #include <string.h> void main() { fstream File("test_file.txt",ios::out | ios::in | ios::binary); char arr[13]; strcpy(arr,"Hello World!"); //put Hello World! into the array File.write(arr,5); //put the first 5 symbols into the file- "Hello" File.seekg(ios::beg); //go to the beginning of the file static char read_array[10]; //I will put the read data, here File.read(read_array,3); //read the first 3 symbols- "Hel" cout << read_array << endl; //display them File.close(); } 48) What is template? Explain class templates? (E) Ans) Templates: - A template can be used to create a family of classes or functions . A template can be considered as a kind of Marco. Template can be defined as class or function parameterized by a set of type parameters, values, or templates. The type parameters in the template definition are replaced by specified data type at runtime. The templates are some times called parameterized classes or functions. Class templates: Class template is a class parameterized by type parameters, values, or templates . To utilize the class template the template arguments must be passed at the time of instantiation. The following is the general form of defining class templates. template <class T> class name { class member specification with anonymous type T where ever appropriate. }; A class created from a class template is called a template class. The syntax of defining an object of a template class is as follows. class name <data type> object; The process of creating a specific class from a class template is called template instantiation. The following is an example program.

# include <iostream.h> # include <iomanip.h> template <class T> class vector { T a [50]; T temp; int i,j,n; public void getdata ( ) { cout<<enter how many no.s; cin<<n; cout<<enter<<n<<items; for (i=0, i<n;i++) cin >>a [ i ]; } void sort ( ) {for (i=0, i<n-1; i++) for (J=i+1;J<n;J++) if (a[ i ] > a[ J ]) {temp = a [ i ]; a[ i ] = a [ j ];a [ J ] = temp; }} 49) Explain about function templates? (E) Ans)

void display ( ) { cout<<The sorted array is; for (i=0; i<n;i++) cout<<a [ i ]<<\t; } }; void main ( ) { vector <int> x; vector <int> y; cout<<Item type is int:<<endl; x. getdata ( ); x. sort ( ); x. display ( ); cout<<Item type is float:<<endl; y. getdata ( ); y. sort ( ); y. display ( ); getch ( ); }

Function templates: Function template can be defined as a template that defines an unbounded set of related functions. or Function templates are functions that are parameterized by set of type parameters to represent a family of functions .Function templates can be used to create a family of functions with different argument types. The general format of a function template is as follows. template <class T> reurn type function name (arguments of type T) { --------------body of function with type T where ever Appropriate } We must use the template parameter T wherever necessary in the body. The following example program gives an idea. # include <iostream.h> template <class T> T big (T x, T y) { if (x<y) return x; else return y; } void main ( ) { float a,b; int p,q; double m,n; cout<<"enter 2 integers"; cin>>p>>q; cout<<"big="<<big (p,q) <<endl; cout<<"enter 2 floats"; cin>>a>>b; cout<<"big="<<big(a,b)<<endl; cout<<"enter 2 doubles"; cin>>m>>n; cout<<"big="<<big (m,n)<<endl; }

A function generated from a function template is called a template function. In the above example big is a template function.

50) Explain about template parameters? (s) Ans) Template Parameters 1. C++ templates allow one to implement a generic Queue<T> template that has a type parameter T. T can be replaced with actual types 2. C++ allows you to specify a default template parameter 3. Default arguments cannot be specified in a declaration or a definition of a specialization. 4. A type-parameter defines its identifier to be a type-name in the scope of the template declaration, and cannot be re-declared within its scope (including nested scopes). 5. The value of a non-type-parameter cannot be assigned to or have its value changed. 6. A template-parameter that could be interpreted as either a parameter-declaration or a type-parameter is taken as a type-parameter

DATA STRUCTURES 1). Define data structure? Explain classification of data structures?(E) Ans). Definition: Collection of data elements items organized in a specified manner and a set of functions to store, retrieve and manipulate the individual data elements. Or The way of representing data internally in the memory is called data structure Or A data structure is a way of storing data in a computer so that it can be used efficiently

D a ta S tru c tu re s S im p le D a t a S t r u c t u r e s C o m p o u n d D a ta S tru c tu re N o n - L in e a r D a ta S t r u c u tr e s T re e G ra p h

L in e a r D a t a S t r u c t u r e s S ta c k Q ueue L is t s

Data structures can be classified as Simple data structures Compound data structures Linear data structures Non linear data structures Simple Data Structures: Simple data structures can be constructed with the help of primitive data structures. A primitive data structure is the one, which is used to represent the standard data types of any one of the computer languages. Variables, arrays, pointers, structures, unions, etc. are examples of primitive data structures. Compound Data structures: Compound data structure can be constructed with the help of any one of the primitive data structures and it is having a specific functionality. They are normally designed by user. Compound data structures can be further classified as 1) Linear data structures 2) Non-linear data structures. Linear data structures: Collection of nodes which are logically adjacent in which logical adjacency is maintained by pointers (or)

Linear data structures can be constructed as a continuous arrangement of data items in the memory. It can be constructed by using any one of the primitive data structures of type array. In the linear Data Structures the relation ship of adjacency is maintained between the Data items. Functionally / operations applied on linear data structures; The following list of operations applied on linear data structures. 1. 2. 3. 4. 5. Add an element Data an element Traverse Sort the list of elements Search for a data element

By applying one or more functionalities to create different types of data structures For example stacks, Queues, tables, list, and linked lists. Non-linear data structures: Non-linear data structures can be constructed as a collection of randomly distributed set of data item joined together by using a special pointer (tag). In non-linear Data structures the relationship of adjacency is not maintained between the Data items. Functionally / operations applied on linear data structures; The following list of operations applied on non-linear data structures. 7. Add an element 8. Data an element 9. Display the elements 10. Sort the list of elements

11. Search for a data element By applying one or more functionalities and different ways of joining randomly distributed data items to create different types of data structures. For example Trees, Graphs and forests 2). Explain about stack data structure? (E) Ans). Stacks: Stack is a data structure that works on the principle Last In First Out (LIFO). The last element put on the stack is the first element that can be taken off. Insertion and deletion can be takes place at one end called TOP. It looks like one side closed tube. The insertion operation of the stack is called push operation The deletion operation is called as pop operation. Push operation on a full stack causes overflow. Pop operation on an empty stack causes underflow. Stack pointer is a pointer, which is used to access the top element of the stack. If you push an element that is added at the top of the stack; in the same way when we pop the element the item at the top of the stack is deleted. For example the following figures give an idea about the stack.

Fig 01
3 2 1 0 Stack with 4 locations SP = -1 3 2 1 0

Fig 02
3 14 13 12 2 1 0

Fig 03
3 2 1 12 0

Fig 04
18 18 17 16 12

Stack with 4 locations SP = 2

Stack with 4 locations SP = 0

Stack with 4 locations SP = 3

From the above fig 01 it is clear that the size of the stack is 4 locations and sp = -1 indicates that the stack is empty and we can push the new items into the stack. Now the fig 02 shows how the stack grows, when we push an element 12, 13, 14 into the stack. The fig 03 shows the status of the stack after popping 2 times. Now performing (one more) pop operation one more time on the above stack causes an error known as stack under flow. The fig 04 shows the content of the stack after pushing 16, 17, 18, and 19. If you try to add one more element stack generate error stack over flow. Operations of stack: There are two operations applied on stack they are 1 push 2. pop. While performing push & pop operations the following test must be conducted on the stack. 4) Stack is empty or not 5) Stack is full or not Push: Push operation is used to insert a new element in to the stack. At the time of insertion first check the stack is full or not. If the stack is full it generates an error message stack overflow. Pop: Pop operation is used to delete an element from the stack. At the time of deletion first check the stack is empty or not. If the stack is empty it generates an error message stack underflow. Assumptions: sp stack pointer whose initial value is -1 max_stack is the size of the queue stack[] is an array Element is the element to be added or deleted Algorithm to push an element into the stack :-

step :- 1) start step :- 2) take the element to push into stack step :- 3) If (Sp == max_stack) display The stack is full else Sp = Sp+1 stack [Sp] = item step :- 4) return to main program Algorithm to pop an element from the stack :step :- 1) start step :- 2) if (Sp == -1) display stack is empty else element = stack[Sp] Sp = Sp -1 step :- 3) return element Implementing stacks using arrays is at end of the tutorial

Implementation using linked list is at end of the tutorial


3). Write about the applications of stack data structure? (s) Ans). Application of stacks :The linear data structure stack can be used in the following situations. 1. It can be used in function calls. 2. Implementing recursive functions in high level languages 3. Converting and evaluating expressions. Function calls: A stack is useful for the compiler/operating system to store local variables used inside a function block, so that they can be discarded once the control comes out of the function block. Recursive functions: The stack is very much useful while implementing recursive functions. The return values and addresses of the function will be pushed into the stack and the lastly invoked function will first return the value by popping the stack. Representation of expressions :In general there are 3 kinds of expressions available depending on the placement of the operators & operands. 1) Infix expression :- It is the general notation used for representing expressions. In this expression the operator is fixed in between the operands Ex: a + bc 2) Post fix expression :- (Reverse polish notation) In this expression the operator is placed after the operands. Ex : abc+ 3) Prefix expression :- (Polish notation) In this expression the operators are followed by operands i.e the operators are fixed before the operands Ex : +abc All the infix expression will be converted into post fix notation with the help of stack in any program The stack will be useful in evaluating the postfix expressions also. 4). Write an algorithm to evaluate postfix expression? (E) Ans). Algorithm for evaluating post fix expression using stacks :-

step :- 1 step :- 2 step :- 3 step :- 4 step :- 5 step :- 6 step :- 7 step :- 8 step :- 9

start scan the given post fix expression from left to right and repeat the following steps until the end of the expression. If operand is found push it into the stack Repeat the step 3 until the operator is found If operator is found then pop the stack 2 times OP2 = pop ( ) OP1 = pop ( ) Perform the specified operation on the popped operands Push the intermediate result obtained back into the stack Repeat the above steps until the end of the expression pop the stack to obtain the final result

The program to evaluate postfix expression at the end of the tutorial 5). Write an algorithm to convert the given infix expression to postfix expression? (E) Ans). Algorithm to convert infix to post fix expression: assumptions The string is a syntactically correct postfix expression No unary operators are present No exponentiation operators are present Operands are single lowercase letters that represent integer values Steps 1. for (each character ch in the infix expression) { 2. switch (ch) { i. case operand: // append operand to end of PE 1. postfixExp = postfixExp + ch 2. break ii. case '(': 1. aStack.push(ch) 2. break iii. case ')': 1. while (top of stack is not '(') { a. postfixExp = postfixExp + (top of aStack) b. aStack.pop() 2. } 3. aStack.pop() // remove the open parenthesis 4. break iv. case operator: 1. while (!aStack.isEmpty and top of stack is not '(' and 2. precendence(ch) <= precendence(top of aStack)) { a. postfixExp = postfixExp + (top of aStack) b. aStack.pop() 3. } 4. aStack.push(ch) // save new operator 5. break 3. } 4. } 5. 6. 7. 8. 9. // append to postfixExp the operators remaining in the stack while (!aStack.isEmpty()) { postfixExp = postfixExp + (top of aStack) aStack.pop() }

Fox example convert the infix expression a - (b + c * d)/e to postfix form

Implementation at the end of the tutorial 6). Explain about queue data structures? (E) Ans) Queue: Queue is a data structure that works on the principle First In First Out (FIFO). The first element put on the queue is the first element that can be taken off. Insertions can be done at one end namely front and deletions can be done at other end namely rear It looks like open tube. The insertion operation of the Queue is called append/enqueue operation The deletion operation is called as serve/dequeue operation. Push operation on a full queue causes overflow. Pop operation on an empty queue causes underflow. The initial value of the front and rear pointer is always 1 The pointer front points to the starting end of the queue The pointer rear points to the rear end of the queue

front a Fig 01 b

rear c

front b Fig 02

rear c

front b c d Fig 03

rear e

For example The fig 01 illustrates a queue containing three elements a, b and c. the element (a ) is at the front of the queue and c is at the rear of the queue. Fig 02 shows queue after d eleting an element. Since elements may be deleted only from the front of the queue, (a) is removed and b is now at the front. Now fig 03 shows queue after inserting elements d and e , they must be inserted at the rear of the queue. Operations of a queue: There are two operations applied on queue they are 1 enqueue 2. dequeue. While performing enqueue & dequeue operations the following test must be conducted on the queue they are queue is full or empty Enqueue: enqueue operation is used to insert a new element in to the queue. At the time of insertion first check the queue is full or not. If the queue is full it generates an error message queue overflow.

Dequeue: dequeue operation is used to delete an element from the queue. At the time of deletion first check the queue is empty or not. If the queue is empty it generates an error message queue underflow. Assumptions: rear, front are pointers , initial values are -1, -1 max_queue is the size of the queue

Q[ ] is an array element is the element to be added or deleted Algorithm for adding an element in to the queue (enqueue): Step1: start Step2: if (rear == max_queue) then error queue is full go to step 6 Step3: other wise read element from the console Step4: put it in to queue at the rear queue[rear]= element Step5: update rear as rear = rear+1; Step6: stop. Algorithm for deleting an element from the queue (dequeue): Step1: start Step2: if (front = rear) then error queue is empty go to step5 Step3: other wise get the element form queue element = queue[front] Step4: update front as front = front + 1 Step5: stop. Drawbacks of a queue: For each and every enqueue operation the queue it is to be rearranged other wise even the queue is having an empty space it is not possible to utilize. Implementation at the end of the tutorial 7). Write about application of queue data structure? (s) Ans). Applications of queue: Queues can be used to store the interrupts in the operating system It is used by an application program to store the incoming data, which determines the order in which it is to be processed Queues are used for process synchronization in OS Used for job scheduling 8). Write about priority queues? Ans). A priority queue is a data structure that works on a principle add an element to the queue with an associated priority and remove the element from the queue that has the highest priority. A priority queue is essentially a list of items in which each item has associated with a priority. In general different items may have different priorities. For a given list we can determine which is the highest (or the lowest) priority item and inserted into a priority queue in any, arbitrary order. However, items are withdrawn from a priority queue in order of their priorities starting with the highest priority item first.

Item Priority

J1 1

J2 1

J3 1

------ ------

P1 2

P2 2

------ ------

O1 3

O2 3

O3 3

-------

priority - 1

J1 P1 O1

J2 P2 O2

------

Ji-1 Pi-1 Oi-1

J i Queue Pi Queue Oi Queue

priority - 2

------

priority - 3

------

The priority Queue of the above figure can be visualized as 3 separated Queues each following strictly FIFO behavior. In this example the items are deleted from the front end of each Queue. Elements in the 2nd Queue are removed only, when the first Queue is empty and elements from the 3rd Queue are removed only when the 2nd Queue is empty and soon. Implementation at the end of the tutorial

9). Write about DeQueue? (E) Ans). DeQueue (or) Deque (Double ended Queue) :DeQueue is a data structure in which elements may be added to or deleted from the front or the rear. Like an ordinary queue, a double-ended queue is a data structure it supports the following operations: enq_front, enq_back, deq_front, deq_back, and empty. Dequeue can be behave like a stack by using only enq_front and deq_front , and behaves like a queue by using only enq_front and deq_back. . The DeQueue is represented as follows.

front deletion insertion

rear insertion deletion

DeQueue can be represented in two ways they are 1) Input restricted DeQueue 2) output restricted DeQueue The out put restricted Dequeue allows deletions from only one end and input restricted Dequeue allow insertions at only one end. The DeQueue can be constructed in two ways they are 1. Using array 2. using linked list Algorithm to add an element into DeQueue : Assumptions: pointer f,r and initial values are -1,-1 Q[] is an array max represent the size of a queue

enq_front step1. Start step2. Check the queue is full or not as if (f < 0) if yes queue is full step3. If false update the pointer f as f= f-1 step4. Insert the element at pointer f as Q[f] = element step5. Stop enq_back step1. Start step2. Check the queue is full or not as if (r == max-1) if yes queue is full step3. If false update the pointer r as r= r+1 step4. Insert the element at pointer r as Q[r] = element step5. Stop Algorithm to delete an element from the DeQueue deq_front step1. Start step2. Check the queue is empty or not as if (f == r) if yes queue is empty step3. If false update pointer f as f = f+1 and delete element at position f as element = Q[f] step4. If ( f== r) reset pointer f and r as f=r=-1 step5. Stop deq_back step1. Start step2. Check the queue is empty or not as if (f == r) if yes queue is empty step3. If false delete element at position r as element = Q[r] step4. Update pointer r as r = r-1 step5. If (f == r ) reset pointer f and r as f = r= -1 step6. Stop Implementation at the end of the tutorial 10). what is a liked list? Write various operations performed by linked list? (E) Ans).

Linked list: Linked list is a data structure that works on a principle Random In Random Out (RIRO). Linked list can be defined as Collection of logically adjacent nodes in which logical adjacency is maintained by pointers. Ex: The days of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat) Linked lists can be represented in memory by two ways they are Using array method 2. Using pointer method In array method all the elements are stored in the continuous memory locations. It is having certain disadvantages they are 1. Arrays follow static memory allocation. 2. It is not possible to extend the size of the array while running the program. 3. Due to static memory allocation some memory space will be wasted. In pointer method all the data elements are represented using nodes. Each node is having data item and pointer to the next node. In this method the elements in the list need not occupy continuous memory locations. The advantages of this method are Efficient memory management is possible, i.e., due to dynamic memory allocation the memory is not wasted Insertion and deletion operations are easy to perform, i.e, It is possible to add or delete an element any ware in the list It is dynamic in nature, i.e., It is possible to handle a list of any size It is possible to extend the size of a list at runtime Various operations performed on lists: The operations performed on lists are. 1. Inserting a new element at the given position. 2. Delete the element from the given position 3. Find the length of the list 4. Read the list from left to right 5. Retrieve the ith element 6. Copy a list 7. Sort the elements in either ascending or descending order 8. Combine 2 or more list 11). Discuss about single linked list? (E) Ans). Single linked list: Single Linked list is a fundamental data structure used in computer programming. It consists of a sequence of nodes connected by only one pointer in one direction. Each node is having two parts the first part contains the data and second part contains the address of the next node. The first part is called data field or information field and the second part is called as link field or next address field. The first node of a list is represented by using pointer root and the last node is represented by a special value called NULL . it is also called as one way list The schematic diagram of a linked list is given below.
Data Root
st

next

Data

Data Last node or Tailor node

NULL

1 node or header node

Need for linked representation :The following problem arises when sequential mapping like an array is used for list of items 1. Wastage of storage 2. It is not possible to add or delete in the middle of a list with out rearrangement 3. It is not possible to extend the size of a list To overcome all the above problem by implementing the list using linked representation. In linear lists insertion and deletion operations are inexpensive. Operations applied on single linked list: The basic types of operations applied on single linked list are Adding an element to an existing list Deleting an element from the list Print all the element of a list

Algorithm to add an element to an existing list: It is possible to add an element to an existing list in three ways they are 1) Add at the front 2) Add at the end of the list 3) Add after a node of the existing list Assume that 1) Pointer start always contains the current list start node address. 2) ->next stands for next node address Add at the front of a list Step1: create a new node n Step2: n->next = start; Step3: start = n;

start n start n

Add at the end of a list Step1: create a new node n Step2: take temporary pointer t and traverse the list until t->next = null Step3: t->next = n

start
Add after a node of a list n Step1: create a new node n Step2: read the position of the node p; Step3: take temporary pointer t and traverse the list until the p position. Step4: n->next = p->next; Step5: p->next = n

start

n
Drawbacks of a single linked list: It is having only one pointer so that it is possible to traverse in only one way Implementation at the end of the tutorial

12) Explain about double linked list? (E) Ans). Doubly linked list (or) Double linked list :Doubly linked list is one of the fundamental data structure used in computer programming. It consists of a sequence of nodes, each containing arbitrary data fields and two pointers pointing to the next and previous nodes.

Previous node address

Data Double linked node

Next node address

The basic node structure of double linked list is shown in the fig. From the above fig the node is containing 2 pointers. 6. Pointer1 is pointing to the previous node. 7. Pointer2 is pointing to the next node.

Root Null

Data
D - Data

Null Last

Doubly linked list can be represented as above fig. in doubly linked list it is possible to traverse both forward & backward directions. It is also called two way lists. Operation applied on double linked list:

Inserting a new element at a given position. Delete element from the given position Find the length of the list Read the list from left to right Retrieve the ith element Copy a list Sort the elements in either ascending or descending order Combine 2 or more list

Algorithm to add an element to an existing list: It is possible to add element to an existing list in thee ways they are add at the front, add at the end of the list, add after a node of the existing list. Assume that start always contains the current list start node address. ->next stands for next node address

L start
Add node at the front of a list Step1. Create a new node Step2. n->right = start Step3. start->left = n Step4. start = n;

n start

Add node at the end of a list Step1. Create a new node Step2. t = start where t is a temporary variable. Step3. Traverse the tree until t->right = null Step4. t->right = n start Step5. n->left = t Add node after a particular position or a node Step1. Create a new node. Step2. t = start where t is a temporary pointer variable Step3. Read position p from console. Step4. Traverse the list until the position p Step5. if not found the position error no such node exist : go to step 9

t start

Step6. n->right = p->right Step7. n->left = p Step8. p->right = n Step9. end

start
Insert node after second (2) node

t start t start

Implementation is at the end of the tutorial

13) What is Circular Queue? Explain the different ways of creating Circular Queue? (E) Ans). Circular queue :Queue is a structure, which follow FIFO principle. When a new item is inserted at the rear, the pointer to rear moves upwards similarly, when an item is deleted from the queue the front arrow moves downwards. After a few insert and delete operations the rear might reach the end of the queue. Even though the queue is having a free space it is not possible to insert new elements. To solve this problem by making a queue as a circular; In circular queue the last node is connected back to the first node to make a circle. Circular linked list fallow the First In First Out principle Elements are added at the rear end and the elements are deleted at front end of the queue Both the front and the rear pointers points to the beginning of the array. It is also called as Ring buffer. Items can inserted and deleted from a queue in O(1) time.

Circular Queue can be created in three ways they are Using single linked list Using double linked list Using arrays Using single linked list: It is an extension for the basic single linked list. In circular linked list Instead of storing a Null value in the last node of a single linked list, store the address of the 1st node (root) forms a circular linked list. Using circular linked list it is possible to directly traverse to the first node after reaching the last node. The following figure shows circular single linked list:
Root Data Data Data Data

Using double linked list In double linked list the right side pointer points to the next node address or the address of first node and left side pointer points to the previous node address or the address of last node of a list. Hence the above list is known as circular double linked list. The following figure shows Circular Double linked list :-

Root

Data

L ast

Using array Using array if the pointer reaches to the maximum size of the list the next addressable index location is the starting (0) index location. To achieve this repositioning array index by using the following formula (index = index +1) % max_size. The following figure shows circular array:

F R

Algorithm for creating circular linked list :Step 1) start Step 2) create anode with the following fields to store information and the address of the next node. Structure node begin int info pointer to structure node called next end Step 3) create a class called clist with the member variables of pointer to structure nodes called root, prev, next and the member functions create ( ) to create the circular linked list and display ( ) to display the circular linked list. Step 4) create an object called C of clist type Step 5) call C. create ( ) member function Step 6) call C. display ( ) member function Step 7) stop Algorithm for create ( ) function:Step 1) allocate the memory for newnode newnode = new (node ) Step 2) newnode->next=newnode. // circular Step 3) Repeat the steps from 4 to 5 until choice = n Step 4) if (root=NULL) root = prev=newnode // prev is a running pointer which points last node of a list else newnode->next = root prev->next = newnode prev = newnode Step 5). Read the choice Step 6) return Algorithm for display ( ) function :Step 1) start Step 2) declare a variable of pointer to structure node called temp, assign root to temp temp = root Step 3) display temp->info Step 4) temp = temp->next Step 5) repeat the steps 6 until temp = root Step 6) display temp info Step 7) temp=temp->next Step 8) return Implementation at the end of the tutorial 14). Write differences between single linked list and arrays? (s)

Ans). Differences between single linked list and arrays LINKED LIST 1 2 3 4 5 6 7 8 9 10 11 Collection of nodes connected together by using pointers is known as Linked List The elements can be accessed using a pointer to the next node in the current node Sequentially we can access each node of a linked list Linked list not be in a continuous memory Linked list is a dynamic list We can extend the size of the linked list by inserting new nodes We can dispose the linked list nodes Initially creating a linked list may be complex in many situations Failure of any link (pointer) affects the entire linked list while traversing As it follows dynamic memory allocation, there is no chance of having memory wastage Linked list of integers is shown below ARRAYS Collection of similar data items is known as array. The elements can be accessed using subscripts or index We can access the elements of the array randomly Array stored in a continuous memory locations Array is a static list We cannot extend the size of the array We cannot dispose the array elements Easy to maintain the elements by the user Accessing of elements will not be affected by any memory locations As array follows static memory allocation, there may be chance of having wastage of memory Array of integers is as shown below.
2000 2002 04 A 2006 2008 2010 10 20 30 40 50 60

info root 20 A ddress of next node 30 node Null

A[0] A[1] A[2] A[3] A[4] A[5]

12 13

Backward traversing is not possible in single linked list node declaration in C++ struct node { nt info; node next; }node root;

Any way we can access each element The following is the way of declaring an integer array in C++ int a [10];

15. Define tree data structure? (s) Ans). Trees: A tree T is having one or zero nodes (null) number of nodes

the remaining nodes are partitioned into n(n>=0) disjoint sets T1,T2,T3,Tn where each Ti(I =1,2,3n) is a tree,, T1,T2,T3, Tn are called sub trees of the root

A tree consists of a collection of nodes, which are connected by directed arcs. A tree contains a unique first element known as the root, which is shown at the top of the tree structure. The nodes connected to this node are called as children nodes. The root node or the node connected by the children node is called as a parent node. The root is the only node in the tree that does not have a parent. All other nodes in the tree have exactly one parent. The node having no Childs are called leaf nodes

Root

Where ch1, ch2, ch n are Childs

Ch1 Ch1

Ch2 Chn

Ch3 Ch1

Chn Chn

16) What is Binary tree? Explain how it is to be represented in the memory? (E) Ans). Binary tree :A binary tree is a tree data structure in which each node has at most two children. The child nodes are called left and right. Or A binary tree T is defined as the finite set of elements called nodes. Such that T is having zero or null nodes T contains a distinguished node called the root (R ) and the remaining nodes of T form an ordered pair of two disjoint binary trees T1 and T2 which are called left and right sub trees respectively. A binary tree is represented by means of a diagram as follows.

T T1 Lc Root Lc Rc Lc Rc Rc T2

There are two ways to represent Binary tree in memory they are 1. Linear representation and 2. Linked representation Linear Representation of binary tree in memory This is the static representation of the binary tree, so that a block of memory for an array is to be allocated before going to store the actual tree in it. The size of the tree will be restricted as the memory permits In this representation the nodes are stored level by level starting from the zero (root) level. Root node is stored in the first memory location (as the first element of array) and the remaining nodes are stored using the following rules. Assume that the array index is starting at 1 1. The root node is at location 1 2. for any node with index i, 1 < i <= n (for some n); 1. PARENT(I) = [i/2] for the node when i =1 there is no parent 2. LCHILD(i) = 2*i if 2*i > n then i has no left child 3. RCHILD(i) = 2*i+1 if 2*i+1 > n, then i has no child Linked Representation of binary trees in memory :This is a dynamic representation of a binary tree. The required memory to store an element is allotted at run time. Elements are stored by using double linked list node structure i.e. the node is having one data part and two pointers points to left and right side nodes. The node structure is to be shown in the fig. in c++ the node structure can be declare as struct node {

node * left; int info; node * right; };

A Node structure Left Data Right child field child T1 D B E

T C T2 F
Null

A B D Null
Null

Null C E Null
Null

F Null

17) Define level and depth of a tree? (s) Ans). Level of a tree :Each node in a binary tree is assigned a level number. The root R of the tree is assigned a level number Zero and every other node assigned a level number which is one more than the level number of its parent said to belong to the same generation. Depth of a tree:The depth or height of a tree is the max No. of nodes in a branch of a tree. For example

A A A A A A A A A A

Level 0 Level 1 Level 2 Level 3 Depth = max level =3

18) What is binary search tree? (s) Ans) Binary search tree: A binary tree T is defined as the finite set of elements called nodes. Such that T is empty called null tree or empty tree. T contains a distinguished node R called the root of the tree T and the remaining nodes of T form an ordered pair of disjoint binary trees T1 and T2 which are called left and right sub trees respectively and For every node, X, in the tree, the values of all the keys in the let subtree are smaller than or equal to the key value in X, and the values of all the keys in the right subtree are larger than the key value in x.

20 15 12 18 25 67

19) Explain the operations of a binary search tree? (E) Ans). Operations applied on Binary search tree 1. Insert a node 2. Delete a node 3. Traversal.

Search and inserting a new node into binary tree: Assumptions: T is A binary tree Item is a new node to be inserted

The following algorithm finds the location of item in T, or inserts item as a new node in the tree. Step1. Compare item with the root ( N ) of the tree as if ( item < N ) proceed to the left child of N. if ( item > N ) proceed to the right child of N Step2. Repeat step1 until one of the following occurs. We meet a node N such that item = N. in this case the search is successful We meet an empty sub tree, which indicates the search is unsuccessful. Insert item in place of the empty sub tree. Step3. Exit Delete a node from binary tree. Assumptions: a binary search tree T item is the node to be deleted F(N) denotes the parent of a node N S (N) denotes the inorder successor of N.

Step1. Compare item with the root(N) of the tree as If (item < N ) F(N) = current pointer ,proceed to the left child of N If (item > N ) F(N) = current pointer , proceed to the right child of N Step2. Repeat step 1 until one of the following occurs. 1. We meet a node N such that item = N in this case the search is successful 2. We meet an empty sub tree print error node not found , stop and exit. Step2. Determine the number of children of N. there are three cases. 1. N has no children. N is deleted from T by simply replacing the location of N to the parent node F(N) by the NULL pointer. 2. N has exactly one child M. N is deleted from T by replacing the location of N in the parent node F(N) by location of M( this replaces N by M) 3. N has two children 1. Find the inorder successor S(N) of N and S(N) has no child), Replace N by S(N) in T 2. If inorder successor S(N) of N is having a child delete S(N) from T using case 1 or case 2 and Replace N by S(N) in T and For example suppose node 88 is added to the existing tree

60 30 63 78 30

60 78 88 Inorder 63 successor

Delete node 60

63 30 78 88

20). Write about binary search Tree traversals? (Or) How to traverse a binary search tree? (E) Ans). Tree traversal techniques: Tree transversal is a process in which each node of a tree is visited exactly ones. There are several possible ways to visit nodes during traversal. In Binary trees there are three traversal techniques they are 1) Inorder 2) preorder 3) postorder

Inorder:Inorder traversal of a binary tree follows three ordered steps as Traverse the left sub tree of the root node R in inorder Visit the root node R Traverse the right subtree of the root node R in inorder Out of these steps, step1 and 3 are recursive. Following is the algorithm for INORDER to implement above definition Algorithm: INORDER Input : ROOT is the pointer to the root node of the tree Output : visiting of all the nodes in inorder fashion Data structure : linked structure of binary tree Steps; 1. ptr = ROOT 2. if (ptr != NULL) then INORDER (ptr -> Left ) VISIT(ptr) INORDER (ptr -> Right ) 3. endif 4. stop Preorder traversal:For example inorder for the following graph

B
Is BAC

Preorder traversal of a binary tree follows three ordered steps as visit the root node R Traverse the left sub tree of the root node R in preorder Traverse the right subtree of the root node R in preorder Out of these steps, step1 and 3 are recursive. Following is the algorithm for PREORDER to implement above definition Algorithm: PRERDER Input : ROOT is the pointer to the root node of the tree Output : visiting of all the nodes in preorder fashion Data structure : linked structure of binary tree Steps; 1. ptr = ROOT 2. if (ptr != NULL) then VISIT(ptr) PREORDER (ptr -> Left ) PREORDER (ptr -> Right ) 3. endif 4. stop Post order traversal of a binary tree: Traverse the left sub tree of the root node R in postorder Traverse the right subtree of the root node R in postorder Visit the root node R for example preorder for the following graph

B
Is ABC

Out of these steps, step1 and 3 are recursive. Following is the algorithm for PREORDER to implement above definition

Algorithm: POSTORDER Input : ROOT is the pointer to the root node of the tree Output : visiting of all the nodes in postorder fashion Data structure : linked structure of binary tree Steps; 1. ptr = ROOT 2. if (ptr != NULL) then POSTORDER (ptr -> Left ) POSTORDER (ptr -> Right ) VISIT(ptr) 3. endif 4. stop

for example postorder for the following graph

B
Is BCA

21). How to represent an expression as an expression tree? Ans) Expression can also be represented using trees. The following is the way of representing arithmetic expressions using trees. 1. (A+B) (C+D)

* +
A B C

+
D

Inorder pre order post order

: (A+B) (C+D) : +AB+CD : AB+CD+

22) Write an algorithm to convert a general tree to binary tree? (s) Ans) conversion of general trees to binary tree: It is convenient to represent binary trees than represent the general trees in programs because in case of a general tree, the number of edges connected to a node at any given level is unpredictable.. But in case of a binary tree, each node has a maximum of two sub trees. A general tree can be converted into an equivalent binary tree. The algorithm is as follow Algorithm: Insert edges connecting siblings from left to right at the same level. Delete all edges of a parent to its children except to its left mode offspring Rotate the resultant tree 45 to mark clearly left and right sub trees.
A A

23) Write the applications of a binary tree? (s) Ans). Applications of Binary tree : A binary search tree is an appropriate data structure for searching a value A binary tree used for manipulation of arithmetic expression A binary tree can be used as a Decision tree construction of symbol tables and maintenance of symbol tables The trees also play an important role in the area of syntax analysis (parsing) of complier design by constructing parse trees Another application of trees is in playing of games such as chess, checkers etc (Game trees) Binary trees may also useful to evaluate the expressions A heap tree may be constructed for a given set of numbers, which facilitates the way of sorting 24) What is complete binary tree? (s) Ans). Complete binary tree: a complete binary tree of depth d is the strictly binary tree, all of whose leaves are at level d. for example

A B D
25) What is almost complete binary tree? (s) Ans). Almost complete binary tree: a binary tree is almost complete binary tree if any node n at level less than d-1 has two sons. for any node n if the tree with a right descendent at level d, n must have a left son and every left descendent of n is either a leaf at level d or has tow sons. an almost complete binary tree of n leaves has 2n-1 node. For example

C E F G

A B F H
Eample 2:

Case1 : satisfy, all nodes is having two sons C Case 2: the right descendent j at level 3 but left descendent E at level 2 hence condition 2 fails. It is not complete binary tree. E K Case1 : satisfy, all nodes is having two sons C Case 2: the right descendent F at level 2 and left descendent E. hence conditions 2 satisfy. It is complete binary tree. E

G I J

A B F H I G D

Example 3:

A B D H I E J F C G

Case1 : fails, because node E not having right child. Hence it is not complete binary tree.

26) What is extended binary tree? (s) Ans) Extended binary trees (e-trees) : A binary tree T is said to be a 2-tree or an extended binary tree if each node N hs either 0 or 2 children in such a case a node with 2 children are called internal nodes, and the nodes with 0 children are called external nodes. These nodes are distinguished by using circle for internal and square for external node.

27) What is threaded binary tree? (s) Ans) Threaded binary trees: A binary tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node, and all left child pointers that would normally be null point to the inorder predecessor of the node 28) What is height balanced tree (AVL tree)? (s) Ans) Height balanced tree: (AVL Tree) : The height of the left subtree of R and the height of the right sub tree of R differ by at most 1 (or) A binary search tree is said to be height balanced binary search tree if all its nodes have a balance factor of 1, 0, -1 that is Balance factor = height of left height of right <= 1 For example

-1 0 AVL tree -1 1 0 0

-1 -3 1 0 Not height balance

29) Define graph? What are the different types of graphs? Define graph terminologies? (s) Ans) A Graph G consists of two sets: 1. A set V of elements called nodes ( or points or vertices) 2. A set E of edges such that each edge e in E is identified with a unique (unordered) pair [u,v] of nodes in V, denoted by e = [u, v]

Each edge in e joins 2 different vertices of v and is denoted by (i,J) where i& J are the 2 vertices joined by an edge in e. A Graph G is generally represented as a figure in which the vertices are represented by circles and edges by lines. The following are the list of different types of graphs

A graph with all undirected edges is called undirected graph.


1

A graph with all directed edges is called directed graph.


1 4 2

3
3

Undirected

Directed

A graph with self loops and parallel edges is known as multi graph.

A graph with without self loops & parallel edges is said to be simple graph
1

1 2 2 3 4 4 5 3

A Graph in which all the vertices having the same degree is said to be regular graph If the degree of each vertex is 2 then it is known as 2- regular. In the same way if the degree of each vertex is r then V1 it is called r-regular graph.
V1 V2
V1 V2

1 - regular V2 V3 2 - regular V4 3 - regular V3

Complete Graph:- If there is an edge joining between any 2 vertices then it is said to be an complete graph i.e each vertex must have an edge to all other vertices in the Graph
V1

V 2

V 3

V 4

V 5

Bipartite Graph:Let G=(V,E) is a graph, if the vertices set V={i1, i2,i3......ik.....in} Then the above set v can be portioned into V1 and v2 as follows v1= {i1,i2,i3.......ik} v2={ik+1,ik+2,ik+3,....... in} Now the graph G is said to be Bipartite if every vertex of v1 is containing an edge to every other vertex of v2 The following is an example v= {i1,i2,i3,i4,i5} and Let V1= {i1,i2} and v2= {i3,i4,i5} Then the Bipartite graph can be given as follows

i1

i2

i3

i4

i5

The above graph can be represented as K2,3 i.e 1st set is containing 2 vertices & set 2nd set is containing 3 vertices. In general Km,n is Bipartite graph with m vertices in 1st set and n vertices in 2nd set. Graph terminology: Path:- A sequence of vertices P= i1,i2,i3,........ik is an i1 to ik path in the Graph G=(V,E) Simple path :- A simple path is a path in which all the vertices except the first and last are different Cycle: a cycle is a path, which satisfies the following conditions. No edge appears more than once in the sequence of edges. The first node of the path is the same as the last node of the path A graph containing cycle is called cyclic graph Order: the number of elements in V(G) is called the order of graph G. Tree in terms of Graphs:A Graph G is said to be tree if the following conditions are satisfied. G must be connected If G is containing vertices, then it should contain (N-1) edges G should not contain self loops and parallel edges and cycles 30). How to represent a graph in computer memory? (or) what is adjacency list and what is adjacency matrix? Explain? (E) Ans). Representation of Graphs in computers memory:Graphs can be represented in memory by two ways they are 1) Linked representation using Adjacency matrix 2) Sequential representation using Adjacency list Adjacency List : The Adjacency list of a vertex v is a sequence of all vertices adjacent to v

An Adjacency list provides a convenient way of storing the adjacent nodes with the help of a linked list. For each vertex i of a graph there will be a linked list of adjacent nodes containing the names of all vertices that are adjacent to itself. We can also make use arrays to represent these adjacency lists. The graph itself is an array of nodes. The basic node structure of a graph is

Label

adj_list

Weight

Label

adj_list

Non weighted graph

weighted graph

The following one is the example of representing the graphs using adjacency list method.
1

v e rte x 1
3

a d ja c e n c y lis t 2 ,3 ,4 1 ,3 1 ,2 ,4 1 ,3

2 3 4

[1] [2] [3] [4]

2 1 1 1

3 3 2 3

4
NU LL

NU LL

4
NU LL

NU LL

Adjacency matrix:The Adjacency matrix of a graph G=(V,E) with n vertices an nxn matrix A. If G is an undirected graph then the elements of A are defined as follows A(i,J) = 1 if there is an edge other wise 0 If G is a directed graph (digraph) then the elements of A are defined as follows. A(i,j) = 1 if there is a directed edge between nodes whose source node value is 1 other wise it is zero i.e a directed edge a->b then value of a is 1 and b is 0

For example consider the following Graph& obtain the adjacency matrix Graph1:

1
1 2

3 4

0 1 1 1

1 0 1 0

1 1 0 1

1 0 1 0

In the side graph contains 4 vertices then the order of the adjacency matrix is 4x4

Graph2:
4
1 1 0 2 1 31 4 0 5 0 6 0 7 0 2 3 1 0 0 0 0 0 0 1 0 0 0 0 0 0 4 5 6 7 0 0 0 0 1 0 0 0 0 0 1 0 1 1 0 0 0 0 1 0 1 0 0 0 0 1 1 0

Mapping the adjacency matrix into an array The n*n Adjacency matrix A may be mapped into an array a of type integer A(i,J) = a[ i ] [ j ] where i,j are index values starting with 1. Properties of an Adjacency matrix The Adjacency matrix of an undirected graph is symmetric i.e A(i,J) =A(j,i), & for an n vertex directed graph 31). How to traverse a graph? Explain? Write and explain an algorithm for BFS and DFS? (E)

Ans). Graph traverses:Graphs can be traverse to find a required node or visit all the nodes. There are two ways to traverse graph. They are Depth first search (DFS) Breadth first search (BFS) DFS :Depth-first search (DFS) is an algorithm for traversing or searching a graph. Select some node as the root and visit all nodes along each branch before backtracking. Algorithm :During the execution of our algorithm each node n of G will be in one of the following 3 states. STATUS =1 (ready state) - The initial state of the node n STATUS =2 (waiting state) - The node n is on stack waiting to be processed. STATUS =3 (processed state) - The node n has been processed The following algorithm executes a DFS on a graph G beginning at a starting node A. Steps: Initialize all nodes to the ready state (STATUS =1) push the starting node A on to stack and change its status to the waiting state (STATUS =2) Repeat steps 4&5 until stack is empty Pop the top node N of stack. Process N and change its status to the processed state (STATUS =3) Push on to the stack, all the neighbors of N that are still in the ready state (STATUS=1) and change their status to the waiting state ( STATUS =2) Repeat the above process until all the nodes of a graph are visited (i.e the status of all the nodes are in processed state (STATUS = 3). Stop

u
Apply DFS algorithm for the following graph:

x
Start at vertex u and change the status = 3 Push vertex connected to u (x, v) and change status = 2 Stack : x,v

x
Pop vertex v from stack and change the status =3 Push the vertex connected to v (y) and change the status = 2 Stack : x, y

y v

z w

x
Pop vertex y from stack and change the status =3 The vertex connected to y (x) but which is already in the stack Stack : x

y v

z w

Pop vertex x form stack and change the status= 3 Stack : NULL Since all the connected verteces are visted there is no way to visit w,z so start the process again at vertex w or z. Start at vertex w; push the vertex connected to w(y,z) to stack. But vertex y is already visited so push z to stack Stack : z

u
B

x u
F B

y v
C

z w
9/

x
Pop z from stack and change status = 3 Stack : NULL And all the nodes are visited. Stop the process
F

y v
B C

z w

BFS:The general idea behind BFS is start at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, explore their unexplored neighbor nodes, and so on until it finds the goal. Algorithm :- This algorithm executes a BFS on a graph G beginning at a starting node A. 1. 2. 3. 4. Initialize all nodes to the ready state (STATUS =1) Put the starting node A in Queue and change it status to the waiting state (STATUS=2) Repeat steps 4 and 5 until Queue is empty Remove the front node n of Queue. Process n and change the status of n to the processed state (STATUS=3) 5. Add to the rear of the Queue all the neighbors of n that are in the ready state and change their status to the waiting state. 6. Repeat the above process until all the nodes of a graph are visited (i.e. the status of all the nodes are in processed state (STATUS = 3). 7. Stop


v
r

0
w

0 1
w
s t


x
u

Q s

v
r

wr 1 1

1
v r

0 1
w s

2 2
x t


y u

Q r t x

1 2 2

Starting at node s
s t u

1 2
v

0 1
w

2 2
x

Qt x v

1 2
v

0 1
w

2 2
x

3
y

Qx v u

2 2

3 3

Qv u y

2 2 2

2 2 3
u

2
v

1
w

2 3 3

1 2
v

0 1
w

2 2
x

3 3
y

u y 3 3

1 2
v

0 1
w

2 2
x

3 3
y

Q y

1 2
v

0 1
w

2 2
x

3 3
y

Q -

32). Define spanning tree and minimum spanning tree? Ans). A spanning tree of a connected Graph G is a sub-graph of G which covers all the vertices of G.

A minimum-cost spanning tree is one whose edge weights add up to the least among all the spanning trees.

33).Find minimum spanning tree using Prims algorithm? Ans). The technique for creating minimum spanning tree for a weighted graph was discovered by Prims and Dijkstra Prims algorithm: Step 0: Pick any vertex as a starting vertex. (Call it S). Mark it status as visited. Step 1: Find the least weight neighbor of S (call it P1). Mark both P1 and the edge SP1 status as visited. Visit next cheapest unvisited edge in the graph that doesn't form a cycle. Mark this edge status as visited. Step 2: Find the least weighted unvisited neighbor to the visited sub graph (i.e., the closest vertex to any visited vertex). Mark the status of edge connected to vertex as visited. Step 3: Repeat Step 2 until all vertices are visited. The visited sub graph is a minimum spanning tree. Prims Algorithm: Assumptions: Graph [ ][ ] is an adjacency matrix of a graph Infi is a constant represents infinity value (ex. 50000) Selected [ ] is an array store the spanning tree Node represents maximum number of nodes in a graph void primsAlgo(){ for(i=0;i<nodes;i++) selected[i]=false; selected[0]=true; ne=0; while(ne < nodes-1){ min=infi; for(i=0;i<nodes;i++) { if(selected[i]==true){ for(j=0;j<nodes;j++){ if(selected[j]==false){ if(min > graph[i][j]) // find the minimum weighted neighbour { min=graph[i][j]; x=i; y=j; } } } } } selected[y]=true; // add the node to the spanning tree cout<<"\n"<<x+1<<" --> "<<y+1; ne=ne+1; } } Complete program at the end of the tutorial // to make all the nodes of a graph are unvisited // select the node 0 and make it as visited

For example:

4 V3 5

V1 2 V6

2 1 V4 8 1 3

V2 7 4 V7

10 V5 6 V3

V1 V4 V6 Fig 01 2 1 V4 V6

V2 V5 V7

V1 V3 V6

1 V4

V2 V5 V7 V3

V1

V2 V5 V7

Fig 02 V1 V3 2 V6 Fig 04 2 1 V4 4 1 Fig 06 V7 2 1 V4 V7 V2 V5

Select v4 v2 form a cycle so choose v4 v7 V3

Fig 03 2 1 V4

V1 2 V6

V2 V5 4 V7

V1 V3 2 V6

V2 V5 V3

V1 2

Fig 05 2 1 V4

V2 V5 4 6 V7

V6

1 Fig 07

Its minimum spanning tree starting from v1is as follows First start at v1 , v1-v4,v1-v2,v4-v3,v4-v7,v7-v6,v7-v5 The final minimum spanning tree is read as (v2,v1),(v3,v4),(v4,v1),(v5,v7),(v6,v7),v(7,v4)

34). Find minimum spanning tree using Kruskals algorithm? Ans). Kruskals algorithm: Step 1: Initially all the edges of the graph are sorted based on their weights. Step 2: Select the edge with minimum weight from the sorted list in step 1.Selected edge shouldnt form a cycle. Selected edge is added into the tree or forest.

Step 3:

Repeat step 2 till the tree contains all nodes of the graph.

Kruskals algorithm states that continuously select the edges in order of a smallest weight and accept an edge if it does not cause a cycle. Formerly Kruskals algorithm maintains a forest (a collection of trees). Initially, there are | V | single nodes trees. Adding an edge merges two trees into one. When the algorithm terminates, there is only one tree, and this is the minimum spanning tree. For example:

4 V3 5

V1 1 2

2 1 V4 8 3

V2 7 4

10 V5 6 V3

V1 V4 V6

V2 V5 V7

V6

V7

Fig 01

V1 1 V3 V6

1 V4

V2 V5 V7 V3

V1

1 V4

V2 V5 V7

V6

Fig 02
V1 1 V3 V6 2 1 V4 V7 V2 V5 V3 V1

Fig 03
2 1 V4 V7 V2 V5

2 V6

Fig 04
V1 1 V3 2 V6 2 1 V4 4 1 V7 V2 V5 V3 V1

Fig 05
2 1 V4 4 1 V7 V2 V5 6

2 V6

Fig 06

Fig 07

Its minimum spanning tree is starting from v1. The construction process is as follows First start at v1 , v1-v4,v6-v7,v1-v2,v4-v3,v4-v7,v7-v5

The final minimum spanning tree is read as (v2,v1),(v3,v4),(v4,v1),(v5,v7),(v6,v7),v(7,v4) The following sequence of diagrams illustrates Kruskal's algorithm in operation.

Working programs:
Stack Programs: 1. Stack implementation using linked list #include<process.h> #include<iostream.h> struct node { int info; node *next; }; class stack { public : node *top; stack () { top = NULL; } void push (); void pop (); void dis (node *t); }; void stack :: push () { node *n; n = new node; cout << "enter the element \n; cin >> n->info; n->next = top; top = n; } void stack::pop() { node *n; if (top == NULL) cout << "empty stack " <<endl; else { cout << "the poped element is " <<top->info; n = top->next; top = top->next; } } void stack :: dis(node *t) { cout<<" "<<t->info; if (t->next!=NULL) dis (t->next); } void main () { stack s; int choice; while (1){ cout<<"1.push 2.pop 3.display 4.exit"<<'\n'; cin>>choice; switch(choice) { case 1 : s.push (); break; case 2 : s.pop (); break; case 3 : s.dis(s.top); break; case 4 : exit(0); } }}

2. Stack using array


#include <iostream.h> #include <process.h> class stack { private : int *s, sp,max; public : void push (); // to push item into stack void pop ( ); // to delete an item void display ( ); // to display the contents of stack stack (int); // constructor int isfull(); int isempty(); }; //The following is the member function for the push operation. int stack::isempty() { if (sp == -1) return 1; else return 0; } // the following is the display member function void stack :: display ( ) { for (int i=sp; i>0; i --) cout<<s[ i ]<<endl; } stack :: stack ( int n) { sp=-1; max = n; s = new int[max]; } void main ( )

void stack :: push () {if (isfull()) cout << stack is full <<endl; else {cout <<enter element \n; cin >> s[sp++]; } } //The following is the member function for the pop operation void stack :: pop ( ) { if (isempty) cout<<"stack is empty"; else cout<<s [sp--]; } int stack::isfull() { if (sp== max-1) return 1; else return 0; }

int n; cout << enter size of stack <<endl; cin>>n; stack s(n); int choice; do { cout<<" 1. psuh\n 2. pop\n 3. Display/n 4. exit\n"; cout<<"enter choice"; cin>>choice; switch (choice) { case 1: s.push () ; break ; case 2 : s.pop ( ); break; case 3 : s.display ( ); break; case 4 : exit(0); } } while (choice!=4) ; }

3. Convert infix expression to post fix expression


#include <iostream.h> #include <process.h> #include <ctype.h> class stack {private : char s[10]; int top; public : int isfull() { if (top >= 9) return 1; else return 0; } int isempty() {if (top == -1) return 1; else return 0; } void push (char item); // to push char pop ( ); // to delete an item void display ( ); // to display stack (); }; //The following is the member function for the push operation. void stack :: push (char item) { top ++; s [top] = item; } //The following is the member function for pop and display operations char stack :: pop ( ) { char x; x=s [top]; top -- ; return x; } void stack :: display ( ) { for (int i=top; i>0; i --) cout<<s[ i ]<<endl; } stack :: stack ( ) { top=-1; } int priority(char ch) { switch (ch) { case '+' : return 1; case '-' : return 2; case '*' : return 3; case '/' : return 4; } } //Now the following main program can create an object of type stack and perform push, pop and display operations. void main ( ) {char eq[10]; int i,j,k; stack a,b; cout << "enter the infix equation "<<endl; cin >> eq; for (i=0; eq[i] != '\0'; i++) {if (isdigit(eq[i]) ) cout <<eq[i] << " "; else { if (a.isempty() ) a.push(eq[i]); else {char e = a.pop(); if (priority(e) < priority(eq[i]) ) {a.push(e); a.push(eq[i]); } else cout << e<<" "; a.push(eq[i]); } } } } while (!a.isempty()) cout << a.pop()<<" ";}

4. Evaluate postfix expression. #include <iostream.h> #include <process.h> #include <string.h> #include <ctype.h> #include <iostream.h> #include <process.h> class stack { private : int *s, sp,max; public : void push (int); // to push item into stack int pop ( ); // to delete an item void display ( ); // to display the contents of stack stack (); // constructor int isfull(); int isempty(); }; //The following is the member function for the push operation. void stack :: push (int n) {if (isfull()) cout << stack is full <<endl; else {cout <<enter element \n; s[sp++] =n; } } //The following is the member function for the pop operation int stack :: pop ( ) { if (isempty) cout<<"stack is empty"; else return s [sp--]; } int stack::isfull() { if (sp== max-1) return 1; else return 0; } II, Queue programs 1. Queue using array // Implementing Queue as a Class # include<iostream.h> # include<conio.h> # define SIZE 20 class queue { int *a; int front; int rear; public: queue(); ~queue(); void insert(int i); int remove(); int isempty(); int queue::remove() { if(isempty()) {cout<<"\n\n******\nQueue Empty !!!\nValue returned will be garbage.\n******\n"; return 0 ; } return(a[front++]); } int queue::isempty() { if(front == rear) return 1; else return 0; int stack::isempty() { if (sp == -1) return 1; else return 0; } // the following is the display member function void stack :: display ( ) { for (int i=sp; i>0; i --) cout<<s[ i ]<<endl; } stack :: stack ( ) { sp=-1; max = 100; s = new int[max]; } void main ( ) { stack a; int p1,p2; int item, choice,i=0,l; char e[] = "223*+"; l = strlen(e)-1; do { if (isdigit(e[i]) ) a.push ((e[i])-'0' ); else { p2= a.pop(); p1= a.pop(); switch(e[i]) { case '+': a.push(p1+p2); break; case '-': a.push(p1-p2); break; case '*': a.push(p1*p2); break; case '/': a.push(p1/p2); break; default: cout<<" improper operator " ; exit(0); } } } while (++i <=l); cout <<" the result is " << (a.pop()); }

int isfull(); }; queue::queue() { a = new int[SIZE]; front=0; rear=0; } queue::~queue() { cout << "distructor "<<endl; delete []a; } void queue::insert(int i) { if(isfull()) {cout<<"\n\n******\nQueue is FULL !!!\nNo insertion allowed further.\n******\n"; return ; } a[rear] = i; rear++; }

} int queue::isfull() { if(rear == SIZE) return 1; else return 0; } void main() { //clrscr(); queue q; q.insert(1); q.insert(2); cout << "test "<<endl; cout<<"\n"<<q.remove(); cout<<"\n"<<q.remove(); cout<<"\n"<<q.remove(); getch(); }

2. Queue implementation using Single linked list #include <iostream.h> #include <process.h> struct node { node *next ; int info; }; class queue { node *Q, *n, *t; public : queue () {Q=n=t=NULL; } void insert(); void qdelete(); void display(); }; void queue::insert() { int item ; n=new node; cout<<"enter tem to be insert \n"; cin>>item; n->info=item; n->next=NULL; if (Q==NULL) { Q=n ; t=n ; } else { t->next=n; t=n; } } void queue :: qdelete ( ) { if (Q!=NULL) Q=Q->next; else cout<<"Q is empty \n"; } void queue :: display ( ) { node *temp; for (temp=Q; temp!=NULL;temp=temp->next) cout<<""<<temp->info; } void main ( ) { int choice; queue p; while (1) { cout<<"1.insert 2. delete 3. display 4. exit \n"; cin>>choice; switch (choice) { case 1 :p.insert (); break; case 2 :p.qdelete(); break; case 3 :p.display (); break; case 4 :exit (0); } } }

3. Circular Program using arrays:

#include <iostream.h> class cqueue { int *q; int max,f,r; public: cqueue(int n) { max = n; q = new int[n]; f = -1; r = -1; } int isfull() { if ( (r+1)%max == f) return 1; else return 0; } int isempty() { if( (f==r) && (f == -1) ) return 1; else return 0; } void enqueue() { r = (r+1) % (max); if (f == -1) f =0; cout << "ener the element \n"; cin >> q[r]; cout << r; } 4. Circular single linked list Operations : 1. Creating a circular linked list 2. Inserting a new node in the existing list 3. Deleting an existing node from the list 4. Displaying the existing list */ #include<iostream.h> struct node { int info; node *next; }; class clist { node root, prev, newnode, temp; public: clist () { //root=prev=newnode=temp=NULL; } void create (); void insert ();

void dequeue () { int ele; ele = q[f]; cout << "element " <<ele<<" "<<f<<endl; if (f == r) { f=-1; r=-1;} else f = (f+1) % (max); } }; void main() { int n,ch; cout << "enter the size of the circular queue "; cin >> n; cqueue t(n); do { cout << " choice 1 add 2 delete 3 exit \n" ; cin >> ch; switch (ch) { case 1: if (t.isfull() ) cout << "queue is full tray again "; else t.enqueue(); break; case 2: if (t.isempty() ) cout << "queue is empty "; else t.dequeue(); break; case 3: break; } }while (ch != 3); }

If (tempnext=root) {newnodenext=root; tempnext=newnode; else { newnodenext=tempnext; tempnext=newnode; } } } // end of insert void Clist :: delet () { node temp; int pos, i; cout<<"Enter the position of the node to be deleted"<<endl; cin>>pos; If (pos = = 1) { root = rootnext; while (tempnext! = newnodenext) temp=tempnext; }

void delet (); void display (); }; void clist :: create ( ) { int item; newnode = new node; cout<<"Enter the item to be inserted"<<endl; cin>>item; newnodeinfo=item; newnodenext=NULL; while (item! = -999) {If (root == NULL) root = newnode; else prevnext = newnode; prev = new node; prevnext = root; newnode=new node; cout<<"Enter item -999 at the end"<<endl; cin>>item; newnodeinfo = item; newnode next = NULL; }} void clist :: insert () { node newnode, temp; int item, pos, i; newnode = new node; cout<<"Enter the item"<<endl; cin>>item; newnodeinfo=item; newnodenext=NULL; cout<<"Enter the position"<<endl; cin>>pos; If (pos = = 1) { temp = root; newnodenext=root; root=newnode; while(tempnext! =newnode) { temp=tempnext; } tempnext==root; } else { temp = root; i=2; while ((i<POS)&&(tempnext!=root)) { temp=tempnext; i++; } }

else {

temp=root; i=2; while ((i<pos)&&(tempnext!=root)) { temp = tempnext; i++; } If (tempnext! = root) tempnext=tempnextnext; else cout<<"These is no node to delete"<<endl; } } void clist :: display () { node temp; temp = root; cout<<""<<tempinfo; temp=tempnext; while (temp!=root) { cout<<""tempinfo; temp=tempnext; } } void main () { clist C; int choice; c.create (); while (1) { Cout<<"1. Insert"<<Endl; Cout<<"2. delete"<<Endl; Cout<<"3. display"<<Endl; Cout<<"4. exit"<<Endl; Cout<<"Enter UR Choice"<<Endl; Cin>>choice; switch (choice) { case 1 : C.Insert (); break; case 2 : C.delet (); break; case 3 : C.display (); break; case 4 : exit ( 0 ); break; } } }

5. Priority queue #include <iostream> class priqueue { private: int maxsize,r; int *x; public: int isfull() void priqueue::show() { cout << "the contents of the queue are for (int i=0; i<=r;i++) cout << x[i] << " "; cout << endl; }

";

{if (r >= maxsize-1) return 1; else return 0; } int isempty() {if (r == -1) return 1; else return 0; } priqueue(int m) { maxsize = m;r=-1; x = new int[maxsize-1]; } void insert(int t) { int i, p; x[++r] = t; cout << "test" <<endl; for (i=1; i <=r ; i++) // sort it using insertion sort method {int index = x[i]; for (int j = i; ((j>0) && (x[j-1] >index ) ); j--) x[j] = x[j-1]; x[j] = index; }} void show(); int extractmin() { int e = x[0]; for (int i=1; i<=r;i++) x[i-1] =x[i]; r--; return e; }};

// main int main() { int n,ch,ele; cout << "enter the size of the queue " ; cin >> n; priqueue pq(n); do { cout << "enter the choice 1 add 2 << delete 3 display "; cin >> ch; switch(ch) { case 1: if (pq.isfull()) cout << "queue is full \n" else {cout << "ener the element "; cin >> ele; pq.insert(ele); } break; case 2: if (pq.isempty() ) cout << "queue is empty " <<endl; else cout << "element is " << pq.extractmin(); case 3:pq.show(); break; } }while(ch!=4); }

6. Program: dequeue using array #include <iostream.h> #include <stdlib.h> class abc { int q[10]; int max; int f,r; public: abc(int n) {max = n; f=-1; r=-1;} int lisfull() { cout << "left"<<f<<endl; if (f < 0) return 1; else return 0; } int risfull() { if (r == max-1) return 1; else return 0; } int isempty () { if (f == r) return 1; else return 0; } void lpush(int ele) {f =f-1; int main() { system("clear"); int n,ch,d,x; cout << "this is test" <<endl; cout << "enter the size of the queue "<<endl; cin >> n; abc t(n); do { cout << "enter the choice 1 add 2 pop 3 exit "; cin >> ch; switch(ch) { case 1: cout <<"enter the direction 1 left 2 right "<<endl; cin >> d; if (d == 1) { if (t.lisfull()) cout << "que full in this side"<<endl; else {cout << "enter the element insert" <<endl; cin >>x; t.lpush(x); } } else {if (t.risfull()) cout << "que full in this side" <<endl; else {cout <<"enter element "<<endl; cin >> x;

q[f] = ele; } void rpush(int ele) { r++; q[r] = ele; } int lpop() {int ele; ele = q[++f]; if (f == r) {f = -1; r=-1;} return (ele); } int rpop() {int ele; ele = q[r--]; if (f == r) {f =-1;r=-1;} return (ele); } }; III. Linked list 1. Single linked list program #include <iostream.h> struct node { int ele; node *next; }; class list { node *start,*t; int n; public: list () {t=start = NULL;n = -1;} node* newnode() { node *x = new node();

t.rpush(x); } } break; case 2: cout << "enter the direction " <<endl; cin >> d; if (t.isempty() ) cout << "queu is empty " <<endl; else if(d == 1 ) cout << "element " <<t.lpop(); else cout << "element " <<t.rpop(); break; case 3: break; } }while(ch != 3); }

void display() { t = start; while(t != NULL) { cout << t->ele<< " ";t = t->next;} cout <<endl; } void list :: largest () { int big; big=start->ele; for(t=start; t!=NULL; t=t->next) { if (t->ele > big) big=t->ele; } cout<<"Largest="<<big; } void list :: smallest () { int small; small= start->ele; for(t=start; t!=NULL; t=t->next) if (t->ele < small) small = t->ele; cout<<"smallest="<<small; } void list :: sort () { int temp; node *i, *j; for (i=start; i!=NULL; i=i->next) { for (j=i->next; j!=NULL; j=j->next) {

if(x==NULL) { cout<<"Out of memory\n";} cout << "enter the element "<<endl; cin>>x->ele; x->next = NULL; n++; return x; } void addnode() { int p; if (start == NULL ) {cout << "create a new list "; start = newnode();} else { node *temp; t= start;

cout << "enter the position 0 .. n "<<endl; cin >> p; if (p == 0) {cout << " add at front of the list \n " ; temp=newnode(); temp->next = start; start = temp; } else { while( (t != NULL) &&(--p > 0) ) t = t->next; if ( t == NULL) cout << "position not exists\n " ; else if( t->next == NULL) { cout << "add node at the end of the list " <<endl; t->next = newnode(); } else { temp = newnode(); temp->next = t>next; t->next = temp; } } } } void list :: ndelete () { int p; if (start == NULL ) cout << "list not exists "<<endl; else { cout<<"enter the position of the node to be deleted 0 .. n"<< endl; cin>>p; if (p == 0) start = start->next; else { for (t = start; (t->next->next != NULL ) && (p>1) ; t = t->next ) p--; if (p>= 2 ) cout << "the position not exists \n; else if (t->next->next == NULL ) //delete node at end of a list { cout << "delete node at end of a list " <<endl; t->next = NULL; } else t->next = t->next->next; } } } 2. Double linked list: #include<iostream.h> #include<process.h> struct node { int info; node *left,*right;

if (i->ele > j->ele) { temp=i->ele; i->ele=j->ele; j->ele=temp; } } } } void list :: reverse () { node *t1,*t2,*t3; t2 = t3 = NULL; t1 = start; while(t1) { start = t1; t2 = t1->next; t1->next=t3; t3=t1; t1=t2; } } }; // end of class void main() { list t; int ch; do { cout << "1 add 2 dis 3 delete 4 big 5 small 6 reverse 7 sort 8 exit " <<endl; cin >> ch; switch(ch) { case 1: cout << t.addnode(); break; case 2: t.display(); break; case 3: t.ndelete(); break; case 4: t.largest(); break; case 5: t.smallest(); break; case 6: t.reverse(); break; case 7: t.sort(); break; case 8: break; } }while(ch != 8); return 0; }

void list :: ndelete () { node *temp,*nprev,*nnext; int pos; temp = root;

}; class list { node *root; public : list () { root = NULL; void create (); void insert (); void ndelete (); void largest (); void smallest (); void sort (); void display(); };

void list :: create () // create a new list {int ch; node *news,*prev; cout <<"enter your choice 1 yes 0 stop " <<endl; cin >> ch; while (ch!=0) { news = new node; cout<<"Enter the item to be inserted"; cin>>news->info; news->left = NULL; news->right = NULL; if (root == NULL) root = prev = news; else { prev->right = news; news->left=prev; prev = news; } cout<<"Enter your choice 1 yes 0 stop"<<endl; cin>>ch; } } void list :: insert () // insert a node at a particular position { node *nnode,*temp; int pos, i; nnode = new node; cout<<"Enter the new item to be inserted"<<endl; cin>>nnode->info; nnode->left=NULL; nnode->right=NULL; cout<<"Enter the position"<<endl; cin>>pos; if (pos==1) { nnode->right= root; root->left = nnode; root = nnode; } else { temp=root; i=2; while((i<pos)&&(temp->right!=NULL) ) { temp=temp->right; i++; } if(temp->right == NULL) // add at last

cout<<"enter the position of the node to be deleted"<< endl; cin>>pos; while (--pos) { if ((pos == 0) || (temp == NULL)) { cerr <<"such position found tray again; cout << "enter the new positions \n"; cin >> pos; temp = root; } else temp=temp->right; } if (temp->left == NULL ) // root node { temp = root; root = root->right; root->left = NULL; } else if(temp->right == NULL) // last node temp->left->right = NULL; else { nprev= temp->left; nnext = temp->right; nprev->right = nnext; //temp->right; nnext->left = nprev; // temp->left; } delete temp; }

void list :: sort () { int temp; node *i, *j; for (i=root; i!=NULL; i=i->right) { for (j=i->right; j!=NULL; j=j->right) { if (i->info>j->info) { temp=i->info; i->info=j->info; j->info=temp; } } } }

void list :: display () { node *temp; temp = root; while (temp!=NULL) { cout<<" "<<temp->info; temp=temp->right;

{ } else {

temp->right= nnode; nnode->left=temp; } nnode->right = temp->right; temp->right->left= nnode; temp->right= nnode; nnode->left= temp;

} cout <<endl; void main () { list l; int choice; cout <<"hellow this is the time to create a new linked list "<<endl; l.create (); while ( 1 ) { cout<<"1. Insert"<<endl; cout<<"2. delete"<<endl; cout<<"3. largest"<<endl; cout<<"4. smallest"<<endl; cout<<"5. sort"<<endl; cout<<"6. display"<<endl; cout<<"7. Exit"<<endl; cout<<"Enter your choice"<endl; cin>>choice; switch (choice) { case 1 :l.insert (); break; case 2: l.ndelete (); break; case 3: l.largest(); break; case 4: l.smallest(); break; case 5: l.sort (); break; case 6: l.display (); break; case 7: exit (0); } } }

} } } void list :: largest () { int big; node *temp; temp=root ; big=temp->info; while(temp!= NULL) { if (temp->info>big) big=temp->info; temp = temp->right; } cout<<"Largest="<<big<<endl; } void list :: smallest () { int small; node *temp; temp=root; small=temp->info; while(temp != NULL) { if (temp->info<small) small = temp-info; temp= temp->right; } cout<<"smallest="<<small<<endl; }

III. Binary search tree Create a binary search tree and traverse the tree in inorder preorder postorder #include <iostream.h> #include <process.h> void tree :: inorder (node *r) struct node { { node *left; if (r!=NULL) int info; { inorder (r->left); node *right; cout<<r->info; }; inorder (r->right); class tree } {public : } node *root, *temp; void tree :: postorder (node *r) tree () {root=temp=NULL; } { if (r != NULL) void create (); { node * addnode(node *,int); postorder(r->left); void preorder (node *);\ postorder(r->right); void inorder (node *);\ cout<<r->info; void postorder (node *);\ } }; } void tree :: preorder (node *r) node * tree :: addnode (node *r, int num) { {if (r==NULL) if (r!=NULL) { r=new node; { r->info=num; cout<<r->info; r->left=r->right=NULL; preorder (r->left); } preorder (r->right); else }

{ if (num<r->info) r->left=addnode (r->left, num); else r->right=addnode (r->right, num); } return (r);} void tree :: create ( ) {int n, num, i=0; cout<<"enter how many numbers you want"; cin>>n; for(i=0; i<n; i++) { cin>>num; root=addnode (root, num); }}

} void main ( ) { tree t ; t.create ( ); cout << " pre order traversal "; t.preorder (t.root); cout << " \n post order traversal "; t.postorder (t.root); cout << "\n inorder traversal "; t.inorder (t.root); }

2 create a binary search tree and find the depth of the tree void tree :: create ( ) #include <iostream.h> { struct node int n, num, i=0; { cout<<"enter how many numbers you want"; node * left; cin>>n; int info; for(i=0; i<n; i++) node *right; { }; cin>>num; class tree root=addnode (root, num); { public : } node *root, *temp; } tree ( ) void tree::calcdepth (node*r, int level, int & d) {root=temp=NULL; } { void create(); if (r!=NULL) node * addnode(node *r, int ); { void calcdepth (node*r,int ,int&); if (level>d) d=level; }; calcdepth (r->left, level+1, d); node* tree::addnode (node*r, int num) calcdepth (r->right, level+1, d); { } if (r==NULL) } { r=new node; //create and add node funs are save as binary r->info=num; search tree. r->left=r->right=NULL; void main ( ) } { else tree t; {if (num<r->info) int level, d; r->left=addnode (r->left, num); level = d = 0; else t.create ( ); r->right=addnode (r->right, num); t.calcdepth(t.root, level, d); } cout<<"depth="<< d+1; return (r); cout<<"level="<<d; } }

3. Graph: implementation of prims algorithm


#include <iostream.h> #include <conio.h> #define ROW 7 #define COL 7 #define infi 5000 //infi for infinity class prims { int graph[ROW][COL],nodes; public: prims(); void createGraph(); void prims :: primsAlgo(){ int selected[ROW],i,j,ne; //ne for no. of edges int false=0,true=1,min,x,y; for(i=0;i<nodes;i++) selected[i]=false; selected[0]=true; ne=0; while(ne < nodes-1){ min=infi; for(i=0;i<nodes;i++) { if(selected[i]==true){ for(j=0;j<nodes;j++){

void primsAlgo(); }; prims :: prims(){ for(int i=0;i<ROW;i++) for(int j=0;j<COL;j++) graph[i][j]=0; } } void prims :: createGraph(){ int i,j; cout<<"Enter Total Nodes : "; cin>>nodes; cout<<"\n\nEnter Adjacency Matrix : \n"; for(i=0;i<nodes;i++) for(j=0;j<nodes;j++) cin>>graph[i][j]; //Assign infinity to all graph[i][j] where weight is 0. for(i=0;i<nodes;i++){ for(j=0;j<nodes;j++){ if(graph[i][j]==0) graph[i][j]=infi; } } } }

if(selected[j]==false){ if(min > graph[i][j]) { min=graph[i][j]; x=i; y=j; } } } selected[y]=true; cout<<"\n"<<x+1<<" --> "<<y+1; ne=ne+1; } } void main(){ prims MST; clrscr(); cout<<"\nPrims Algorithm to find Minimum Spanning Tree\n"; MST.createGraph(); MST.primsAlgo(); getch(); }

M.L.S.SATYANARAYANA Lect. Dept. Of Computer Science Aditya Degree & PG College Kakinada Email : satya_mls@yahoo.com

Vous aimerez peut-être aussi