1 Visit : www.EasyEngineeering.net

UNIT – 1 : DATA ABSTRACTION AND OVERLOADING Overview of C++ – Structures – Class Scope and Accessing Class Members – Reference Variables – Initialization – Constructors – Destructors – Member Functions and Classes – Friend Function – Dynamic Memory Allocation – Static Class Members – Container Classes and Integrators – Proxy Classes – Overloading : Function overloading and Operator Overloading. 1.1 OVERVIEW OF C++ OOP as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data closely to the functions that operate on it and protects it from accidental modification from outside junctions. It allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The data of an object can be accessed only the functions associated with the object. C++ is a general purpose programming language. The C++ language inherits a lot of C language syntax. That’s why people who know C Programming language can easily learn C++. This content is written for people who want to learn C++ Programming Language absolutely from scratch. In this content you will find useful information about the following C++ topics. Features        

Emphasis is on data rather than procedure. Improvement over the structured programming paradigm. Data structures are designed such that they characterize the object. Functions that operate on the data of an object are tied together in the data structure. Data is hidden that cannot be accessed by external functions. Object may communicate with each other through functions. New data and functions can be added easily. Follow bottom up approach in program design.

1.1.1 BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING The object oriented programming approach is based on certain concepts that overcome the drawbacks of conventional programming approaches . These include  Objects  Classes  Abstraction

Visit : www.EasyEngineeering.net

2 Visit : www.EasyEngineeering.net

    

Encapsulation Inheritance Polymorphism Dynamic binding Message Passing

Objects Objects are the basic unit of OOP. They are instances of class, which have data members and uses various member functions to perform tasks. Class It is similar to structures in C language. Class can also be defined as user defined data type but it also contains functions in it. So, class is basically a blueprint for object. It declare & defines what data variables the object will have and what operations can be performed on the class's object. Abstraction Abstraction refers to showing only the essential features of the application and hiding the details. In C++, classes provide methods to the outside world to access & use the data variables, but the variables are hidden from direct access. This can be done access specifiers. Encapsulation It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class. Inheritance Inheritance is a way to reuse once written code again and again. The class which is inherited is called base calls & the class which inherits is called derived class. So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base class, hence making code reusable. Polymorphism This is a way to use the same interface for the different data types. In simple words it can be described as using the same name for member functions that have different arguments. Polymorphism is not only related to member functions. It's discussed in more details in "C++ Polymorphism" Dynamic binding

Visit : www.EasyEngineeering.net

3 Visit : www.EasyEngineeering.net

Dynamic binding is determining the method to invoke at runtime instead of at compile time. Dynamic binding is also referred to as late binding. Message passing Message passing is a form of communication between objects, processes or other resources used in object-oriented programming, inter-process communication and parallel computing. 1.1.2. BENEFITS OF OOPS  Through inheritance, we can eliminate redundant code and extend the use of existing classes which is not possible in procedure oriented approach.  We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch which happens procedure oriented approach. This leads to saving of development time and higher productivity.  The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.  It is possible to have multiple instances of object to co-exist without any interference.  It is possible to map objects in the problem domain to those in the program.  It is easy to partition the work in a project based on objects .  The data-centered design approach enables us to capture more details of a model in implementable from.  Object oriented systems can be easily upgraded from small to large systems.  Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler.  Software complexity can be easily managed. 1.1.3. DEMERITS OF OOPS  With OOP, classes tend to be overly generalized.  One need to do proper planning and proper design for OOPs.  The program with OOP, programmer need proper skills such as design skills, programming skills , thinking in terms of objects, etc. 1.1.4. OBJECT ORIENTED LANGUAGES This can be classified into two categories : (1)Object based programming languages This type of language support the following features Data encapsulation Data hiding and access mechanisms

Visit : www.EasyEngineeering.net

4 Visit : www.EasyEngineeering.net

Automatic initialization and clear up objects Operator overloading Example : Ada programming (2)Object oriented programming languages Object oriented programming supports all of object programming features along with two additional features namely inheritance and dynamic binding Example : C++,Java etc 1.1.5. Features of C++ C++ is object oriented programming language and it is a very simple and easy language, this language have following features.

      

Simple Portability Powerful Platform dependent Object oriented oriented Case sensitive Compiler based

Visit : www.EasyEngineeering.net

5 Visit : www.EasyEngineeering.net

 Syntax based language  Use of Pointers 1.1.6. TOKENS The smallest individual unit is a program is known as a token. A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of tokens: identifiers, keywords, literals, operators, punctuators, and other separators. A stream of these tokens makes up a translation unit. C++ has the following tokens.  Keywords     

Keywords are the words that convey a special meaning to the language compiler. These are reserved for special purpose. It must not be used as normal identifier names. Many of the keywords are common to both C and C++ C++ have additional keywords to enhance its feature and make it an object oriented languages.

 Identifiers  Identifier refers to the name of the variables, functions arrays, classes etc. Created by the programmer.  They are the fundamental requirement of any language.  Each language has its own rules for naming identifiers.

Visit : www.EasyEngineeering.net

6 Visit : www.EasyEngineeering.net

 Constants  Constants or literals are data item that never change their value during the execution of a program. C++ allows several kinds of literals.    

Integer constant Character constant Floating constant String literal

 Strings  C++ supports two types of string representation.  C style character string  String class type  Operators 1.1.7. OPERATORS  Operators are special type of functions, that takes one or more arguments and produces a new value. For example : addition (+), substraction (-), multiplication (*) etc, are all operators. Operators are used to perform various operations on variables and constants.  Unary operators are those operators that require one operator to operate upon.

Visit : www.EasyEngineeering.net

7 Visit : www.EasyEngineeering.net

Types of operators 1. 2. 3. 4. 5. 6. 7. 8. 9.

Assignment Operator Mathematical Operators Relational Operators Logical Operators Bitwise Operators Shift Operators Unary Operators Ternary Operator Comma Operator

Assignment Operator ( = ) Operates '=' is used for assignment, it takes the right-hand side (called rvalue) and copy it into the left-hand side (called lvalue). Assignment operator is the only operator which can be overloaded but cannot be inherited.

Mathematical Operators There are operators used to perform basic mathematical operations. Addition (+) , subtraction (-) , diversion (/) multiplication (*) and modulus (%) are the basic mathematical operators. Modulus operator cannot be used with floating-point numbers. C++ and C also use a shorthand notation to perform an operation and assignment at same type. Example, int x=10; x += 4 // will add 4 to 10, and hence assign 14 to X. x -= 5 // will subtract 5 from 10 and assign 5 to x.

Relational Operators These operators establish a relationship between operands. The relational operators are : less than (<) , grater thatn (>) , less than or equal to (<=), greater than equal to (>=), equivalent (==) and not equivalent (!=). You must notice that assignment operator is (=) and there is a relational operator, for equivalent (==). These two are different from each other, the assignment operator assigns the value to any variable, whereas equivalent operator is used to compare values, like in if-else conditions, Example int x = 10; //assignment operator

Visit : www.EasyEngineeering.net

8 Visit : www.EasyEngineeering.net

x=5; // again assignment operator if(x == 5) // here we have used equivalent relational operator, for comparison { cout <<"Successfully compared"; }

Logical Operators The logical operators are AND (&&) and OR (||). They are used to combine two different expressions together. If two statement are connected using AND operator, the validity of both statements will be considered, but if they are connected using OR operator, then either one of them must be valid. These operators are mostly used in loops (especially while loop) and in Decision making. Bitwise Operators There are used to change individual bits into a number. They work with only integral data types like char, int and long and not with floating point values.    

Bitwise AND operators & Bitwise OR operator | And bitwise XOR operator ^ And, bitwise NOT operator ~

They can be used as shorthand notation too, & = , |= , ^= , ~= etc. Shift Operators Shift Operators are used to shift Bits of any variable. It is of three types, 1. Left Shift Operator << 2. Right Shift Operator >> 3. Unsigned Right Shift Operator >>> Unary Operators These are the operators which work on only one operand. There are many unary operators, but increment ++ and decrement -- operators are most used. Other Unary Operators : address of &, dereference *, new and delete, bitwise not ~, logical not !, unary minus - and unary plus +.

Visit : www.EasyEngineeering.net

9 Visit : www.EasyEngineeering.net

Ternary Operator The ternary if-else ? : is an operator which has three operands. int a = 10; a > 5 ? cout << "true" : cout << "false"

Comma Operator This is used to separate variable names and to separate expressions. In case of expressions, the value of last expression is produced and used. Example : int a,b,c; // variables declaration using comma operator a=b++, c++; // a = c++ will be done.

sizeof operator in C++ sizeOf is also an operator not a function, it is used to get information about the amount of memory allocated for data types & Objects. It can be used to get size of user defined data types too. sizeOf operator can be used with and without parentheses. If you apply it to a variable you can use it without parentheses. cout << sizeOf(double); int x = 2; int i = sizeOf x;

typedef Operator typedef is a keyword used in C language to assign alternative names to existing types. Its mostly used with user defined data types, when names of data types get slightly complicated. Following is the general syntax for using typedef, typedef existing_name alias_name

Lets take an example and see how typedef actually works. typedef unsigned long ulong;

Visit : www.EasyEngineeering.net

10 Visit : www.EasyEngineeering.net

The above statement define a term ulong for an unsigned long type. Now this ulong identifier can be used to define unsigned long type variables. ulong i, j;

1.1.8. STRUCTURE OF C++ PROGRAM C++ Programming language is most popular language after C Programming language. C++ is first Object oriented programming language. We have summarize structure of C++ Program in the following Picture –

Structure of a C++ Program Section 1 : Header File Declaration Section 1. 2. 3. 4.

Header files used in the program are listed here. Header File provides Prototype declaration for different library functions. We can also include user define header file. Basically all preprocessor directives are written in this section.

Visit : www.EasyEngineeering.net

11 Visit : www.EasyEngineeering.net

Section 2 : Global Declaration Section 1. Global Variables are declared here. 2. Global Declaration may include  Declaring Structure  Declaring Class  Declaring Variable Section 3 : Class Declaration Section 1. Actually this section can be considered as sub section for the global declaration section. 2. Class declaration and all methods of that class are defined here. Section 4 : Main Function 1. Each and every C++ program always starts with main function. 2. This is entry point for all the function. Each and every method is called indirectly through main. 3. We can create class objects in the main. 4. Operating system call this function automatically. Section 5 : Method Definition Section 1. This is optional section . Generally this method was used in C Programming. Sample Program #include class person { char name[30]; int age; public : void getdata( ); void display( ); };

Visit : www.EasyEngineeering.net

12 Visit : www.EasyEngineeering.net

void person ::getdata( ) { cout<< “enter name :”; cin>>name; cout<<”enter age :”; cin>> age; } void person :: display( ) { cout<< “\n name :”<
Visit : www.EasyEngineeering.net

13 Visit : www.EasyEngineeering.net

1.1.9. CONCEPT OF DATATYPES The data types are used to create variables or your new data types. A variable is a amount of memory that has its own name and value. That's why it is important to know the built in data types, their properties and size. Definition : Data types are means to identify the type of data and associated operations of handling it.

C++ Data Types Type Name Int unsigned int bool char signed char unsigned char short

Bytes 4 4 1 1 1 1 2

Range of Values 2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 false or true 128 to 127 128 to 127 0 to 255 32,768 to 32,767

Visit : www.EasyEngineeering.net

14 Visit : www.EasyEngineeering.net

unsigned short Long unsigned long long long unsigned long long float double long double wchar_t

2 4 4 8 8 4 8 same as double 2

0 to 65,535 2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0 to 18,446,744,073,709,551,615 3.4E +/- 38 (7 digits) 1.7E +/- 308 (15 digits) Same as double 0 to 65,535

1.2. STRUCTURES  Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collection of data of different data types. For example: You want to store some information about a person: his/her name, age and salary  The struct keyword defines a structure type followed by an identifier (name of the structure).  Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure. For example: struct Person { char name[50]; int age; float salary; };

1.2.1. UNION A union is a user-defined type in which all members share the same memory location. This means that at any given time a union can contain no more than one object from its list of members. It also means that no matter how many members a union has, it always uses only enough memory to store the largest member. Unions in C++ is a user defined data type that uses the same memory as other objects from a list of objects. At an instance it contains only a single object.

Visit : www.EasyEngineeering.net

15 Visit : www.EasyEngineeering.net

Syntax: union union-type-name{ type member-name; type member-name; }union-variables; 1.2.2. Enumerated Data Type An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used. enum season { spring, summer, autumn, winter }; Here, the name of the enumeration is season. And, spring, summer and winter are values of type season. By default, spring is 0, summer is 1 and so on. You can change the default value of an enum element during declaration (if necessary). enum season { spring = 0, summer = 4, autumn = 8, winter = 12 }; 1.2.3. Derived Data Types Array : Array is a collection of similar Objects We can have array of Integers, Characters, Strings, any user defined types, etc. Since we can have any kind of collection (Integers, Characters, Strings, etc.) in an array, so in a generic way we can call array is a collection of similar objects. Arrays are fixed in size After declaring an array, we cannot change the size of the array. That means we can't reduce the size nor increase the size of an array. Elements of an array will be allocated contiguously in memory When we create an array then each element of an array will be allocated in contiguous memory locations. Contiguous memory locations means that just after the first element of an array,

Visit : www.EasyEngineeering.net

16 Visit : www.EasyEngineeering.net

second element will be present in the memory. And just after the second element, third element will be present, and so on. The first element of an array will have the lowest address and the last element will have the highest address. Elements of an array are accessed by an index Elements of an array are accessed by an index. The first element will have the index 0, second element will have the index 1, third will have the index 2 and so on. The last element will have index (n-1) where n is the number of elements in an array. Example : float a[3]; // declares array of 3 floats a[0], a[1], a[2] Int b[2] [4]; // declares a 2 dimensional array of integers. b[0][0], b[0][1], b[0][2], b[0][3], b[1][0], b[1][1], b[1][2], b[1][3], Functions in C++ Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check errors etc. Syntax of Function return-type function-name (parameters) { // function-body } return-type : suggests what the function will return. It can be int, char, some pointer or even a class object. There can be functions which does not return anything, they are mentioned with void. Function Name : is the name of the function, using the function name it is called. Parameters : are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list. void sum(int x, int y) { int z; z = x + y; cout << z; } int main() {

Visit : www.EasyEngineeering.net

17 Visit : www.EasyEngineeering.net

int a = 10; int b = 20; sum (a, b); } Here, a and b are sent as arguments, and x and y are parameters which will hold values of a and b to perform required operation inside function . Function body : is the part where the code statements are written. Declaring, Defining and Calling Function

Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Lets understand this with help of an example. #include < iostream.h> int sum (int x, int y); //declaring function int main() { int a = 10; int b = 20; int c = sum (a, b); //calling function cout << c; } int sum (int x, int y) //defining function { return (x + y); } Here, initially the function is declared, without body. Then inside main() function it is called, as the function returns sumation of two values, hence z is there to store the value of sum. Then, at last, function is defined, where the body of function is mentioned. We can also, declare & define the function together, but then it should be done before it is called. Pointers  A pointer is a variable that holds a memory address  This address is usually the location of another variable in memory.  Pointers are used in C++ program to access the memory and manipulate the address.

Visit : www.EasyEngineeering.net

18 Visit : www.EasyEngineeering.net

Address in C++ To understand pointers, you should first know how data is stored on the computer. Each variable you create in your program is assigned a location in the computer's memory. The value the variable stores is actually stored in the location assigned. To know where the data is stored, C++ has an & operator. The & (reference) operator gives you the address occupied by a variable. If var is a variable then, &var gives the address of that variable. Example 1: Address in C++ #include int main() { int var1 = 3; int var2 = 24; int var3 = 17; cout << &var1 << endl; cout << &var2 << endl; cout << &var3 << endl; } Output 0x7fff5fbff8ac 0x7fff5fbff8a8 0x7fff5fbff8a4

References  A reference is an alternative name for an object.  A reference variable provides an alias for a previously defined variable.  A reference declaration consists of a base type an & , a reference variable name equated to a variable name.  The general form of declaring a reference variable is type & ref_var = var_name Where , type is any valid C++ data type. ref_var is name of reference variable.

Visit : www.EasyEngineeering.net

19 Visit : www.EasyEngineeering.net

Example : int total; int &sum = total; total=100; Sum is declared as a reference variable for a variable total. 1.2.4. SYMBOLIC CONSTANTS There are two ways of creating symbolic constant in C++. 1.Using the qualifier constant. 2.Defining a set of integer constant using enum keyword. 1. Using the Qualifier Const  Any value declared as constant cannot be modified by the program.  Const can be used in a constant expresson, such as const int size=10; char name[size]; Using Enumeration  Naming integer constants is by enumeration. i.e., enum{x,y,z};  This defines x,y,z as integer constants with values 0,1,2 respectively. This is equivalent to const x=0; const y=1; const z=2; 1.2.5. DECLARATION OV VARIABLES  All variables must be declared before they are used in executable statements.  It allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use.  It also makes the program easier to understand because the variables are declared in the context of their use.

Visit : www.EasyEngineeering.net

20 Visit : www.EasyEngineeering.net

 The declaration of a variable generally takes the following format: type name; where type is any C++ data type; name is the name of the variable Example :

signed int value; unsigned short count;

 When more than one identifier of a type is being defined, a comma separated int of identifiers may follow the type specifier. Example : double salary, wage; Sample Program int main() { float x; float sum=0; for(int i=1;i<5;i++) { cin>>x; sum=sum+x; } float average; average=sum/(i-1); cout<
Visit : www.EasyEngineeering.net

21 Visit : www.EasyEngineeering.net

 Initial value mane be specified in the definition of a variable. Example : int val=1001; double price=314.70, discount =0.22; Dynamic initialization  One additional feature of C++ is that it permits initialization of the variables at run time. This is referred to as dynamic initialization.  A variable can be initialized at run time using expressions at the place of declaration. float avg; avg=sum/count; then the above two statements can be combined into one as follows: float avg = sum / count; It will initialize avg using the information available at run time. i.e., using the values of sum and count known at run time. Reference Variables  A reference variable provides an alias for a previously designed variable.  A reference variable is created as follows. data type of reference_name=variable name Example : float total=100; float &sum=total; 1.2.6. OPERATORS IN C++ C++ Operators Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations. C++ supports all operators of C, C++ introduces some new operators given as below: Symbols Name << Insertion operator.

Visit : www.EasyEngineeering.net

22 Visit : www.EasyEngineeering.net

>> :: ::* ->* .* new delete

Extraction operator. Scope resolution operator. Pointer-to-member declarator. Pointer-to-member operator. Pointer-to-member operator. Dynamic memory allocation operator. Memory release operator.

1.2.7. EXPRESSIONS An expression is a combination of operators, constants and variables arranged as per the rules of the language. There are different categories of an expression are discussed here.  Constant expressions: The expressions that comprise only constant values are called constant expressions. Some examples of constant expressions are 20, ‘ a‘ and 2/5+30 .  Integral expressions: The expressions that produce an integer value as output after performing all types of conversions are called integral expressions. For example, x, 6*xy and 10 +int (5.0) are integral expressions. Here, x and y are variables of type int.  Float expressions: The expressions that produce floating-point value as output after performing all types of conversions are called float expressions. For example, 9.25, x-y and 9+ float (7) are float expressions. Here, x 'and y are variables of type float.  Relational or Boolean expressions: The expressions that produce a bool type value, that is, either true or false are called relational or Boolean expressions. For example, x + y<100, m + n==a-b and a>=b + c .are relational expressions.  Logical expressions: The expressions that produce a bool type value after combining two or more relational expressions are called logical expressions. For example, x==5 &&m==5 and y>x I I m<=n are logical expressions.  Bitwise expressions: The expressions which manipulate data at bit level are called bitwise expressions. For example, a >> 4 and b<< 2 are bitwise expressions.  Pointer expressions: The expressions that give address values as output are called pointer expressions. For example, &x, ptr and -ptr are pointer expressions. Here, x is a variable of any type and ptr is a pointer.  Special assignment expressions: An expression can be categorized further depending upon the way the values are assigned to the variables.  Chained assignment: Chained assignment is an assignment expression in which the same value is assigned to more than one variable, using a single statement. For example, consider these statements. a = (b=20); or a=b=20;

Visit : www.EasyEngineeering.net

23 Visit : www.EasyEngineeering.net

In these statements, value 20 is assigned to variable b and then to variable a. Note that variables cannot be initialized at the time of declaration using chained assignment. For example, consider these statements. int a=b=30; // illegal int a=30, int b=30; //valid  Embedded assignment: Embedded assignment is an assignment expression, which is enclosed within another assignment expression. For example, consider this statement a=20+(b=30); //equivalent to b=30; a=20+30;

1.2.8. CONTROL STRUCTURES In a program, statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence, selection or iteration. Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met. C++ handles decision-making by supporting the following statements    

if statement switch statement conditional operator statement goto statement

Decision making with if statement The if statement may be implemented in different forms depending on the complexity of conditions to be tested. The different forms are, 1. 2. 3. 4.

Simple if statement If....else statement Nested if....else statement else if statement

Simple if statement The general form of a simple if statement is, if( expression ) {

Visit : www.EasyEngineeering.net

24 Visit : www.EasyEngineeering.net

statement-inside; } statement-outside; If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-inside' is skipped and only 'statement-outside' is executed. Example : #include< iostream.h> int main( ) { int x,y; x=15; y=13; if (x > y ) { cout << "x is greater than y"; } }

if...else statement The general form of a simple if...else statement is, if( expression ) { statement-block1; } else { statement-block2; } If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is skipped and 'statement-block2' is executed. Example : void main( ) { int x,y; x=15; y=18;

Visit : www.EasyEngineeering.net

25 Visit : www.EasyEngineeering.net

if (x > y ) { cout << "x is greater than y"; } else { cout << "y is greater than x"; } }

Nested if....else statement The general form of a nested if...else statement is, if( expression ) { if( expression1 ) { statement-block1; } else { statement-block2; } } else { statement-block3; } if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is executed otherwise 'statement-block2' is executed. Example : void main( ) { int a,b,c; clrscr(); cout << "enter 3 number"; cin >> a >> b >> c; if(a > b) {

Visit : www.EasyEngineeering.net

26 Visit : www.EasyEngineeering.net

if( a > c) { cout << "a is greatest"; } else { cout << "c is greatest"; } } else { if( b> c) { cout << "b is greatest"; } else { printf("c is greatest"); } } getch(); }

else-if ladder The general form of else-if ladder is, if(expression 1) { statement-block1; } else if(expression 2) { statement-block2; } else if(expression 3 ) { statement-block3; } else default-statement; The expression is tested from the top(of the ladder) downwards. As soon as the true condition is found, the statement associated with it is executed.

Visit : www.EasyEngineeering.net

27 Visit : www.EasyEngineeering.net

Example : void main( ) { int a; cout << "enter a number"; cin >> a; if( a%5==0 && a%8==0) { cout << "divisible by both 5 and 8"; } else if( a%8==0 ) { cout << "divisible by 8"; } else if(a%5==0) { cout << "divisible by 5"; } else { cout << "divisible by none"; } getch(); }

Looping in C++ In any programming language, loops are used to execute a set of statements repeatedly until a particular condition is satisfied

Visit : www.EasyEngineeering.net

28 Visit : www.EasyEngineeering.net

A sequence of statement is executed until a specified condition is true. This sequence of statement to be executed is kept inside the curly braces { } known as loop body. After every execution of loop body, condition is checked, and if it is found to be true the loop body is executed again. When condition check comes out to be false, the loop body will not be executed.

There are 3 type of loops in C++ language 1. while loop 2. for loop 3. do-while loop

while loop while loop can be address as an entry control loop. It is completed in 3 steps.   

Variable initialization.( e.g int x=0; ) condition( e.g while( x<=10) ) Variable increment or decrement ( x++ or x-- or x=x+2 )

Visit : www.EasyEngineeering.net

29 Visit : www.EasyEngineeering.net

Syntax : variable initialization ; while (condition) { statements ; variable increment or decrement ; }

for loop for loop is used to execute a set of statement repeatedly until a particular condition is satisfied. we can say it an open ended loop. General format is, for(initialization; condition ; increment/decrement) { statement-block; } In for loop we have exactly two semicolons, one after initialization and second after condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. for loop can have only one condition.

Nested for loop We can also have nested for loop, i.e one for loop inside another for loop. Basic syntax is, for(initialization; condition; increment/decrement) { for(initialization; condition; increment/decrement) { statement ; } }

do while loop In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. General format of dowhile loop is,

Visit : www.EasyEngineeering.net

30 Visit : www.EasyEngineeering.net

do { .... ..... } while(condition);

Jumping out of loop Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becocmes true, that is jump out of loop. C language allows jumping from one statement to another within a loop as well as jumping out of the loop. 1) break statement When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop. 2) continue statement It causes the control to go directly to the test-condition and then continue the loop process. On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle. Switch Statement  This is alternate to the cascaded if (if-else ladder). This switch statement causes a particular group of statement to be chosen from several available groups.  The selection is based upon the current value of variable or expression, which is included within the switch statement.  Nested switch is also possible.  If the expression or variable is of numeric type, the constant value need not be enclosed in either single quotation or double quotation mark.  If variable or expression is of character type, the constant value should be enclosed in single quotation mark ( ’ ).  If no case matching for corresponding value of the variable, default option will get executed. SYNTAX:

Visit : www.EasyEngineeering.net

31 Visit : www.EasyEngineeering.net

switch(expression/variable) { case constant-1: statement – sequence; break; case constant-2: statement – sequence; break; … default : statement – sequence; break; }   

Example: … int a, b, c; char opt, action[20]; cout << “iput a and b?” ; cin >> a >> b; cout << “your option(+, –, *)?”; opt = getchar(); switch(opt) { case ‘+’ : c = a + b; strcpy(action, “sum”); break; case ‘ – ’ : c = a – b; strcpy(action, “difference”); break; case ‘ * ’ : c = a – b; strcpy(action, “product”); break; default: strcpy(action, “invalid action”); } cout << action << “of the “<< a <<” and b is =” << c << endl; …

Visit : www.EasyEngineeering.net

32 Visit : www.EasyEngineeering.net

TERNARY OPERATOR/CONDITIONAL OPERATOR/THE ?: OPERATOR 

This statement just alternate to the “simple if”. The only major difference between “simple if” and “ternary operator” is that we cannot use “if statement inside printf() function, but we can use ternary operator inside printf() function. SYNTAX:Exp1 ? Exp2 : Exp3;  If Exp1 is evaluated to true than Exp2 is executed; otherwise Exp3 will be executed. Example: int x = 10, y = 20; cout << “The big number was” << (x > y ? x : y) << endl; 1.3. CLASS SCOPE AND ACCESSING CLASS MEMBERS CLASS SCOPE 

Two principal form of scope: local scope and file scope. The basic rule for scoping is that identifiers are accessible only within the block in which they were declared.  Local scope - local scope is scoped to block. Function bodies are example of blocks; they contain set declarations that includes their parameter. File scope has name that are external.

STORAGE CLASS   

   

Storage classes are used to determine the life time(existence) and accessibility of variable during the program execution. There are four different storage-class specifications in C: automatic, external, static and register. They are identified by the keywords auto, extern, static and register, respectively. The general syntax for storage class specification are: Storage-specifiers data-type variable-name; (or) [Storage-specifiers] data-type variable-name-1 [,variable-name-2…]; Storage class associated with a variable can sometime be established by the location of the variable declaration with in the program. Variables which are declared inside function are automatically treated as auto variable and can be referenced only within the function in which it is declared. Similarly, variable declared outside of all function are automatically treated as external / global variables. Code fragment shown below describe several typical variable declarations. auto int a, b, c; extern float root1, root2; static int count; register int a, b;

Visit : www.EasyEngineeering.net

33 Visit : www.EasyEngineeering.net

AUTOMATIC VARIABLE (auto)  Variables declared inside the functions are auto / local variables; they are accessible only with the function in which they are declared. They are created, the moment the function is called, and destroyed the moment function is exited.  Automatic variable defined in different function independent of one another, even though they have the same name. Formal argument declared in the function is also treated as auto variable.  It is not necessary to mention auto keyword explicitly in front of variable declaration.  An automatic variable does not retain its value once control is transferred out of its defining function. Therefore, any value assigned an automatic variable within the function will be lost once the function is exited.

{ /* auto variable declaration */ int x, y, sum; float avg; auto char name[30]; ….. } EXTERNAL / GLOBAL VARIABLE (extern)  Variables declared outside of all function are external / global variable. It is not required to mention extern keyword explicitly.  An external variable can be assigned a value within one function, and this value can be used within another function.  For an external variable definition, there is no extern keyword required. But for external variable declaration, extern keyword has to be explicitly specified. For external variable declaration memory will not be allocated. If the function definition precedes the external variable definition, then the function must include a declaration for the external variable. The name and its data type present in the declaration must match with the corresponding external variable definition that appears outside of the function. Example: void readX( ) { extern int x; // external variable declaration cout << “x?”; cin >> x; } int x; // external variable definition main( ) {

Visit : www.EasyEngineeering.net

34 Visit : www.EasyEngineeering.net

readX( ); cout << “X=” << x << endl; x += 10; cout << “X =% d” << x << endl; } STATIC VARIABLES  Static variables are permanent variables within their own function or file.  Unlike global variables they are not known outside the function or file, but they maintain their values between function calls.  Either local variable or external variable can be qualified with static keyword. Based on that there are two types of static variable exist. They are local static and global static. STATIC LOCAL VARIABLES  If the variable defined with in the function is qualified with static, it is called local static variable.  Local Static variables are created, when you call the function first time and retain its values throughout the program life cycle, but accessible only with in the function in which it is defined. Similar to local variable outside the function it is not accessible.  When function is called, its local variables are created, and upon its exit they are destroyed. So that local variable cannot retain their value between calls. But local static variable are capable of retain its value between function call. Example:

#include #include long int fibo() { static long int f1 = – 1, f2 = 1; long int f; f = f1 + f2; f1 = f2; f2 = f; return f; } main() { int cnt, n; clrscr(); cout << "How many fibonacci do you need to print: "; cin >> n; for(cnt = 1; cnt <= n; cnt++)

Visit : www.EasyEngineeering.net

35 Visit : www.EasyEngineeering.net

cout << “\t” << fibo(); getch(); }

Output How many fibonacci do you need to print 0 1 1 2 3 5 8 

Suppose if variable f1, f2 is not declared as static variable, it does not retain its old value assigned in the previous function call. So that every time f1 and f2 will be initialized to –1 and 1, so that output will always zero, because f1 and f2 will be treated as auto variable. GLOBAL STATIC VARIABLES  If an external variable or global variable is qualified with static, they are called global static variables. Static global variable is accessible and known only from different functions with in the same file in which it is defined, but from outside of file, it is not accessible. It has life time through out the program.  Global variables are accessible not only accessible within the file in which it is declared, but outside of file also it is accessible. Example: static int x; // static global variable x cannot be accessible outside file void main () { read (); cout << “x = ” << x; } void read () { cout << “ x? ”; } cin >> x; REGISTER VARIABLE  Only local/auto variable of type int, char, int*, char* can be declared as register variable.  The register specifies request the compiler to keep the values of a variable in the registry of the CPU rather than in main memory, where normal variables are stored.  Operation on a register variable could occur much faster than on a normal variable because the register variable was actually held in the CPU & did not require memory access time to determine or modify its value.  Larger objects like’s arrays obviously cannot be stored in a register, since it will take more register area.  Global Register variable are not allowed to declared as register variable.

Visit : www.EasyEngineeering.net

36 Visit : www.EasyEngineeering.net

Example:register int count; register char choice;

Function : 

A problem in C++ can be decomposed into subprograms, each of which can be coded directly or further decomposed. This is the method of stepwise refinement. The function is used to write code for these directly solvable sub problems.  These functions are combined into other functions, and ultimately used in main( ) to solve the original problem. FUNCTION DEFINITION  The general form of function definition is: return-type function-name(parameter-list) { body of function; }  Function may return any type of data except an array.  Parameter list are comma-separated list of variables names & their associated types.  Function may be without parameter, in which case the parameter list is empty.  Even if there are no formal parameters, the parenthesis is still required.  The code that constitutes the body of function is hidden from the rest of the program.  Parameter-list in the function definition are called formal parameters. They are the way the calling program can pass message to function for process.  Formal parameters behave like other local variables inside function. They are created the moment function is called and destroyed the moment function exited.  Such a parameters in C++ are call-by-value. Example: #include const char BELL = '\a'; //function definition for repeated bell ringing void ring(int k) { int i; for (i = 0; i < k; ++i) cout << BELL; } int main() { int n; cout << "\nInput a small positive integer: "; cin >> n; ring(n); // function call }

Visit : www.EasyEngineeering.net

37 Visit : www.EasyEngineeering.net

THE RETURN STATEMENT The return statement is used for two purposes. So the return statement has following two form: return; return expression; (i) when first form is encountered in the function, program control is immediately passed back to the calling environment. (ii) when the second form is used, then the value of the expression is returned to the calling program as well. Some examples are: return; return 3; return (a + b); Example: #include //find the minimum of two ints. int min(int x, int y) { if (x < y) return x; else return y; } int main() { int j, k, m; cout << "Input two integers: "; cin >> j >> k; m = min(j, k); cout << '\n' << m << " is the minimum of " << j << " and " << k << endl; }

Storage Classes in C++ Storage classes are used to specify the lifetime and scope of variables. How storage is allocated for variables and how variable is treated by complier depends on these storage classes. These are basically divided into 5 different types : 1. Global variables 2. Local variables 3. Register variables

Visit : www.EasyEngineeering.net

38 Visit : www.EasyEngineeering.net

4. Static variables 5. Extern variables Global Variables These are defined at the starting , before all function bodies and are available throughout the program. using namespace std; int globe; // Global variable void func(); int main() { ..... }

Local variables They are defined and are available within a particular scope. They are also called Automatic variable because they come into being when scope is entered and automatically go away when the scope ends. The keyword auto is used, but by default all local variables are auto, so we don't have to explicitly add keyword auto before variable dedaration. Default value of such variable is garbage.

Register variables This is also a type of local variable. This keyword is used to tell the compiler to make access to this variable as fast as possible. Variables are stored in registers to increase the access speed. But you can never use or compute address of register variable and also , a register variable can be declared only within a block, that means, you cannot have global or static register variables.

Static Variables Static variables are the variables which are initialized & allocated storage only once at the beginning of program execution, no matter how many times they are used and called in the program. A static variable retains its value until the end of program. void fun()

Visit : www.EasyEngineeering.net

39 Visit : www.EasyEngineeering.net

{ static int i = 10; i++; cout << i; } int main() { fun(); // Output = 11 fun(); // Output = 12 fun(); // Output = 13 } As, i is static, hence it will retain its value through function calls, and is initialized only once at the beginning. Static specifiers are also used in classes, but that we will learn later.

Extern Variables This keyword is used to access variable in a file which is declared & defined in some other file, that is the existence of a global variable in one file is declared using extern keyword in another file.

Introduction to Classes and Objects The classes are the most important feature of C++ that leads to Object Oriented programming. Class is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating instance of that class. The variables inside class definition are called as data members and the functions are called member functions.

Visit : www.EasyEngineeering.net

40 Visit : www.EasyEngineeering.net

For example : Class of birds, all birds can fly and they all have wings and beaks. So here flying is a behavior and wings and beaks are part of their characteristics. And there are many different birds in this class with different names but they all posses this behavior and characteristics. Similarly, class is just a blue print, which declares and defines characteristics and behavior, namely data members and member functions respectively. And all objects of this class will share these characteristics and behavior. More about Classes 1. Class name must start with an uppercase letter. If class name is made of more than one word, then first letter of each word must be in uppercase. Example, class Study, class class1 etc 2. Classes contain, data members and member functions, and the access of these data members and variable depends on the access specifiers (discussed in next section). 3. Class's member functions can be defined inside the class definition or outside the class definition. 4. Class in C++ are similar to structures in C, the only difference being, class defaults to private access control, where as structure defaults to public. 5. All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation, Abstraction etc. 6. Objects of class holds separate copies of data members. We can create as many objects of a class as we need. 7. Classes do posses more characteristics, like we can create abstract classes, immutable classes, all this we will study later. Objects Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects are instances of class, which holds the data variables declared in class and the member functions work on these class objects. Each object has different data variables. Objects are initialised using special class functions called Constructors. We will study about constructors later. And whenever the object is out of its scope, another special class member function called Destructor is called, to release the memory reserved by the object. C++ doesn't have Automatic Garbage Collector like in JAVA, in C++ Destructor performs this task. class Abc { int x; void display(){} //empty function }; in main()

Visit : www.EasyEngineeering.net

41 Visit : www.EasyEngineeering.net

{ Abc obj; // Object of class Abc created }

Member Functions in Classes Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class. If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution :: operator along with class name alng with function name. Example : class Cube { public: int side; int getVolume(); };

// Declaring function getVolume with no argument and return type int.

If we define the function inside class then we don't not need to declare it first, we can directly define the function. class Cube { public: int side; int getVolume() { return side*side*side; } };

//returns volume of cube

But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside. class Cube { public: int side;

Visit : www.EasyEngineeering.net

42 Visit : www.EasyEngineeering.net

int getVolume(); } int Cube :: getVolume() { return side*side*side; }

// defined outside class definition

The maine function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot . operator. int main() { Cube C1; C1.side=4; // setting side value cout<< "Volume of cube C1 ="<< C1.getVolume(); } Similarly we can define the getter and setter functions to access private data members, inside or outside the class definition. Types of Member Functions We already know what member functions are and what they do. Now lets study some special member functins present in the class. Following are different types of Member functions, 1. 2. 3. 4. 5.

Simple functions Static functions Const functions Inline functions Friend functions

Simple Member functions These are the basic member function, which dont have any special keyword like static etc as prefix. All the general member functions, which are of below given form, are termed as simple and basic member functions. return_type functionName(parameter_list) { function body; }

Visit : www.EasyEngineeering.net

43 Visit : www.EasyEngineeering.net

Static Member functions Static is something that holds its position. Static is a keyword which can be used with data members as well as the member functions. We will discuss this in details later. As of now we will discuss its usage with member functions only. A function is made static by using static keyword with function name. These functions work for the class as whole rather than for a particular object of a class. It can be called using the object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator. Example : class X { public: static void f(){}; }; int main() { X::f(); // calling member function directly with class name } These functions cannot access ordinary data members and member functions, but only static data members and static member functions. It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will study about "this" keyword later. Const Member functions We will study Const keyword in detail later, but as an introduction, Const keyword makes variables constant, that means once defined, there values can't be changed. When used with member function, such member functions can never modify the object or its related data members. //Basic Syntax of const Member Function void fun() const {}

Visit : www.EasyEngineeering.net

44 Visit : www.EasyEngineeering.net

Inline functions All the member functions defined inside the class definition are by default declared as Inline. We will study Inline Functions in details in the next topic.

Friend functions Friend functions are actually not class member function. Friend functions are made to give private access to non-class functions. You can declare a global function as friend, or a member function of other class as friend. Example : class WithFriend { int i; public: friend void fun(); // Global function as friend }; void fun() { WithFriend wf; wf.i=10; // Access to private data member cout << wf.i; } int main() { fun(); //Can be called directly }

Hence, friend functions can access private data members by creating object of the class. Similarly we can also make function of other class as friend, or we can also make an entire class as friend class.

class Other { void fun(); }; class WithFriend

Visit : www.EasyEngineeering.net

45 Visit : www.EasyEngineeering.net

{ private: int i; public: void getdata(); // Member function of class WithFriend friend void Other::fun(); // making function of class Other as friend here friend class Other; // making the complete class as friend };

When we make a class as friend, all its member functions automatically become friend functions. Friend Functions is a reason, why C++ is not called as a pure Object Oriented language. Because it violates the concept of Encapsulation.

Function Overloading If any class have multiple functions with same names but different parameters then they are said to be overloaded. Function overloading allows you to use the same name for different functions, to perform, either same or different functions in the same class. Function overloading is usually used to enhance the readability of the program. If you have to perform one single operation but with different number or types of arguments, then you can simply overload the function.

Ways to overload a function 1. By changing number of Arguments. 2. By having different types of argument.

Number of Arguments different In this type of function overloading we define two functions with same names but different number of parameters of the same type. For example, in the below mentioned program we have made two sum() functions to return sum of two and three integers. int sum (int x, int y) { cout << x+y; } int sum(int x, int y, int z)

Visit : www.EasyEngineeering.net

46 Visit : www.EasyEngineeering.net

{ cout << x+y+z; } Here sum() function is overloaded, to have two and three arguments. Which sum() function will be called, depends on the number of arguments. int main() { sum (10,20); // sum() with 2 parameter will be called sum(10,20,30); //sum() with 3 parameter will be called }

Different Datatype of Arguments In this type of overloading we define two or more functions with same name and same number of parameters, but the type of parameter is different. For example in this program, we have two sum() function, first one gets two integer arguments and second one gets two double arguments. int sum(int x,int y) { cout<< x+y; } double sum(double x,double y) { cout << x+y; } int main() { sum (10,20); sum(10.5,20.5); }

Default Arguments When we mention a default value for a parameter while declaring the function, it is said to be as default argument. In this case, even if we make a call to the function without passing any value for that parameter, the function will take the default value specified. sum(int x,int y=0) {

Visit : www.EasyEngineeering.net

47 Visit : www.EasyEngineeering.net

cout << x+y; } Here we have provided a default value for y, during function definition. int main() { sum(10); sum(10,0); sum(10,10); } Output : 10 10 20

First two function calls will produce the exact same value. for the third function call, y will take 10 as value and output will become 20. By setting default argument, we are also overloading the function. Default arguments also allow you to use the same function in different situations just like function overloading. Rules for using Default Arguments 1. Only the last argument must be given default value. You cannot have a default argument followed by non-default argument. 2. sum (int x,int y); 3. sum (int x,int y=0); 4. sum (int x=0,int y); // This is Incorrect 5. If you default an argument, then you will have to default all the subsequent arguments after that. 6. sum (int x,int y=0); 7. sum (int x,int y=0,int z); // This is incorrect 8. sum (int x,int y=10,int z=10); // Correct 9. You can give any value a default value to argument, compatible with its datatype.

Placeholder Arguments When arguments in a function are declared without any identifier they are called placeholder arguments. void sum (int,int);

Visit : www.EasyEngineeering.net

48 Visit : www.EasyEngineeering.net

Such arguments can also be used with default arguments. void sum (int, int=0);

Operator Overloading Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type. For example '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc.

Almost any operator can be overloaded in C++. However there are few operator which can not be overloaded. Operator that are not overloaded are follows     

scope operator - :: sizeof member selector - . member pointer selector - * ternary operator - ?:

Visit : www.EasyEngineeering.net

49 Visit : www.EasyEngineeering.net

Operator Overloading Syntax

Implementing Operator Overloading Operator overloading can be done by implementing a function which can be : 1. Member Function 2. Non-Member Function 3. Friend Function Operator overloading function can be a member function if the Left operand is an Object of that class, but if the Left operand is different, then Operator overloading function must be a nonmember function. Operator overloading function can be made friend function if it needs access to the private and protected members of class.

Restrictions on Operator Overloading Following are some restrictions to be kept in mind while implementing operator overloading. 1. Precedence and Associativity of an operator cannot be changed. 2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains binary etc. 3. No new operators can be created, only existing operators can be overloaded. 4. Cannot redefine the meaning of a procedure. You cannot change how integers are added. Operator Overloading Examples Almost all the operators can be overloaded in infinite different ways. Following are some examples to learn more about operator overloading. All the examples are closely connected.

Visit : www.EasyEngineeering.net

50 Visit : www.EasyEngineeering.net

Overloading Arithmetic Operator Arithmetic operator are most commonly used operator in C++. Almost all arithmetic operator can be overloaded to perform arithmetic operation on user-defined data type. In the below example we have overridden the + operator, to add to Time(hh:mm:ss) objects.

Example: overloading '+' Operator to add two time object #include< iostream.h> #include< conio.h> class time { int h,m,s; public: time() { h=0, m=0; s=0; } void getTime(); void show() { cout<< h<< ":"<< m<< ":"<< s; } time operator+(time); //overloading '+' operator }; time time::operator+(time t1) //operator function { time t; int a,b; a=s+t1.s; t.s=a%60; b=(a/60)+m+t1.m; t.m=b%60; t.h=(b/60)+h+t1.h; t.h=t.h%12; return t; } void time::getTime() { cout<<"\n Enter the hour(0-11) "; cin>>h; cout<<"\n Enter the minute(0-59) "; cin>>m;

Visit : www.EasyEngineeering.net

51 Visit : www.EasyEngineeering.net

cout<<"\n Enter the second(0-59) "; cin>>s; } void main() { clrscr(); time t1,t2,t3; cout<<"\n Enter the first time "; t1.getTime(); cout<<"\n Enter the second time "; t2.getTime(); t3=t1+t2; //adding of two time object using '+' operator cout<<"\n First time "; t1.show(); cout<<"\n Second time "; t2.show(); cout<<"\n Sum of times "; t3.show(); getch(); }

Overloading I/O operator    

Overloaded to perform input/output for user defined datatypes. Left Operand will be of types ostream& and istream& Function overloading this operator must be a Non-Member function because left operand is not an Object of the class. It must be a friend function to access private data members.

You have seen above that << operator is overloaded with ostream class object cout to print primitive type value output to the screen. Similarly you can overload << operator in your class to print user-defined type to screen. For example we will overload << in time class to display time object using cout. time t1(3,15,48); cout << t1; 1.4 REFERENCE VARIABLE INITIALIZATION A reference variable is an alias, that is , another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the refrence name must be used to refer to the variable. 1.4.1. DIFFERENCE BETWEEN REFERENCE AND POINTERS

Visit : www.EasyEngineeering.net

52 Visit : www.EasyEngineeering.net

References are often confused with pointers with pointers but three major differences between references and pointers are :  We cannot have NULL references. We must always be able to assume that a reference is connected to a legitimate piece of storage.  Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.  A reference must be initialized when it is created. Pointers can be initialized at any time. 1.4.2. CREATION OF REFERENCE VARIABLE  Variable name as a label attached to the variable’s location in memory.  We can then think of a reference as a second label attached to that memory location.  We can access the contents of the variable through either the original variable name or the reference. Example : int i=17; We can declare reference variables for i as follows.

int& r = i; Read the & in these declarations as reference. Thus , read the first declaration as “ r is an integer reference initialized to i” #include int main( ) { int i; double d; int& r=i; double& s=d; i=5; cout<<”value of i :”<
Visit : www.EasyEngineeering.net

53 Visit : www.EasyEngineeering.net



It provides more reliable and flexible.  Functions can be overloaded to make it perform different tasks depending on the arguments passed to it. Type of Functions C++ functions classified into two types. (1) Built in function (2) User defined functions Built – in Functions These functions are part of the compile package. These part of standard library made available by the compiler. Example : exit(), sqrt(), pow(), strlen(),etc.,

User defined functions  The user defined functions are created by the programmer.  These functions are created as per requirements of our program. Function Definition  A function must be defined before it is used anywhere in the program.  The general form of function definition is : type function name(parameter list) { body of the function } where the type specifies the type of value that the return statement of the function.  

If no type sis specified, the compiler assumes that the function returns an integer value. The parameter list is a list of variables separated by comma, referred as function arguments.  A function definition must have a return statement. FUNCTION PROTOTYPE  function prototype is not required for every function definition in the program. If function-call encountered before function definition, then function prototype is required.  In C++ all function must be declared before they are used. This is normally accomplished using function prototype.  The function prototype has the following general form: return-type function-name(argument-declaration-list);  The argument-declaration-list is either empty, or a single declaration, or a comma separated list of declarations. If the function has not parameters, the keyword void may be used. Example:

Visit : www.EasyEngineeering.net

54 Visit : www.EasyEngineeering.net

//Add three ints -illustrating function prototypes. #include

int add3(int, int, int); double average(int); int main() { int score_1, score_2, score_3, sum; cout << "\nEnter 3 scores: "; cin >> score_1 >> score_2 >> score_3; sum = add3(score_1, score_2, score_3); cout << "\nTheir sum is " << sum; cout << "\nTheir average is " << average(sum); } int add3(int a, int b, int c) { return (a + b + c); } double average(int s) { return (s / 3.0); }  C++ uses ellipsis symbol(…) to indicate that an argument list that is unspecified. For example, the function printf( ) prototype is given below: int printf( const char* cntrl_str,…);  Such a function can be invoked on an arbitrary list of actual parameters Need For Prototypes  Function prototyping enables a compiler to carefully compare each use of the function with the prototype of determine whether the function is invoked properly. Accesssing a Function 

A function is called by providing the function name, followed by the parameters enclosed in braces.  The general form for accessing a function is function name(argument list) Example : area(x,y); Default Arguments  C++ allow to call a function without specifying all the arguments. In such cases, function assigns a default value to the parameter.  Default values are specified at the time of function declaration.

Visit : www.EasyEngineeering.net

55 Visit : www.EasyEngineeering.net

Constant Arguments  An argument to a function can be declared as const.  The qualifier const tells the compiler that the function should not modify the argument.  The constant arguments are useful when the functions are called by reference. Example : int sum(const int a,const int b); int length(const string &s);

Visit : www.EasyEngineeering.net

56 Visit : www.EasyEngineeering.net

Call by Value and Call by Reference in C++ On the basis of arguments there are two types of function are available in C++ language, they are;

 

With argument Without argument

If a function take any arguments, it must declare variables that accept the values as a arguments. These variables are called the formal parameters of the function. There are two ways to pass value or data to function in C++ language which is given below;  

call by value call by reference

Visit : www.EasyEngineeering.net

57 Visit : www.EasyEngineeering.net

Call by value In call by value, original value can not be changed or modified. In call by value, when you passed value to the function it is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only but it not change the value of variable inside the caller function such as main().

#include #include void swap(int a, int b) { int temp; temp=a; a=b; b=temp; } void main() { int a=100, b=200; clrscr(); swap(a, b); // passing value to function cout<<"Value of a"<
Visit : www.EasyEngineeering.net

58 Visit : www.EasyEngineeering.net

Output: Value of a: 200 Value of b: 100 Call by reference In call by reference, original value is changed or modified because we pass reference (address). Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, any value changed inside the function, is reflected inside as well as outside the function. Example Call by reference #include #include void swap(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; } void main() { int a=100, b=200; clrscr(); swap(&a, &b); // passing value to function cout<<"Value of a"<
Difference between call by value and call by reference. call by value

call by reference

Visit : www.EasyEngineeering.net

59 Visit : www.EasyEngineeering.net

This method copy address of arguments into function as a arguments. Changes made to the parameter affect the argument. Changes made to the parameter inside the 2 Because address is used to access the actual function have no effect on the argument. argument. Actual and formal arguments will be Actual and formal arguments will be created in 3 created in different memory location same memory location 1

This method copy original value into function as a arguments.

Visit : www.EasyEngineeering.net

60 Visit : www.EasyEngineeering.net

1.5. CONSTRUCTORS A member function with the same name as its class is called constructor and it is used to initialize the objects of that class type with a legal initial value. Features of Constructor  

The same name as the class itself. no return type.

Syntax classname() { .... } Characteristics  They should be declared in the public section.  They are involved automatically when the objects are created.  They do not have return types, not even void and therefore they cannot have return values.  They cannot be inherited.  They can have default arguments.  They cannot be virtual.  We cannot refer to their addresses.  An object with a constructor cannot be used as member of a union.  They make ‘implicit calls’ to the operators new and delete when memory allocation is required. Why use constructor ? The main use of constructor is placing user defined values in place of default values. How Constructor eliminate default values ? Constructor are mainly used for eliminate default values by user defined values, whenever we create an object of any class then its allocate memory for all the data members and initialize there default values. To eliminate these default values by user defined values we use constructor. Example of Constructor in C++ #include #include

Visit : www.EasyEngineeering.net

61 Visit : www.EasyEngineeering.net

class sum { int a,b,c; sum() { a=10; b=20; c=a+b; cout<<"Sum: "<
when program ends when a block containing temporary variables ends when a delete operator is called

Features of destructor  

The same name as the class but is preceded by a tilde (~) no arguments and return no values

Syntax ~classname() { ......

Visit : www.EasyEngineeering.net

62 Visit : www.EasyEngineeering.net

} Note: If you do not specify a destructor, the compiler generates a default destructor for you. Example of Destructor in C++ #include #include class sum { int a,b,c; sum() { a=10; b=20; c=a+b; cout<<"Sum: "<
Visit : www.EasyEngineeering.net

63 Visit : www.EasyEngineeering.net

Example class_name (const class_name&); { ...... } 1.5.2 COPY CONSTRUCTOR A Copy constructor is used to create a temporary object of a class object. This is called when a new class object is initialized using an existing same class object. We can pass all types of arguments to a constructor except the object itself.

Visit : www.EasyEngineeering.net

64 Visit : www.EasyEngineeering.net

It is possible to pass the reference of the identical object to the constructor. This type of constructor is known as copy constructor and it has an important use in C++. A copy constructor takes a reference to an object of the same class as an argument and produces such object. General Syntax of copy constructors in C++ programming is :Class_Name(Class_Name &pointer) { ----; ----; } Let us see a example of program demonstrates the use of copy constructor by showing the fibonacci series of numbers in our C++ programming :#include class Fib_Series { private: int n,n1,n2; public: Fib_Series() { n = 0; n1 = 1; n2 = n + n1; } Fib_Series(Fib_Series &ptr) { n = ptr.n; n1 = ptr.n1; n2 = ptr.n2; } void incremental_value() { n = n1; n1 = n2; n2 = n1+n; } void showdata() { cout << n2 << "\n";

Visit : www.EasyEngineeering.net

65 Visit : www.EasyEngineeering.net

} }; int main () { Fib_Series x; int limit; cout << "Give the number of fibonacci number needed :- "; cin >> limit; for (int j = 1; j <= limit; j++) { x.showdata(); x.incremental_value(); } return 0; }

1.5.3 CONSTRUCTOR OVERLOADING  Just like function, the constructor of a class may also be overloaded.(i.e.,) more than one constructor defined in the class. Constructors Overloading are used to increase the flexibility of a class by having more number of constructor for a single class. By have more than one way of initializing objects can be done using overloading constructors. #include class Overclass { public: int x; int y; Overclass() { x = y = 0; } Overclass(int a) { x = y = a; } Overclass(int a, int b) { x = a; y = b; } }; int main() { Overclass A; Overclass A1(4); Overclass A2(8, 12);

Visit : www.EasyEngineeering.net

66 Visit : www.EasyEngineeering.net

cout << "Overclass A's x,y value:: " << A.x << " , "<< A.y << "\n"; cout << "Overclass A1's x,y value:: "<< A1.x << " ,"<< A1.y << "\n"; cout << "Overclass A2's x,y value:; "<< A2.x << " , "<< A2.y << "\n"; return 0; } Result : Overclass A's x,y value:: 0 , 0 Overclass A1's x,y value:: 4 ,4 Overclass A2's x,y value:; 8 , 12 1.6 FRIEND FUNCTIONS Private members cannot accessed from outside the class i.e., a non member function cannot have an access to the private data of a class. A function can be made a friend function using keyword friend. Any friend function is preceded with friend keyword. The declaration of friend function should be made inside the body of class starting with keyword friend. Need for Friend Functions You do not access private or protected data member of any class, to access private and protected data member of any class you need a friend function. Syntax class class_name { ...... friend returntype function_name(arguments); } Friend class Similarly like, friend function a class can be made a friend of another class using keyword friend. Syntax class A { friend class B; // class B is a friend class ...... } class B {

Visit : www.EasyEngineeering.net

67 Visit : www.EasyEngineeering.net

...... } When a class is made a friend class, all the member functions of that class becomes friend function. If B is declared friend class of A then, all member functions of class B can access private and protected data of class A but, member functions of class A can not private and protected data of class B. Example Friend function In below example you can access private function of class employee by using friend function. Example #include #include class employee { private: friend void sal(); }; void sal() { int salary=4000; cout<<"Salary: "<
Visit : www.EasyEngineeering.net

68 Visit : www.EasyEngineeering.net



It can be declared either in the public or private part of a class without affecting its meaning.  It has the object as arguments. 1.7 DYNAMIC MEMORY ALLOCATION

Dynamic memory allocation means creating memory at runtime. C++ provides two special operators to perform memory ,management dynamically. (1) New operator for dynamic memory allocation. (2) Delete operator for dynamic memory deallocation For example, when we declare an array, we must provide size of array in our source code to allocate memory at compile time. But if we need to allocate memory at runtime me must use new operator followed by data type. If we need to allocate memory for more than one element, we must provide total number of elements required in square bracket[ ]. It will return the address of first byte of memory. Syntax of new operator ptr = new data-type; //allocte memory for one element ptr = new data-type [ size ]; //allocte memory for fixed number of element C++ delete operator Delete operator is used to deallocate the memory created by new operator at run-time. Once the memory is no longer needed it should by freed so that the memory becomes available again for other request of dynamic memory. Syntax of delete operator

delete ptr; //deallocte memory for one element delete[] ptr; //deallocte memory for array

Visit : www.EasyEngineeering.net

69 Visit : www.EasyEngineeering.net

Example of c++ new and delete operator

#include #include void main() { int size,i; int *ptr; cout<<"\n\tEnter size of Array : "; cin>>size; ptr = new int[size]; //Creating memory at run-time and return first byte of address to ptr.

for(i=0;i<5;i++) //Input array from user. { cout<<"\nEnter any number : "; cin>>ptr[i]; } for(i=0;i<5;i++) cout<
//Output array to console.

delete[] ptr; //deallocating all the memory created by new operator } Output : Enter size of Array : 5 Enter any number : 78 Enter any number : 45 Enter any number : 12 Enter any number : 89 Enter any number : 56 78, 45, 12, 89, 56, 1.7.1 MEMBER DEREFERENCING OPERATORS

Visit : www.EasyEngineeering.net

70 Visit : www.EasyEngineeering.net



C++ permits us to define a class containing various types of data and function as members.  C++ also permits us to access the class members through pointers.  C++ provides a set of three pointer to member operators.

Operator ::* * -> *

Function To declare a pointer to a member of a class. To access member using object name and a point to that member. To access a member using a pointer to the object and a pointer to that member.

Visit : www.EasyEngineeering.net

71 Visit : www.EasyEngineeering.net

1.8 STATIC DATA MEMBERS A data member of a class can be qualified as static. Characteristics  It is initialized to zero when the first object of its class is created. No other initialization is permitted.  Only one copy of that member is created for entire class and is shared by all the objects of that class.  It is visible only within the class, but its life time is entire program.  Static variables are normally used to maintain values common to the entire class. Sample Program class item { static int count; int number; public : void getdata(int a) { number=a; count ++; } void getcount(void) { count<<”count :”; count<
Visit : www.EasyEngineeering.net

72 Visit : www.EasyEngineeering.net

} Output : count=0 count=0 count=0 After reading data : count=3 count=3 count=3 Static data member count is initialized to zero when the objects are created. The count is incremented whenever the data is read into an object. Static Member Functions 

A member function that is declared static.

Properties  A satic function can have access to only static members declared in the same class.  A static member function can be called using the class name(instead of objects) classname :: function-name; Example : class something { private : static int s_nvalue; public : static int getvalue( ) { return s_nvalue; }; int something::s_nvalue=1; int main( ) { std::cout<
Visit : www.EasyEngineeering.net

73 Visit : www.EasyEngineeering.net

Access    

It means accessing the container elements. In the case of arrays, accessing is done with the array index. For stacks, access of elements is done using Last In First Out. For queues it is done using First In First Out.

Storage  

It includes storing of items of containers. Some containers are finite containers and some are infinite containers.

Traversal 

It includes how the item can be traversed.

IMPLEMENTATION Container can be implemented in the following ways.  Create a new empty container(constructor).  Report the number of objects it stores(size).  Delete all the objects in the container(clear).  Insert new objects into the container.  Remove objects from it.  Provide access to the stored objects. TYPES OF CONTAINER Containers can be divided into two groups  Value based containers  Reference based containers Value based containers  Store copies of objects.  If we access an object, the object returns a copy of it.  If an external object is changed after it has been inserted in the container it will not affect the content of the container. Reference based containers  Store pointers or reference of the object  If we access an object, the object returns a reference to it.  If an external object is changed after it has been inserted in the container, it affects the content of the container. Value based containers Value based container classified into single value and Associative value Single value containers

Visit : www.EasyEngineeering.net

74 Visit : www.EasyEngineeering.net

Each object is stored independently in the container and it is accessed directly or with an iterator. Associative containers Associative array, map or dictionary is a container composed of(key,value) pairs, such that each key appears at most once in the container. The key is used to find the value, the object, if it is stored in the container. Example : Array of container class #include class test { public : void insert(int); void show( ); int size( ); test( ) { count = 0; } private : int data[20]; int count; }; void test :: insert(int val) { data[count]=val; count++; } void test::show( ) { for(int i=0;i
Visit : www.EasyEngineeering.net

75 Visit : www.EasyEngineeering.net

} 1.10 PROXY CLASS The proxy pattern is used when you need to represent a complex object by a simpler one. If creating an object is expensive in time or computer resources, Proxy allows you to postpone this creation until you need the actual object. A Proxy usually has the same methods as the object it represents, and once the object is loaded, it passes on the method calls from the Proxy to the actual object. Merits  If an object such as a large image, takes a long time to load.  If the object is on a remote machine and loadint it over the network may be slow, especially during peak network load periods.  If the object has limited access rights, the proxy can validate the access permissions for that user.  Proxies can also be used to distinguish between requesting an instance of an object and the actual need to access it. Example : #include #include

// The 'Subject interface class IMath { public: virtual double Add(double x, double y) = 0; virtual double Sub(double x, double y) = 0; virtual double Mul(double x, double y) = 0; virtual double Div(double x, double y) = 0; }; // The 'RealSubject' class class Math : public IMath { public: double Add(double x, double y) { return x + y; } double Sub(double x, double y) { return x - y; } double Mul(double x, double y)

Visit : www.EasyEngineeering.net

76 Visit : www.EasyEngineeering.net

{ return x * y; } double Div(double x, double y) { return x / y; } }; // The 'Proxy Object' class class MathProxy : public IMath { public: MathProxy() { math_ = NULL; } virtual ~MathProxy() { if(math_) delete math_; } double Add(double x, double y) { return getMathInstance()->Add(x, y); } double Sub(double x, double y) { return getMathInstance()->Sub(x, y); } double Mul(double x, double y) { return getMathInstance()->Mul(x, y); } double Div(double x, double y) { return getMathInstance()->Div(x, y); } private: Math* math_; Math* getMathInstance(void) { if(!math_) math_ = new Math(); return math_; }

Visit : www.EasyEngineeering.net

77 Visit : www.EasyEngineeering.net

}; //The Main method int main() { // Create math proxy MathProxy proxy; //Do the math cout<<"4 + 2 = "<
Visit : www.EasyEngineeering.net

79 Visit : www.EasyEngineeering.net

Integer number: 5 Float number: 5.5 Integer number: 5 and float number: 5.5

Visit : www.EasyEngineeering.net

80 Visit : www.EasyEngineeering.net

Another Example: C++ program to find the area of various geometrical shapes by function overloading. #include #include #include #define pie 3.14 class shape { public: float area(float a) { return (pie*a*a); } float area(float a, float b) { return (a*b); } float area(float a, float b, float c) { float s, temp; s = (a+b+c)/2; temp = s*(s-a)*(s-b)*(s-c); temp = pow(temp,0.5); return temp; } }; int main() { float radius,length,breadth,side[3]; shape circle, rectangle, triangle; cout<<"Enter radius of circle: "; cin>>radius; cout<<"Area of circle="<>length>>breadth; cout<<"Area of rectangle=" << rectangle.area(length, breadth) << " sq. unit" << endl << endl;

Visit : www.EasyEngineeering.net

81 Visit : www.EasyEngineeering.net

cout<<"Enter three sides of a triangle: "; cin>>side[0]>>side[1]>>side[2]; cout<<"Area of rectangle="<
1.12 OPERATOR OVERLOADING Operator overloading provides a flexible option for the creation of new definitions for most of the C++ operators. C++ has the ability fo provide the operators with a special meaning for a data type.The mechanism of giving special meaning to an operator is known as operator overloading. C++ overload the all operators except the following :     

Member access operator (.) Pointer to member access operator (.*) Scope resolution operator (::) Size operator (sizeof) Ternary operator (? :)

Rules for operator overloading 1. 2. 3. 4.

Only existing member can be overloaded. New operators cannot be created. The overloaded operator must have at least one operand of user-defined type. Overloaded operators follow the syntax rules of original operators. This means we can't change the basic meaning of an operator. 5. Some operators can't be overloaded. They are: member access operator (.), pointer to member access operator (.*), scope resolution operator (::), size operator (sizeof), ternary operator (? :).

Visit : www.EasyEngineeering.net

82 Visit : www.EasyEngineeering.net

6. We can't use friend function to overload some operators. They are: assignment operator (=), function call operator (( )), subscripting operator ( [ ] ), class member access operator (->). 7. If the operator function is a friend function then it will have one argument for unary operator and two argument for binary operator. If the operator function is a non static member function then it will have no arguments for unary operators and one argument for binary operators. 8. When binary operators are overloaded through member function, the left hand operand must be an object of the relevant class. 9. Binary arithmetic operators such as +, -, *, / must explicitly return a value. Example : C++ program to overload unary minus (-) operator. #include #include class example { int a,b; public: void input() { cout<<"Enter a and b: "; cin>>a>>b; } void operator -() //operator function as a member function { a=-a; b=-b; } void display() { cout<<"a="<
Visit : www.EasyEngineeering.net

83 Visit : www.EasyEngineeering.net

return 0; } 1.13 OVERLOADING BINARY OPERATORS 

The binary overloaded operator function takes the first object as an implicit operand and the second operand must be passed explicitly.  The data members of the first object are accessed without using the dot oerator whereas the second argument members can be accessed using the dot operator. If the argument is an object, otherwise it can be accessed directly.  The syntax for overloading a binary operator is return type operator operator symbol (argument) { //body of operator function } Sample Program -Overloading Binary Operators #include #include class complex { int a,b; public: void getvalue() { cout<<"Enter the value of Complex Numbers a,b:"; cin>>a>>b; } complex operator+(complex ob) { complex t; t.a=a+ob.a; t.b=b+ob.b; return(t); } complex operator-(complex ob) { complex t; t.a=a-ob.a; t.b=b-ob.b; return(t); }

Visit : www.EasyEngineeering.net

84 Visit : www.EasyEngineeering.net

void display() { cout<
Visit : www.EasyEngineeering.net

85 Visit : www.EasyEngineeering.net

 

Strings can be defined as class objects which can be manipulated like the built in types. C++ can be used to manipulate the strings very similar to the decimal numbers.

Visit : www.EasyEngineeering.net

86 Visit : www.EasyEngineeering.net

FAQ - A 1. Which is default access specifier for class members? private is the default access specifier for class 2. What are the features of OOP?  Data abstraction/Type-Extensibility – Having user-defined types (ADTs).  Encapsulation – putting data and code that act on data together into single unit.  Inheritance – reusability of existing code from one class to other classes.  Polymorphism (overloading & overriding) - Allowing runtime interpretation of function call / allowing runtime binding.  Data hiding/data security - Hiding implementation details, and provide security through different accessibility features such as:public, private and protected.  Simulating activity in the real world. 3. Name any three OOP language. Some of oop language are :Java, Smalltalk, Visual Basic.NET, Lisp, Python, Ruby. 4. What is function prototype? Function prototype types are necessary, whenever function call occurs before function definition. Function prototype also referred as function signature. Its general syntax given below: return-type function-name([data-type1, data-type2, …]); 5. Write the advantage and disadvantage of inline functions. Advantages:  It does not require function calling overhead.  It also save overhead of variables push/pop on the stack, while function calling.  It also save overhead of return call from a function.  It increases locality of reference by utilizing instruction cache.  Too many inline function in your program result in a larger code size that bringing down your program performance.  After in-lining function if variables number which are going to use register increases than they may create overhead on register variable resource utilization.  It may cause compilation overhead as if somebody changes code inside inline function than all calling location will also be compiled. 6. What is meant by addressing and deferencing? C++ uses two operators for addressing and deferencing variables. int v = 10; int *p = &v; cout << *p Addressing Operator – If v is a variable, then &v is the address or location in memory of its stored value. The & is an unary address operator Deferencing Or Indirection Operator – if p is a pointer, then *p is the value of the variable that points to. In certain sense * is the inverse operator to &. 7.Write the syntax of initializing pointer variables? int x = 10; int *p1; //declaration of pointer

Visit : www.EasyEngineeering.net

87 Visit : www.EasyEngineeering.net

double *p2; //declaration of pointer p 1 = &x; // static initialization of pointer p =new //dynamic initialization of 2 double(12.12); pointer 8. What is the use of void data type? void data type used for the following reason:  It is used as return type in the function definition, to indicate that the function does not return anything to the calling program Example: void add(int a, int b) { cout << “sum=” << (a + b) << endl; }

It is also used to create generic pointer, so that you can store address of variable of any data type. void *p; int a = 10; p = &a; double d = 20; p = &d; 9. How do you create reference variables? Reference variables are used to give alias name for existing variable. This allows a simpler form of call by reference parameters. Here are some examples: int n; int& n_ref = n; //n_ref is an alternate name for n double d[10]; double& last_d = a[9]; //last_d is alial for a[9] 10. What is the use of assert macro? The standard library assert.h provides a macro assert, its function signature were: void assert(bool expression); assert( ) is used to test program correctness (post-condition) and input validation (precondition). Consider allocation to our safe array type vect: vect :: vect(int n) : size(n) { assert(n > 0); p = new int[size]; assert(p != 0); } 11. Give the syntax of creating generic pointer? typedef void* iterator; iterator p; // p is generic pointer (or)

Visit : www.EasyEngineeering.net

88 Visit : www.EasyEngineeering.net

void *p; int *ip = new int(10); p = ip;

// p is generic pointer

double *dp = new double(10); p = dp; 12. What is encapsulation? Putting data and code that act on data together into single unit is referred as encapsulation. Encapsulation provides:  hidden implementation  public interface 13.What will be the target conversion type if an expression contains one int, one float and one double data item? int and float data in the expression are promoted to double and the final result of the expression is double because, during evaluation of expression, if operands are of different types, the ‘lower’ types are automatically converted to the ‘higher’ type before the operation proceeds. The result is of higher type. 14.Write some situations where inline expansion may not work. In the following situation inline function may not work:  If the function contain more than few line of code.  If the function contains iterative statements such as for loop, while loop, dowhile loop. 15.Compare and contrast structure and union. Structure Union But, only one member variable All individual member variable of of structure can be used at a time. union can be used at a time. Memory allocated independently Memory allocated for union for variable is shared by all its individual every individual members of the memory. structure variable. Size of the structure variable is equal Size of the union variable is equal to to size of the largest member of sum of the size of all individual the members of the structure. union. 16. Compare and contrast structure and class. Structure Class By default all members of By default all members of classes structure are are treated as public member. treated as private member. Members Members

Visit : www.EasyEngineeering.net

89 Visit : www.EasyEngineeering.net

with protected and private with protected and public access access specification has to be specification has to be explicitly explicitly mentioned in the structure declaration mentioned in the class declaration 17. What is the use of mutable keyword? Mutable member variables of the class are always modifiable, even from const member function.

PART – B 1. Explain the features of OOP. 2. Explain types of operators used in c++ with suitable example. 3. Explain different types of function c++ supports with its features. 4. Explain the following parameter passing techniques with suitable example. (a) Passed by value (b) Passed by reference 5. Explain the following: (a) Write a C++ program to explain how to overload a function with three different ways. (b) What is default argument function? Explain with suitable example. 6. Explain in detail about various storage class specifiers with suitable examples. 7. How single and multidimensional arrays are declared, initialized, used in c++? 8. What are the various way of passing arrays to function in C++? Explain with suitable example. 9. Explain the following: (a) Type conversion in expression (b) Reference variables (c) Pointer variables 10. What is assertion? Explain with suitable example. PART -C 1.Explain C++ program structure with an example. 2.Explain different types of constant C++ supports with suitable example

Visit : www.EasyEngineeering.net

1 Visit : www.EasyEngineeering.net

UNIT II : INHERITANCE & POLYMORPHISM Base Classes and Derived Classes – Protected Members – Casting Class pointers and Member Functions – Overriding – Public, Protected and Private Inheritance – Constructors and Destructors in derived Classes – Implicit Derived – Class Object To Base – Class Object Conversion – Composition Vs. Inheritance – Virtual functions – This Pointer – Abstract Base Classes and Concrete Classes – Virtual Destructors – Dynamic Binding

2.1 INHERITANCE – OVERVIEW Inheritance is the capability of one class to acquire properties and characteristics from another class. The class whose properties are inherited by other class is called the Parent or Base or Super class. And, the class which inherits properties of other class is called Child or Derived or Sub class. Inheritance makes the code reusable. When we inherit an existing class, all its methods and fields become available in the new class, hence code is reused. Purpose of Inheritance 1. Code Reusability 2. Method Overriding (Hence, Runtime Polymorphism.) 3. Use of Virtual Keyword

Basic Syntax of Inheritance class Subclass_name : access_mode Superclass_name While defining a subclass like this, the super class must be already defined or atleast declared before the subclass declaration. Access Mode is used to specify, the mode in which the properties of superclass will be inherited into subclass, public, privtate or protected.

Visit : www.EasyEngineeering.net

2 Visit : www.EasyEngineeering.net

Example of Inheritance

class Animal { public: int legs = 4; }; class Dog : public Animal { public: int tail = 1; }; int main() { Dog d; cout << d.legs; cout << d.tail; } Output : 41

Inheritance Visibility Mode Depending on Access modifier used while inheritance, the availability of class members of Super class in the sub class changes. It can either be private, protected or public.

Visit : www.EasyEngineeering.net

3 Visit : www.EasyEngineeering.net

1) Public Inheritance This is the most used inheritance mode. In this the protected member of super class becomes protected members of sub class and public becomes public. class Subclass : public Superclass

2) Private Inheritance In private mode, the protected and public members of super class become private members of derived class. class Subclass : Superclass // By default its private inheritance

3) Protected Inheritance In protected mode, the public and protected members of Super class becomes protected members of Sub class. class subclass : protected Superclass

Table showing all the Visibility Modes Derived Class Derived Class Derived Class Base class Public Mode Private Mode Protected Mode Private

Not Inherited Not Inherited Not Inherited

Protected Protected

Private

Protected

Public

Private

Protected

Public

2.2 Types of Inheritance In C++, we have 5 different types of Inheritance. Namely, 1. 2. 3. 4. 5.

Single Inheritance Multiple Inheritance Hierarchical Inheritance Multilevel Inheritance Hybrid Inheritance (also known as Virtual Inheritance)

Visit : www.EasyEngineeering.net

4 Visit : www.EasyEngineeering.net

Single Inheritance In this type of inheritance one derived class inherits from only one base class. It is the most simplest form of Inheritance.

Multiple Inheritance In this type of inheritance a single derived class may inherit from two or more than two base classes.

Hierarchical Inheritance In this type of inheritance, multiple derived classes inherits from a single base class.

Visit : www.EasyEngineeering.net

5 Visit : www.EasyEngineeering.net

Multilevel Inheritance In this type of inheritance the derived class inherits from a class, which in turn inherits from some other class. The Super class for one, is sub class for the other.

Hybrid (Virtual) Inheritance Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

Visit : www.EasyEngineeering.net

6 Visit : www.EasyEngineeering.net

2.3 Order of Constructor Call Base class constructors are always called in the derived class constructors. Whenever you create derived class object, first the base class default constructor is executed and then the derived class's constructor finishes execution.

Points to Remember 1. Whether derived class's default constructor is called or parameterised is called, base class's default constructor is always called inside them. 2. To call base class's parameterised constructor inside derived class's parameterised constructo, we must mention it explicitly while declaring derived class's parameterized constructor.

2.3.1 INHERITANCE    

It is the Mechanism of creating a new class from already defined class. The new class contains all attributes of the old class in addition to some of its own attributes. Additionally, it can also override some of the features of the old class. Inheritance is the process by which one object can acquire the properties of another object. In other words, it provides ability to define new class that can reuse code present in the existing classes, instead of rewriting the same code again. This is a powerful code reuse mechanism.

Visit : www.EasyEngineeering.net

7 Visit : www.EasyEngineeering.net



   



A derived class inherits the description of the base class; it can then reuse the base class members, and can add its own members variables and member function, modify existing member functions, and modifying access privileges of base class member variables. This reduce programmer burden because inheritance avoids the redevelopment and testing of the existing code. If any modification done in super class will automatically reflect in all derived classes. Base class is also referred to as parent class or super class. Derived class is also referred to as child class, sub class. It support concept of hierarchical classification. Grand Parent, Parent, Child classification possible. C++ supports virtual member functions. These are functions declared in the base class and redefined in a derived class, which supports dynamic polymorphism at runtime. This is a form of polymorphism called pure polymorphism. The following code fragment show feature of inheritance in C++: class A{…}; // base class class B: public A{…}; // derived class

2.3.2 A DERIVED CLASS AND ACCESS SPECIFIERS (VISIBILITY MODE) A class can be derived from an existing class using the form: class class-name: (public | protected | private)opt basename { member declarations }; 

One aspect of the derived class is the visibility of its inherited members. The keywords public, protected, and private are used to specify how the base class members are to be accessible to the derived class. If no access-specifier (public | protected | private) specified explicitly, private is assumed.



When is public is used, all public member of base class become public member of derived class, and all protected members of base class become protected member of the derived class, and all private member of base class will not be accessible from derived class.



When is protected is used, all public, protected members of base class become protected member of derived class, all private-member of base class remain inaccessible from derived class.

Visit : www.EasyEngineeering.net

8 Visit : www.EasyEngineeering.net



When is private is used, all public, protected members of base class become private member of derived class, all private-member of base class remain inaccessible from derived class.



The following is example for, base were inherited as private, then all public, protected members of base would become private members of derived class. The following table summarizes the visibility of inherited members: Derived class visibility Base class visibility

Protected

Private

derivation

derivation

Public derivation

Private

Not inherited

Not inherited

Not inherited

Protected

Protected

Protected

Private

Public

Public

Protected

Private

class Base { int i; protected: int j; public: int k; void set(int a, int b, int c) { i = a; j = b; k = c; } int getI( return i;}

Visit : www.EasyEngineeering.net

9 Visit : www.EasyEngineeering.net

int getJ( return j;} void show(){cout<<"\n\t I : "<< i <<"\t J : "<>code; } void staff::display()

Visit : www.EasyEngineeering.net

12 Visit : www.EasyEngineeering.net

{ cout<<"Name:"<>speed; } void typist::display() { cout<<"Speed:"<
Output : Enter data Name:Roger Taylor Code:13 Speed:46 Display data Name:Roger Taylor Code:13 Speed:46

Another Example :

Visit : www.EasyEngineeering.net

13 Visit : www.EasyEngineeering.net

C++ Program to Inherit a Student class from Person Class printing the properties of the Student #include #include class person /*Parent class*/ { private: char fname[100],lname[100],gender[10]; protected: int age; public: void input_person(); void display_person(); }; class student: public person /*Child class*/ { private: char college_name[100]; char level[20]; public: void input_student(); void display_student(); }; void person::input_person() { cout<<"First Name: "; cin>>fname; cout<<"Last Name: "; cin>>lname; cout<<"Gender: "; cin>>gender; cout<<"Age: "; cin>>age; } void person::display_person() { cout<<"First Name : "<
Visit : www.EasyEngineeering.net

14 Visit : www.EasyEngineeering.net

void student::input_student() { person::input_person(); cout<<"College: "; fflush(stdin); gets(college_name); cout<<"Level: "; cin>>level; } void student::display_student() { person::display_person(); cout<<"College : "<
Visit : www.EasyEngineeering.net

15 Visit : www.EasyEngineeering.net

Multiple Inheritance : 

If the derived class has more than one base class, it is said to be multiple inheritance. class Parent1 { //parent1 code here }; class Parent2 { //parent2 code here }; class child:public Parent1, protected Parent2 { //…child code here };



There is possibility for an ambiguity error possible if both the parent have duplicate variable.

Features 

More than one parent per derived class.



Forms an inheritance Directed Acyclic Graph (DAG).



Multi level inheritance adds additional run-time overhead (also involving dynamic binding).

Inheritance is the process of inheriting properties of objects of one class by objects of another class. The class which inherits the properties of another class is called Derived or Child or Sub class and the class whose properties are inherited is called Base or Parent or Super class. When a class is derived from two or more base classes, such inheritance is called Multiple Inheritance. It allow us to combine the features of several existing classes into a single class.

Syntax of Multiple Inheritance class base_class1 { properties;

Visit : www.EasyEngineeering.net

16 Visit : www.EasyEngineeering.net

methods; }; class base_class2 { properties; methods; }; ... ... ... ... ... ... class base_classN { properties; methods; }; class derived_classname : visibility_mode base_class1, visibility_mode base_class2,... ,visibility_mode base_classN { properties; methods; };

Example : #include #include class student { protected: int rno,m1,m2;

Visit : www.EasyEngineeering.net

17 Visit : www.EasyEngineeering.net

public: void get() { cout<<"Enter the Roll no :"; cin>>rno; cout<<"Enter the two marks :"; cin>>m1>>m2; } }; class sports { protected: int sm; // sm = Sports mark public: void getsm() { cout<<"\nEnter the sports mark :"; cin>>sm; } }; class statement:public student,public sports { int tot,avg; public: void display() { tot=(m1+m2+sm); avg=tot/3; cout<<"\n\n\tRoll No : "<
: "<
Output: Enter the Roll no: 100

Visit : www.EasyEngineeering.net

18 Visit : www.EasyEngineeering.net

Enter two marks 90 80 Enter the Sports Mark: 90 Roll No: 100 Total : 260 Average: 86.66 Multilevel Inheritance :  The derived class inherits the base class, which in turn inherits another class as its base class then it is said to be multilevel inheritance. The inheritance depth can be of any level. Here classes are stored in the hierarchical classification  The Child class will inherits features from not only from parent, but also from grand parent. class GrandParent { //parent class code here }; class Parent:public GrandParent { //parent code here }; class Child:public Parent { //child code here };

When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent classes, such inheritance is called Multilevel Inheritance. Syntax of Multilevel Inheritance class base_classname { properties;

Visit : www.EasyEngineeering.net

19 Visit : www.EasyEngineeering.net

methods; }; class intermediate_classname:visibility_mode base_classname { properties; methods; }; class child_classname:visibility_mode intermediate_classname { properties; methods; };

C++ program to create a programmer derived from employee which is himself derived from person using Multilevel Inheritance #include #include using namespace std; class person { char name[100],gender[10]; int age; public: void getdata() { cout<<"Name: "; fflush(stdin); /*clears input stream*/ gets(name); cout<<"Age: "; cin>>age; cout<<"Gender: "; cin>>gender; } void display() { cout<<"Name: "<
Visit : www.EasyEngineeering.net

20 Visit : www.EasyEngineeering.net

class employee: public person { char company[100]; float salary; public: void getdata() { person::getdata(); cout<<"Name of Company: "; fflush(stdin); gets(company); cout<<"Salary: Rs."; cin>>salary; } void display() { person::display(); cout<<"Name of Company: "<>number; } void display() { employee::display(); cout<<"Number of programming language known: "<
Visit : www.EasyEngineeering.net

21 Visit : www.EasyEngineeering.net

getch(); return 0; } Output : Enter data Name: Karl Lens Age: 31 Gender: Male Name of Company: Dynamic Info Salary: $21000 Number of programming language known: 4 Displaying data Name: Karl Lens Age: 31 Gender: Male Name of Company: Dynamic Info Salary: $21000 Number of programming language known: 4 This program is an example of multilevel inheritance. Hybrid Inheritance : 

It is the combination of multilevel and multiple inheritance. Ambiguity error will be possible in this type of inheritance.



To avoid ambiguity error, you have to make base class as virtual base class. The duplication of inherited members due to multiple path between derived and base class can be avoided by making the common base class as virtual base class.



In the following example Grandparent is the common base class. class Grandparent { //parent1 code here }; class Parent1:public virtual Grandparent { //parent1 code here }; class Parent2: virtual public Grandparent

Visit : www.EasyEngineeering.net

22 Visit : www.EasyEngineeering.net

{ //parent2 code here }; class child:public Parent1, protected Parent2 { //…child code here }; Example: #include #include class GParent { protected: int z; public: void showz() {cout<< "z ==>" << z << "\n";} }; class Parent1: virtual public GParent { protected: int x; public: void showx() { cout << "x ==>" << x << "\n"; } }; class Parent2: public virtual GParent { protected: int y; public: void showy() { cout << "y ==>" << y << "\n"; } }; // Inherit multiple base classes. class ChildClass : public Parent1, public Parent2

Visit : www.EasyEngineeering.net

23 Visit : www.EasyEngineeering.net

{ public: /* x and y are accessible because they are protected in Parent1 and Parent2, not private. y also accessible but there are two copies, to avoid multiple copies, make commonbase class as virtual */ void set(int i, int j, int k) { z = i; x = j; y = k; } }; int main() { ChildClass ob; ob.set(10, 20, 30); // provided by ChildClass ob.showx();

// from Parent1

ob.showy();

// from Parent2

ob.showz();

// from GParent

getch(); return 0; }

Output: x==>20 y==>30 z==>10

Hierarchial Inheritance : If more than one derived classes are inherited from the same base class, then it is said to be hierarchical inheritance. class Parent {

Visit : www.EasyEngineeering.net

24 Visit : www.EasyEngineeering.net

//parent class code here }; class Child-one:public Parent { //child-one code here }; class Child-two:public Parent { //child-two code here }; class Child-three:public Parent { //child-three code-here }; Example: #include using namespace std; class Shape { protected: double a; const static float PI = 3.1415f; public: virtual double area() = 0; virtual double perimeter() = 0; }; class Square: public Shape { public: Square(double a) { this –> a = a; }

Visit : www.EasyEngineeering.net

25 Visit : www.EasyEngineeering.net

double area( ) { return a*a; } double perimeter( ) { return 4*a; } }; class Circle:public Shape { public: Circle(double r) { a = r; } double area( ) { return PI*a*a; } double perimeter( ) { return 2*PI*a; } }; int main( ) { Shape *sp; sp = new Square(10); cout<< "sp.area = "<< sp –> area()<< endl; cout<< "sp.perimeter = "<< sp –> perimeter()<< endl<< endl; sp = new Circle(10); cout<< "sp.area = "<< sp –> area()<< endl; cout<< "sp.perimeter = "<< sp –> perimeter()<< endl<< endl; } Output:

Visit : www.EasyEngineeering.net

26 Visit : www.EasyEngineeering.net

sp.area = 100 sp.perimeter = 40 sp.area = 314.15 sp.perimeter = 62.83

Difference between Composition and Inheritance In real-life, complex objects are often built from smaller, simpler objects. For example, a car is built using a metal frame, an engine, some tires, a transmission, a steering wheel, and a large number of other parts. A personal computer is built from a CPU, a motherboard, some memory, etc.. Even you are built from smaller parts: you have a head, a body, some legs, arms, and so on. This process of building complex objects from simpler ones is called composition Inheritance means deriving features of base class to sub-class.. whereas composition means deriving a complex object from a simpler object.

2.4. VIRTUAL FUNCTIONS AND POLYMORPHISM Polymorphism means the ability of an organism to assume a variety forms. It is implemented using the over loaded functions and operators. 2.4.1. Types of Polymorphism Polymorphism is classified into two types (1)Compile time polymorphism (2)Run time polymorphism (1)Compile Time Polymorphism : The over loaded member functions are selected for invoking by matching arguments, both type and number. This information is known to the compiler at the compile time and therefore compile is able to select the appropriate function for a particular at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism.

Visit : www.EasyEngineeering.net

27 Visit : www.EasyEngineeering.net

Types of Polymorphism (2) Run Time Polymorphism : Appropriate member function could be selected during the run time.This is called as late binding or run time polymorphism.Virtual function is used to achieve run time polymorphism. Virtual Function When we use the same function name in both the base and derived classes, the function in base class declared as virtual using the keyword ‘virtual’ preceding its normal declaration. When a function is made virtual, C++ determines which function to use at run time based on this type of object pointed to by the pointer rather than the type of the pointer.

Rules for Virtual Functions      

The virtual function must be members of some class They cannot be static members They are accessed by using object pointers A virtual function can be friend of another class A virtual function in a base class must be defined, even though it may not be used The prototype of the base class version of a virtual function and all the derived class version must be identical  If two functions with the same name have different prototypes , C++ consider them as overloaded function and the virtual function mechanism is ignored  We cannot have virtual constructors, but we can have virtual destructors

Visit : www.EasyEngineeering.net

28 Visit : www.EasyEngineeering.net

Virtual functions allow programmers to declare function in a base class, which can be defined in each derived class.A pointer to ab object of a base class can also point to the objects of its derived class. Sample Program : #include #include class A { public: virtual void show() { cout<<"Hello base class"; } }; class B : public A { public: void show() { cout<<"Hello derive class"; } }; void main() { clrsct(); A aobj; B bobj; A *bptr; bptr=&aobj; bptr->show(); // call base class function bptr=&bobj; bptr->show(); // call derive class function getch(); } Output : Hello base class Hello derive class Definition of Virtual Functions

Visit : www.EasyEngineeering.net

29 Visit : www.EasyEngineeering.net

A virtual function is a member function of class that is declared within a base class and redefined in derived class. The syntax for defining a virtual function is given below . class classname { public : virtual return type function name(arguments) { ….} …. }; 2.5. PURE VIRTUAL FUNCTIONS Virtual functions defined inside the base class normally server as a framework for future design of class hierarchy. These functions can be over ridden by the methods in the derived classes. In most of the cases, these virtual functions are defined with a null body, it has no definition. Such functions in the base class are similar to do nothing or dummy functions. These functions are 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 a base class having a pure virtual function have to define such a function or redeclare it as a pure virtual function. It must be noted that, a class containing pure virtual functions cannot be used to define any objects of its own and hence such classes are called pure abstract classes a simply abstract classes. A pure virtual function has no implementation in the base class hence, a class with pure virtual function cannot be instantiated. A pure virtual member function can be invoked by its derived class. Example of pure virtual function

#include #include

Visit : www.EasyEngineeering.net

30 Visit : www.EasyEngineeering.net

class BaseClass {

//Abstract class

public: virtual void Display1()=0;//Pure virtual function or abstract function virtual void Display2()=0;//Pure virtual function or abstract function void Display3() { cout<<"\n\tThis is Display3() method of Base Class"; } }; class DerivedClass : public BaseClass { public: void Display1() { cout<<"\n\tThis is Display1() method of Derived Class"; } void Display2() { cout<<"\n\tThis is Display2() method of Derived Class"; } }; void main() { DerivedClass D; D.Display1();// This will invoke Display1() method of Derived Class D.Display2();// This will invoke Display2() method of Derived Class D.Display3();// This will invoke Display3() method of Base Class }

Output :

Visit : www.EasyEngineeering.net

31 Visit : www.EasyEngineeering.net

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

2.6 POINTERS A pointer is a variable that holds a memory address usually, the location of another variable in memory. Features    

Pointers provide the memory location of a variable can be directly accessed. It can be manipulated in the way as required. Pointers support dynamic allocation routines. In can improve the efficiency of certain routines. What is pointer and how it works.

 A pointer is a variable that contains the address of a variable. Using pointer we can pass argument to the functions.  Computer memory is a long array and every array location has a distinct memory location.

Visit : www.EasyEngineeering.net

32 Visit : www.EasyEngineeering.net

The declaration of pointer variable takes the following form. Syntax : datatype *pointer_variable; Example : int *iptr ;

// creates an integer pointer iptr

char *cptr; // creates a character pointer cptr float *fptr; // creates a float pointer fptr Two special operator, * and & are used with pointers. The & is a unary operator that returns the memory address of its operand.

int i=25; int *iptr; iptr = &i // store the memory address of i into iptr 1050

1051

25

1050

i

iptr

iptr=&i &i returns 1050 and iptr returns 25

Working of ‘ &’ and ‘*’ operator

Void Pointers : Void pointers known as generic pointers which refer to variables of any type. Null Pointers :

Visit : www.EasyEngineeering.net

33 Visit : www.EasyEngineeering.net

The pointers which are not initialized in program are called Null pointers. 2.7. MANIPULATION OF POINTERS  We can manipulate a pointer with the indirection operator (i.e) ‘*’ which is also known as deference operator.  With this operator, we can directly access the data variable content. It takes the following general form *pointer_variable Sample Program #include void main() { int a=10,*ptr; ptr=&a; clrscr(); cout<<”The value of a is “<
Pointers are useful to allocate arrays dynamically (i.e) array size decided at run time. Pointers are useful to allocate arrays dynamically

Visit : www.EasyEngineeering.net

34 Visit : www.EasyEngineeering.net

i.e., array size decided at run time. Array  

Pointers It refer to block of memory space The memory address of arrays cannot be changed



It does not refer to any section of memory .  The content of the pointer variables, such as the memory addresses, that it refer to , can be changed

Visit : www.EasyEngineeering.net

35 Visit : www.EasyEngineeering.net

Example : int *nptr; nptr = number[0]; (or) nptr=number nptr points to the first element of the integer array.

Array of Pointers Pointers also, may be arranged like any other data type. To declare an array holding 5 int pointers, the declaration would be as follows : int *ip[5] // array of 5 int pointers

Memory allocated for 5 int pointers

Association between Arrays and Pointers

Sample Program #include

Visit : www.EasyEngineeering.net

36 Visit : www.EasyEngineeering.net

int main () { char *names[4] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali", }; for (int i = 0; i < 4; i++) { cout << "Value of names[" << i << "] = "; cout << names[i] << endl; } return 0; } When the above code is compiled and executed, it produces the following result: Value of names[0] = Zara Ali Value of names[1] = Hina Ali Value of names[2] = Nuha Ali Value of names[3] = Sara Ali Pointers and Strings    

Pointers are efficient to access two dimensional and multidimensional arrays in c++. C++ allows us to handle the special kinds of arrays(i.e) string with pointers. A string is one dimensional array of characters terminated by a null(‘\0’) Alternatively the same can be achieved using a character pointer.c char *cp=”pointer”;

Sample Program: #include void main() { int i,j,len,flag=1; char *a; cout<<"Enter a string:"; cin>>a; for(len=0;a[len]!='\0';++len); for(i=0,j=len-1;i
Visit : www.EasyEngineeering.net

37 Visit : www.EasyEngineeering.net

if(a[j]!=a[i]) flag=0; } if(flag==1) cout<<"\nThe string is Palindrome"; else cout<<"\nThe string is not Palindrome"; } POINTERS TO FUNCTIONS  We can use these function pointers to refer to function  Using function pointers, we can allow a C== program to select a function dynamically at run time  We can also pass a function as an argument to another function  The function is passed as a pointer. The function pointers cannot be deferenced.  C++ provides two types of function pointers. Function pointers that point to static member functions and function pointers that point to non static member functions.  We can declare a function pointer in C++. It takes the following form : data_type (*function_name()); Example : int(*num_function(int x)); Functions Returning Pointers  The function can returns an int , float, double or reference or any other data types, it can even return a pointer  The general form of prototype of a function returning a pointer would be type * function_name (Argument list); POINTERS TO OBJECTS C++ allows you to have pointers to objects The pointers pointing to objects are referred to as object pointers. It takes the following general form : class name * object pointer; Example : item *it_ptr;  Object pointers are useful in creating objects at run time  We can also use an object pointer to access the public members of an object

Visit : www.EasyEngineeering.net

38 Visit : www.EasyEngineeering.net

 We can refer to the member function of item in 2 ways. One by using dot operator and the object. Another by using arrow operator and the object pointer. Example : x.getdata(100,75.50); x.show(); are equivalent to ptr ->getdata(100,75.5); ptr->show( );  we can also create the objects using pointers and new operator as follows. item *ptr = new item;  we can also create an array of objects using pointers. item *ptr = new item[10]; // Array of 10 objects Array of pointers to Objects We can define an array of pointers to objects that can be used to access the individual objects.

2.8.1 THIS POINTER this pointer is used to differentiate class’s member-variable from formal parameter of member function, when both formal parameter and class-membervariable have the same name  this pointer is automatically created and passed by C++ runtime, whenever memberfunction (including constructor) of class is called. It always refer to the invoking object Example: class Demo { int a; public: Demo(int a) { this –> a = a; // assign value from formal parameter a to class variable a } };  Here you have two variable with same name a, one is parameter to constructor, another one is class-member-data. 

Visit : www.EasyEngineeering.net

39 Visit : www.EasyEngineeering.net

2.8.2 POINTERS TO DERIVED CLASSES 

A public derived class is a subtype of its base class. A variable of the derived class can in many ways be treated as if it were the base class type. For example the base class pointer variable cannot only point to object of base class, but also point to the object of derived classes possible.



If base class pointer variable pointing to object any of its derived class, through the pointer, you can access only members defined in the base class, derived class members remain inaccessible. Any additional members defined in the derived class cannot be accessible through base class pointer. To access all member of object of derived class through base class pointer, you have to explicitly type cast base class pointer in to appropriate derived class pointer.



But derived-class pointer cannot used to point to the base-class object.



The following example demonstrates this feature.

Visit : www.EasyEngineeering.net

40 Visit : www.EasyEngineeering.net

((Derived*)bptr) – >getD( ); // no error, because explicit type casting

#include #include class Base {

} int b; public: void setB(int a) { b = a; } void getB( ) { cout<< " \nbase::b ==> "<< b<< endl; }

}; class Derived:public Base { public: int d; void getD() { cout<< "\nderived::d ==>"<< d<< endl; } }; int main( ) { Base *bptr; Derived d; bptr = &d;

// here base pointer pointing derived class object

bptr –>setB(10);

// no error, it is defined in Base class

bptr –>getB( );

// no error, it is defined in Base class // error, because Base pointer does not aware of class members

//bptr –>d = 10;

derived

((Derived*)bptr) –> d = 10; // no error, because of explicit type casting //sptr –>getD( )

// error, because getD( ) not defined in Base

Visit : www.EasyEngineeering.net

41 Visit : www.EasyEngineeering.net

Output: base::b ==> 10 derived::d ==>10

Visit : www.EasyEngineeering.net

42 Visit : www.EasyEngineeering.net

2.8.3 ABSTRACT CLASS 

The classes without any objects are known as abstract classes. These classes are usually outcome of generalization process which finds out common elements of the classes of interest and stores them in a base class.



Whenever a designer has to model an abstract concept which cannot have objects, then abstract classes are handy. Consider the class shape. It can be inherited to rectangle, ellipse, which in turn can be inherited to parallelograms into squares and circles. Except shape, all other can have objects of them.

Feature of an abstract class 

If the class contains one or more pure-virtual-function, that class will be treated as abstract class.



Other than pure virtual function, the abstract class can also contain zero or more member-data and non-virtual function.  Abstract class cannot be instantiated, but abstract class can be Base-class for some other class. 

You can utilize member-data and non-virtual-function of abstract class only through its derived classes.



Abstract class must force its all derived-class to override all pure-virtual function defined in abstract class.



If pure-virtual-function not re-defined in any derived-class that also will be treated as abstract class.

Why abstract class required? 

Abstract classes are used force its derived classes to provides set of uniform interface to its client, so that if the client is familiar with interface of one derived class, they are familiar with interface of other derived class as well.



Functions and variables that are commonly shared by all its derived classes are defined in the abstract class, so that it cannot be refined again and again in all its derived classes.



Functions that behave differently in its derived classes are only declared in abstract class, and force its derived classes to implements it, to maintain standardization across its derived classes.

Visit : www.EasyEngineeering.net

43 Visit : www.EasyEngineeering.net



Abstract base class is used for interface inheritance, but not for implementation inheritance. The derived class will implements this interface concretely.

Visit : www.EasyEngineeering.net

44 Visit : www.EasyEngineeering.net

The following example demonstrate feature of abstract class.

#include using namespace std; class Shape { protected: double a; const static float PI = 3.1415f; public: virtual double area() = 0; virtual double perimeter() = 0; }; class Square: public Shape { public: Square(double a) { this–>a = a; } double area( ) { return a*a; } double perimeter( ) { return 4*a; } }; class Circle:public Shape { public: Circle(double r) { a = r; } double area( ) {

Visit : www.EasyEngineeering.net

45 Visit : www.EasyEngineeering.net

return PI*a*a; } double perimeter( ) { return 2*PI*a; } }; int main( ) { Shape *sp; sp = new Square(10); cout<< "sp.area = "<< sp–>area()<< endl; cout<< "sp.perimeter = "<< sp–>perimeter()<< endl<< endl; sp = new Circle(10); cout<< "sp.area = " << sp–>area()<< endl; cout<< "sp.perimeter = "<< sp–>perimeter()<< endl<< endl; } Output: sp.area = 100 sp.perimeter = 40 sp.area = 314.15 sp.perimeter = 62.83



In the above program class Shape forces Circle, Square, Rectangle, Triangle to have function definitions for area( ) and perimeter( ). This is an example for interface inheritance.

Visit : www.EasyEngineeering.net

46 Visit : www.EasyEngineeering.net

2.8.4 CONCRETE CLASS A concrete class is a class that can be used to create an object. An abstract class cannot be used to create an object. A class is said to be a concrete class if and only if it contains fully defined methods. Defined methods are also known has “concrete methods” or “Implemened methods”. We can instantiate an object for concrete class. C++ introduces concept of virtual function and pure virtual function. When a class has a pure virtual function it acts as an interface and objects cannot be created for such classes. Such class is called abstract class. Some classes implement these interfaces and so objects can be created. This are called Concrete class.

2.8.5 VIRTUAL DESTRUCTOR Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors of the Base class must be made virtual for proper destruction of the object when the program exits. Upcasting without Virtual Destructor Lets first see what happens when we do not have a virtual Base class destructor. class Base { public: ~Base() {cout << "Base Destructor\t"; } }; class Derived:public Base { public: ~Derived() { cout<< "Derived Destructor"; } }; int main() { Base* b = new Derived; delete b; }

//Upcasting

Visit : www.EasyEngineeering.net

47 Visit : www.EasyEngineeering.net

Output : Base Destructor In the above example, delete b will only call the Base class destructor, which is undesirable because, then the object of Derived class remains undestructed, because its destructor is never called. Upcasting with Virtual Destructor Now lets see. what happens when we have Virtual destructor in the base class. class Base { public: virtual ~Base() {cout << "Base Destructor\t"; } }; class Derived:public Base { public: ~Derived() { cout<< "Derived Destructor"; } }; int main() { Base* b = new Derived; delete b; }

//Upcasting

Output : Derived Destructor Base Destructor When we have Virtual destructor inside the base class, then first Derived class's destructor is called and then Base class's destructor is called, which is the desired behaviour. Pure Virtual Destructors  Pure Virtual Destructors are legal in C++. Also, pure virtual Destructors must be defined, which is against the pure virtual behaviour.  The only difference between Virtual and Pure Virtual Destructor is, that pure virtual destructor will make its Base class Abstract, hence you cannot create object of that class.

Visit : www.EasyEngineeering.net

48 Visit : www.EasyEngineeering.net

 There is no requirement of implementing pure virtual destructors in the derived classes. class Base { public: virtual ~Base() = 0; //Pure Virtual Destructor }; Base::~Base() { cout << "Base Destructor"; } //Definition of Pure Virtual Destructor class Derived:public Base { public: ~Derived() { cout<< "Derived Destructor"; } };

2.8.6 DYNAMIC BINDING When a program is compiled, the compiler converts each statement in C++ program into one or more lines of machine language. Each line of machine language is given its own unique sequential address. This is no different for functions. When a function is encountered; it is converted into machine language and given the next available address. Thus each function ends up with a unique machine language address. Binding  It refers to the process that is used to convert identifiers(such as variabke and function names) into machine language addresses.  Although binding is used for both variables and functions Connecting a method call to the method body is known as binding. There are two types of binding 1. Static binding (also known as early binding). 2. Dynamic binding (also known as late binding). Static Binding Most of the function calls the compiler encounters will be direct function calls. A direct function call is a statement that directly calls a function. Direct function

Visit : www.EasyEngineeering.net

49 Visit : www.EasyEngineeering.net

calls can be resolved using a process known as early binding. Early binding (static binding) means the compiler is able to directly associate the identifier name (such as a function or variable name) with a machine address. Remember that all functions have a unique machine address. So when the compiler encounters a function call, it replaces the function call with a machine language instruction that tells the CPU to jump to the address of the function. Example : #include int add(int x, int y) { return x + y; } int subtract(int x, int y) { return x - y; } int multiply(int x, int y) { return x * y; } int main() { int x; cout << "Enter a number: "; cin >> x; int y; cout << "Enter another number: "; cin >> y; int op; do { cout << "Enter an operation (0=add, 1=subtract, 2=multiply): "; cin >> op; } while (op < 0 || op > 2); int result = 0; switch (op) {

Visit : www.EasyEngineeering.net

50 Visit : www.EasyEngineeering.net

// call the target function directly using early binding case 0: result = add(x, y); break; case 1: result = subtract(x, y); break; case 2: result = multiply(x, y); break; } std::cout << "The answer is: " << result << std::endl; return 0; } Because add( ), subtract (), and multiply( ) are all direct function calls, the compiler will use early binding to resolve the add( ), subtract( ) and multiply( ) function calls. The compiler will replace the add( ) function call with an instruction that tells the CPU to jump to the address of the add( ) function. The same holds true for subtract( ) and multiply( ). Dynamic binding In OOPs Dynamic Binding refers to linking a procedure call to the code that will be executed only at run time. The code associated with the procedure in not known until the program is executed, which is also known as late binding. Example : #include int add(int x, int y) { return x + y; } int subtract(int x, int y) { return x - y; } int multiply(int x, int y) { return x * y; } int main() { int x; cout << "Enter a number: "; cin >> x;

Visit : www.EasyEngineeering.net

51 Visit : www.EasyEngineeering.net

int y; cout << "Enter another number: "; cin >> y; int op; do { cout << "Enter an operation (0=add, 1=subtract, 2=multiply): "; cin >> op; } while (op < 0 || op > 2); //create a function pointer named p int(*p)(int,int); //Set p to point to the function the user choose switch (op) { case 0: p = add(x, y); break; case 1: p = subtract(x, y); break; case 2: p = multiply(x, y); break; } cout << "The answer is: " << p(x,y) << endl; return 0; } Instead of calling the Add( ),Subtract( ) or Multiply( ) function directly . we have instead set p to point at the function we wish to call. Then we call the function through the pointer. The compler is unable to use early binding to resolve the function call p(x,y) because it cannot tell which function p will be pointing to at compile time.

Visit : www.EasyEngineeering.net

52 Visit : www.EasyEngineeering.net

2.8.7 Compile time polymorphism In C++ programming you can achieve compile time polymorphism in two way, which is given below;  

Method overloading Method overriding

Method Overloading in C++ Whenever same method name is exiting multiple times in the same class with different number of parameter or different order of parameters or different types of parameters is known as method overloading. In below example method "sum()" is present in Addition class with same name but with different signature or arguments. Example of Method Overloading in C++ #include #include class Addition { public: void sum(int a, int b) { cout<
Visit : www.EasyEngineeering.net

53 Visit : www.EasyEngineeering.net

60

2.8.8 Method Overriding in C++ Define any method in both base class and derived class with same name, same parameters or signature, this concept is known as method overriding. In below example same method "show()" is present in both base and derived class with same name and signature. Example of Method Overriding in C++ #include #include class Base { public: void show() { cout<<"Base class"; } }; class Derived:public Base { public: void show() { cout<<"Derived Class"; } } int mian() { Base b; //Base class object Derived d; //Derived class object b.show(); //Early Binding Ocuurs d.show(); getch(); } Output Base class Derived Class

Visit : www.EasyEngineeering.net

54 Visit : www.EasyEngineeering.net

Compile Time Polymorphism Run Time Polymorphism In Compile time Polymorphism, call is In Run time Polymorphism, call is not resolved resolved by the compiler. by the compiler. It is also known as Static binding, Early It is also known as Dynamic binding and overloading as well. binding,Late binding and . overriding as well Overloading is compile time polymorphism Overriding is run time polymorphism having where more than one methods share the same same method with same parameters or name with different parameters or signature signature, but associated in a class & its and different return type. subclass. It is achieved by function overloading and It is achieved by virtual functions and pointers operator overloading It provides fast execution because known early It provides slow execution as compare to early at compile time binding because it is known at runtime. Compile time polymorphism is less flexible as Run time polymorphism is more flexible as all all things execute at compile time things execute at run time

Visit : www.EasyEngineeering.net

55 Visit : www.EasyEngineeering.net

1.

FAQ-A List out the operators that cannot be overloaded. The operators shown in the following table cannot be overloaded. The table includes the preprocessor symbols # and ##. Operator Name .

Member selection

.*

Pointer-to-member selection

::

Scope resolution

?:

Conditional

#

2.  

3.

Preprocessor convert to string

Preprocessor concatenate ## What are friend functions? Friend functions are global functions. They are non-member functions of class, but they can access private and protected members of the class. To make any non member function as friend function to class, the function signature (with friend keyword in front) has to be included anywhere within the class declaration. The general syntax is: friend return-type function-name([argumentlist]); class Point { friend void ChangePoint( Point & ); int x, y; … }; void ChangePoint ( Point &i ) { i.x++; i.y++; } What are conversion functions? Conversion functions are special member functions of the class, they are used to convert object of class type to appropriate primitive type, which has special signature. Its signature is given below: operator target-data-type( ) { return expression;

Visit : www.EasyEngineeering.net

56 Visit : www.EasyEngineeering.net

4.

} Conversion functions are often called "cast operators". class Integer { int i; public: operator int() // conversion function convert Integer to int { return i; } }; What are virtual functions? Write the syntax. A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. Virtual functions support runtime polymorphism. If function defined in the base class is redefined in the derived class with same signature, than function with same signature defined in the base class has to be declared as virtual function by adding virtual key word in front of it. Its general signature is class Base {… public: virtual return-type functionname([arg-list]) { } … };

5.

What is meant by abstract base class? An abstract class is more generic class that contains at least one or more pure virtual function. They are used to force its derived classes to follows certain interface standard across its derived classes. Abstract class can have member variable, and non pure virtual functions also. These variables and non pure virtual functions can only be used through its derived classes, because abstract cannot be instantiated. The following is an example of an abstract class: class AB { public: virtual void f() = 0; }; 6. Write a short note on pure virtual function. Pure virtual functions are functions without body. They are simply function declaration without body within abstract class. It will have the following signature: return-type function-name([arg-list]) = 0; Pure virtual function always ends with equal to (=) followed by zero(0) followed by semicolon.

Visit : www.EasyEngineeering.net

57 Visit : www.EasyEngineeering.net

They are used to force its derived classes to follows certain interface standard across its derived classes. Example: class AB { public: virtual void f() = 0; }; 7.

What is the difference between function overloading and function overriding? Function overloading Function overriding If more than one function defined using If function with same signature is same name but with different signature defined within both base class and its within the same class then it is referred derived class then it is referred as as function overloading. function overriding. No inheritance involved in function Inheritance involved in function overloading. overriding. Function call determined based on Function call determined based on number of argument and / or types of object from which function is called. argument involved.

8.

What is the difference between abstract base class and virtual base class? Virtual base class Abstract base class Virtual base class involved in hybrid Abstract base class involved in inheritance, that is combination of hierarchical inheritance and some multiple and multilevel inheritance. times in multilevel inheritance. It may or may not contain pure virtual It must contain one or more pure function. virtual function. It does not force its derived classes to It does force its derived classes to follow any standard interface. follow standard interface.

9.What is the difference between conversion function and operator function? Conversion function Operator function Conversion functions are used to Operator functions are used to redefine the mean of operator for specific convert object of class type to variable class, of primitive type. so that compiler know how use that operator for object of specific class. General signature of conversion function is:

General signature of operator function is:

Visit : www.EasyEngineeering.net

58 Visit : www.EasyEngineeering.net

operator target-data-type( ) { return expression; }

return-type operator #([arg-list] ) { return expression; } Note: replace # with operator you want to overload

10. What is template? Template is the C++ feature that allows the C++ programmer to define generic classes and generic functions. They contain algorithms that works regardless of data types. Generic classes are container, in which you can store any type of data. 11. What is inheritance? It is the process by which one object can acquire the properties of another object. It provides ability to define new class that can reuse code present in the existing classes, instead of rewriting the same code again. A new class is derived from an existing one, generally referred as base class. The derived class reuse the base class members, and can add members or alter the feature of existing members. 12. Write the signature of unary operator function for ++ and – for prefix and postfix form? The syntax of operator function for operator ++ and – using member function for both postfix and prefix: // prefix increment return-type operator ++( ); operator return-type // prefix decrement operator – – ( ); operator // postfix increment return-type operator ++(int); operator return-type // postfix decrement operator – – (int); operator The syntax of operator function for operator ++ and – using friend function / global function for both postfix and prefix: friend return-type operator ++(class-name obj); // Prefix increment friend return-type operator ++(class-name obj, int); // Postfix increment friend return-type operator – – (class-name obj); // Prefix decrement friend return-type operator – – (class-name obj, int); // Postfix decrement 13. Write the signature of binary operator function using friend function and member function? The general syntax of operator function for binary operator using member function: return-type operator operator-symbol (Class-name obj1)

Visit : www.EasyEngineeering.net

59 Visit : www.EasyEngineeering.net

The general syntax of operator function for binary operator using global function: return-type operator operator-symbol (Class-name obj1, Class-name obj2 ) 14. What are the inheritance in which ambiguity errors are possible?  Multiple inheritance  Hybrid inheritance 15.What are the restrictions imposed on overloading operators such as >> and << ? Operator function that overload >> and << must be defined as friend / global function, but cannot be defined as member-functions 16. What is meant by function selection? The function selection among overloaded function is determined by matching number of arguments and types of arguments exists in the function-call with function-declaration. Procedure of overloaded function selection algorithm is given below:  Use an exact match if found (use explicit cast for exact match) If exact match not found try the following:  Try standard type promotions (from float to double, from bool, char, short to int)  Try standard type conversions (from int to double)  Try user-defined conversion 17. What is meant by ADT conversion? Converting variable of primitive types (int, float, double, etc) to object of class types, converting object of class type to variable of primitive type is referred as ADT conversion. The first type of conversion is done using conversion constructor, the second type of conversion is done using conversion function. 18. What is conversion constructor? Constructor definition with one argument is referred as conversion constructor. It is used to convert variable of primitive types (int, float, double, etc) into object of class types. Example: class Demo { int a; public: Demo(int x) { a = x; } // conversion constructor }; int main( ) { Demo d2 = 20; // convert int value 20 into d2, an object of Demo int x = d2; //error cannot convert from ADT Demo to basic type int } 19. What is conversion function?

Visit : www.EasyEngineeering.net

60 Visit : www.EasyEngineeering.net

conversion functions are used to convert object of class type into variable of primitive type. Conversion functions are often called "cast operators". It has the following general syntax: operator target-data-type( ) { return expression; } Example: class Integer { int i; public: … operator int() // conversion function convert Integer to int { return i; } }; 20. How the member functions are defined? Member functions of the class could be defined in the following way:  Define within the class.  These functions are treated as inline function. Example: class x { int a, b, c; public: int add() // inline member function add { return a + b + c; } };  Declare within the class but define outside the class. To define member functions outside the class, we use scope resolution operator to differentiate member function from global function Example: class x { int a, b, c; public: int add();

Visit : www.EasyEngineeering.net

61 Visit : www.EasyEngineeering.net

//declaration of member function }; int x :: add() { return a + b+c; } } 21. What is the use of scope resolution operator? Scope resolution operator used for the following reason: To differentiate class member function from global function.: #include class MyClass { public: void display( ); }; void display( ) // non-member-function { cout<< "display"< int i; //global variable void myfunction() { int i; i = 10; :: i = 20; } 22. List the restriction imposed on static member function?  Static member function can only call other static member functions and static member variables of the class, but cannot reference other nonstatic member functions and non-static member variables of the class.  Static member function of the class can be invoked either using class name or using object name Example:

Visit : www.EasyEngineeering.net

62 Visit : www.EasyEngineeering.net

Cout << “square root of 16 = ” << Math :: sqrt(16) << endl; (or) Math m; //not advisable Cout << “square root of 16= ” << m.sqrt(16) << endl; 23.What is a constructor ?

   

Constructor is: special member function of class, which has same name as class name accepts zero or more arguments, but does not have return-type. implicitly invoked by c++ runtime when object of the class is created, but explicitly cannot be called. generally used to initialize object’s member variables or to dynamically allocate memory for object’s member pointer variables at runtime. always placed under public section.

24. What is a destructor? Destructor is:  special member function of class, which has same name as class name preceded with tilde(~) symbol.  neither accepts accept arguments not return any value.  implicitly invoked by c++ runtime when end of the block in which object created has been reached.  generally used to garbage collect memory used by member variables of the object, when it is no more used.  always placed under public section.

25.What is the use of this pointer?  this pointer is used to differentiate class’s member-variable from formal parameter of member function, when both formal parameter and class-membervariable have the same name.  this pointer is automatically created and passed by C++ runtime, whenever non static member-functions (including constructor) of class is called. It always refer to the invoking object. Example: class Demo { int a; public: Demo(int a) { this –> a = a; //assign value from formal parameter a to class variable a }

Visit : www.EasyEngineeering.net

63 Visit : www.EasyEngineeering.net

}; 26. Differentiate constructor and destructor? Constructor Destructor Constructors are generally used to Destructors are generally used to initialize member variable or garbage collect memory used by dynamicall y allocate memory for member pointer variables of object, member pointer variables of the class, when object no more used. when object of the class is created. Constructor accepts zero or more Destructor never accepts arguments. arguments. Constructors are invoked when object Destructors are invoked when object created. destroyed. 27.What are different types of constructor?  Default constructor – which never accepts arguments  Conversion constructor – accepts only one argument, it is used to convert variable of primitive type to object of class type  copy constructor – accepts one argument as object of same class type  parameterized constructor – accepts one or more arguments  constructor initialize 28.What is parameterized constructor? Constructors which accepts one or more arguments are referred as parameterized constructor. class Box { double d, w, h; public: Box(double t) { d = w = h = t; } Box(double t1, double t2, double t3) { d = t1; w = t2; h = t3; } }; 29.What is the significance of cont member function? const member function are read-only member function, they cannot modify value of member variable, but only can retrieve values of member variables. class Demo {

Visit : www.EasyEngineeering.net

64 Visit : www.EasyEngineeering.net

double d; public: void print() const { cout<<”d=”<
Visit : www.EasyEngineeering.net

65 Visit : www.EasyEngineeering.net

33. What is meant by data abstraction? Abstraction in the process of selecting important data sets for an Object in your software and leaving out the insignificant ones. Once you have modeled your object using Abstraction, the same set of data could be used in different applications. 34. What is polymorphism? Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Other polymorphism concept includes function overloading and function overriding. PART – B 1. Explain in detail about how do you overload binary and unary operators with sample program. 2. Why do you need friend function and class? Explain with suitable example. 3. Write a program to overload I/O operators? Explain the functionality of each. 4. Explain how do you overload subscript operator with an example. 5. Explain how do you overload function call operator with an example. 6. Explain how do you overload increment and decrement operator with suitable example. 7. Write a program in C++ to find the factorial of the given number using operator overloading and class. 8. Write a C++ program to define class that implements the functionality of complex numbers. Overload arithmetic operators such as +, –, *, / to add, subtract, multiply and divide two complex numbers respectively. Also overload relational operator == to compare whether two objects of complex number are same. 9. Explain how do you create pointer to class members with suitable example. 10. Explain in detail above function template? Also explain with an example what is meant by explicit specialization of generic function. 11. Explain in detail above class template? Also explain with suitable example what is meant by explicit specialization of generic class. PART- C 1.Write a C++ program to implement Simple ADT stack. 2.Write a C++ program to implement Simple ADT Queue. 3.Write a C++ program to implement Simple ADT String. 4.Write a C++ program to implement dynamic two dimensional array. 5.What is constructor? Explain different types of constructor C++ supports with suitable example. 6.With suitable example, explain how constructors and destructors are used for dynamic memory allocation and garbage collection in C++. 7.Explain the features of static member function and static member variables in c++ with suitable example. 8.Explain the following: (a) const member function (b) mutable member variables (c) conversion function

Visit : www.EasyEngineeering.net

66 Visit : www.EasyEngineeering.net

9.Explain ADT conversion in details with suitable example. 10.Explain nested class and local class with suitable example.

Visit : www.EasyEngineeering.net

1 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year UNIT III

LINEAR DATA STRUCTURES Syllabus: Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list implementation –– singly linked lists –Polynomial Manipulation Stack ADT – Queue ADT - Evaluating arithmetic expressions.

3.1 DATA STRUCTURES A data structure defines a way of organizing all data items that consider not only the elements stored but also stores the relationship between the elements. A data structure represents the logical relationship that exists between the individual elements of data to carry out certain tasks. A data structure is a physical representation of an ADT. It indicates the data type and also suggest how these could be stored on the computer system memory. For example, an integer as a data structure can be defined as a integer data type stored on consecutive memory bytes. An Abstract Data Type (ADT) is a data type in which the members of the data type are unknown to users of the type. If a data structure is created using static memory allocation ( data structure formed when the number of data items are known in advance) it is known as Static Data structure ( or) Fixed size data structure. Ex: Arrays , Structures If a data structure is created using dynamic memory allocation ( data structure formed when the number of data items are not known in advance) it is known as Dynamic Data structure ( or) Variable size data structure. Ex: Arrays , Structures Dynamic data structure can be classified into two types such as linear and non linear data structure. Linear data structures have a linear relationship between its adjacent elements. Ex : Linked List

Visit : www.EasyEngineeering.net

2 Visit : www.EasyEngineeering.net

A linked list is a linear dynamic data structure that can grow and shrink during its execution time.

Visit : www.EasyEngineeering.net

3 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Non Linear Data structure don‟t have a linear relationship between its adjacent elements. Each node may point to several nodes. But in linear data structure, each node has a link which points to another node. Ex : Tree , Graph Abstract Data Type (ADT) A data type that is defined entirely by a set of operations is referred to as an ADT. An ADT is a combination of interface and implementation. The interface defines the logical properties of an ADT and especially the signature of its operations. The implementation defines the representation of the data structure and the algorithm that implements the operations. Linear Data Structures There are two methods by which we can construct a linear data structure. They are, Method 1: By using a sequence of memory locations. These are implemented using arrays. Method 2: By using pointers or links. These are implemented using linked lists. The different types of linear data structures are: Lists The list can be implemented using arrays and pointers. Stacks The stacks can be implemented using arrays and linked lists. Queues The queue can be implemented using arrays and linked lists. Non-Linear Data Structures Non-linear data structure don‟t have a linear relationship between its adjacent elements. Each node may point to several nodes. But in linear data structure ,each node has a link which points to another node. Example Tree, Graph.

Visit : www.EasyEngineeering.net

4 Visit : www.EasyEngineeering.net

Tree A tree is a non-linear data structure that may point to one (or) more nodes at a time.

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Graph A graph is similar to tree except that it has no hierarchical relationship between its adjacent elements.

3.2 LIST ADT Linear List A Linear list is a data object whose instances are of the form ( e1, e2, …en), where n is a finite natural number. ei



Element of the list. n



length of the list. s



size of the element. For example,

a list of names, list of marks, etc. Operations of List ADT The following operations that are performed on a linear list are,        



Create a list.



Delete a list.



Determine whether the list is empty.



Determine the length of the list.



Find the kth element.



Search for a given element.



Delete the kth element.



Insert a new element.



Display all elements.

Implementation of LIST List can be implemented in two ways. They are: 

Using arrays

Visit : www.EasyEngineeering.net

5 Visit : www.EasyEngineeering.net





Using linked list

Array based implementation C program to implement various operations of linear list using arrays:

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

#include #include #define MAX 20 //maximum no of elements in the list //user defined datatypes struct list { int list[MAX]; int element; //new element to be inserted int pos; //position of the element to be inserted or deleted int length; //total no of elements }l; enum boolean { true, false }; typedef enum boolean boolean; void main() { int ch; intNTnt element; int pos; l.length = 0; while(1) { ch = menu(); switch (ch) { case 1: l.length = 0; create(); break; case 2: if (islistfull() != true)

Visit : www.EasyEngineeering.net

6 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

{ printf("\tEnter the New element : "); scanf("%d", &element); printf("\tEnter the Position : "); scanf("%d", &pos); insert(element, pos); } else { printf("\tList if Full. Cannot insert"); printf("\nPress any key to continue..."); getch(); } break; case 3: if (islistempty() != true) { printf("Enter the position of element to be deleted : "); scanf("%d", &pos); delet(pos); } else { printf("List is Empty."); printf("\nPress any key to continue..."); getch(); } break; case 4: printf("No of elements in the list is %d", l.length);

Visit : www.EasyEngineeering.net

7 Visit : www.EasyEngineeering.net

printf("\nPress any key to continue..."); getch(); break; case 5: printf("Enter the element to be searched : "); scanf("%d", &element); find(element); break; case 6: display(); break; case 7: exit(0); break; default: printf("Invalid Choice"); printf("\nPress any key to continue..."); getch(); } } } /* function to display the list of elements */ int menu() { int ch; clrscr(); printf("\n\t\t********************************************\n"); printf("\t\t******LIST Implementation Using Arrays******\n"); printf("\t\t********************************************\n\n");

EC6301 / OOPS AND DS Sem / II Year

BE (ECE) III

Visit : www.EasyEngineeering.net

8 Visit : www.EasyEngineeering.net

printf("\t1. Create\n\t2. Insert\n\t3. Delete\n\t4. Count\n\t5. Find\n\t6. Display\n\t7. Exit\n\n\tEnter your choice : "); scanf("%d", &ch); printf("\n\n"); return ch;

} /* function to create initial set of elements */ void create(void) { int element; int flag=1; while(flag==1) { printf("Enter an element : "); scanf("%d", &element); l.list[l.length] = element; l.length++; printf("To insert another element press '1' : "); scanf("%d", &flag); } } /* function to display the elements in the list */ void display(void) { int i; for (i=0; i
/* function to insert the given element at specified position */ void insert(int element, int pos) { int i; if (pos == 0) { printf("\n\nCannot insert at zeroth position"); getch(); return; } if (pos-1 > l.length) { printf("\n\nOnly %d elements exit. Cannot insert at %d postion", l.length, pos); printf("\nPress any key to continue...");

Visit : www.EasyEngineeering.net

9 Visit : www.EasyEngineeering.net

getch(); } else { for (i=l.length; i>=pos-1; i--) { l.list[i+1] = l.list[i]; } l.list[pos-1] = element; l.length++; } } /* function to delete the element at given position */ void delet(int pos) { int i;

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

if(pos == 0) { printf("\n\nCannot delete at zeroth position"); getch(); return; } if (pos > l.length) { printf("\n\nOnly %d elements exit. Cannot delete", l.length, pos); printf("\nPress any key to continue..."); getch(); return;

Visit : www.EasyEngineeering.net

10 Visit : www.EasyEngineeering.net

} for (i=pos-1; i
EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

printf("\nPress any key to continue..."); getch(); break; } } if(flag == 1) { printf("Element not found.\nPress any key to continue..."); getch();

Visit : www.EasyEngineeering.net

11 Visit : www.EasyEngineeering.net

} } /* function to check whether the list is full or not */ boolean islistfull(void) { if (l.length == MAX) return true; else return false; } /* function to check whether the list is empty or not */ boolean islistempty(void) { if (l.length == 0) return true; else return false; }

Linked List Implementation

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

A Linked list is a collection of elements called nodes, each of which stores two items called info and link. Info is an element of the list and a link is a pointer to the next element. The linked list is also called a chain. The different types of Linked lists are,  



Singly linked list.



Doubly linked list



Circularly linked list

Singly Linked Lists

Visit : www.EasyEngineeering.net

12 Visit : www.EasyEngineeering.net

A singly linked list is a linked list in which each node contains only one link pointing to the next node in the list.

In a singly linked list, the first node always pointed by a pointer called HEAD. If the link of the node points to NULL, then that indicates the end of the list. Operations of Singly Linked List The following operations that can be performed on a singly linked list are,      



Count the number of elements.



Add an element at the beginning of the list.



Add an element at the end of the list.



Insert an element at the specified position in the list.



Delete an element from the list.



Search x in the list.



Display all the elements of the list.

Example for insertion of an element Initially the linked list consists of only one element 10. 10

NULL

head

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Next if we want to insert another element 20 into the linked list,then store the address of 20 in the link part of 10. 10

20

NULL

head

Visit : www.EasyEngineeering.net

13 Visit : www.EasyEngineeering.net

Next if we want to insert another element 30 into the linked list,then store the address of 30 in the link part of 20. 10

20

30

NULL

head Example for deletion of an element Now if we want to delete 20 from the linked list, just store the address of 30 in the link part of 10. 10

20

30

NULL

head 10

30

NULL

head /* C++ Program to Implement Singly Linked List */ #include #include /* Node Declaration */ struct node { int info; struct node *next; }*start; /* Class Declaration */ class single_llist

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

{ public: node* create_node(int); void insert_begin(); void insert_pos(); void insert_last(); void delete_pos(); void sort(); void search(); void update(); void reverse(); void display();

Visit : www.EasyEngineeering.net

14 Visit : www.EasyEngineeering.net

single_llist() { start =NULL; } }; /* Main :contains menu */ void main() { int choice, nodes, element, position, i; single_llist sl; start =NULL; while(1) { cout<
EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

cout<<"3.Insert node at position"<>choice; switch(choice) { case1: cout<<"Inserting Node at Beginning: "<
Visit : www.EasyEngineeering.net

15 Visit : www.EasyEngineeering.net

case3: cout<<"Inserting Node at a given position:"<
EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

cout<
Visit : www.EasyEngineeering.net

16 Visit : www.EasyEngineeering.net

case10: cout<<"Exiting..."<
EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

default: cout<<"Wrong choice"<
if(temp ==NULL) { cout<<"Memory not allocated "<info = value; temp->next =NULL; return temp; } } /* Inserting element in beginning */ void single_llist::insert_begin() { int value; cout<<"Enter the value to be inserted: "; cin>>value; struct node *temp, *p; temp = create_node(value);

Visit : www.EasyEngineeering.net

17 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

if(start ==NULL) { start = temp; start->next =NULL; } else { p = start; start = temp; start->next = p; } cout<<"Element Inserted at beginning"<
{ int value; cout<<"Enter the value to be inserted: "; cin>>value; struct node *temp, *s; temp = create_node(value); s = start;

while(s->next !=NULL) { s = snext; } temp->next =NULL; s->next = temp;

cout<<"Element Inserted at last"<
Visit : www.EasyEngineeering.net

18 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

/* Insertion of node at a given position */ void single_llist::insert_pos() { int value, pos, counter =0; cout<<"Enter the value to be inserted: "; cin>>value; struct node *temp, *s, *ptr; temp = create_node(value);

cout<<"Enter the postion at which node to be inserted: "; cin>>pos; int i; s = start; while(s !=NULL)

{ s = s->next; counter++; } if(pos ==1) { if(start ==NULL) { start = temp; start->next =NULL; } else { ptr = start; start = temp; start->next = ptr; }

Visit : www.EasyEngineeering.net

19 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

} elseif(pos >1&& pos <= counter) { s = start; for(i =1; i < pos; i++) { ptr = s; s = s->next; } ptr->next = temp; temp->next = s; } else { cout<<"Positon out of range"<
Visit : www.EasyEngineeering.net

20 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

for(s = ptr->next;s !=NULL;s = s->next) { if(ptr->info > s->info) { value = ptr->info; ptr->info = s->info; s->info = value;

} } ptr = ptr->next; } } /* Delete element at a given position */ void single_llist::delete_pos() { int pos, i, counter =0; if(start ==NULL) { cout<<"List is empty"<>pos; struct node *s, *ptr; s = start; if(pos ==1) { start = s->next; } else

Visit : www.EasyEngineeering.net

21 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

{ while(s !=NULL) { s = s->next; counter++; } if(pos >0&& pos <= counter) { s = start; for(i =1;i < pos;i++)

{ ptr = s; s = s->next; } ptr->next = s->next; } else { cout<<"Position out of range"<
{ int value, pos, i; if(start ==NULL)

{

Visit : www.EasyEngineeering.net

22 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

cout<<"List is empty"<>pos; cout<<"Enter the new value: "; cin>>value; struct node *s, *ptr; s = start; if(pos ==1) { start->info = value; } else { for(i =0;i < pos -1;i++) { if(s ==NULL) { cout<<"There are less than "<next; } s->info = value; } cout<<"Node Updated"<
Visit : www.EasyEngineeering.net

23 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

{ int value, pos =0; bool flag =false; if(start ==NULL)

{ cout<<"List is empty"<>value; struct node *s; s = start;

while(s !=NULL) { pos++; if(s->info == value) { flag =true; cout<<"Element "<next; } if(!flag) cout<<"Element "<
{ struct node *ptr1, *ptr2, *ptr3; if(start ==NULL)

Visit : www.EasyEngineeering.net

24 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

{ cout<<"List is empty"<next ==NULL) { return; } ptr1 = start; ptr2 = ptr1->next; ptr3 = ptr2->next; ptr1->next =NULL; ptr2->next = ptr1; while(ptr3 !=NULL) { ptr1 = ptr2; ptr2 = ptr3; ptr3 = ptr3->next; ptr2->next = ptr1;

} start = ptr2; } /* Display Elements of a link list */ void single_llist::display() { struct node *temp; if(start ==NULL)

{ cout<<"The List is Empty"<
Visit : www.EasyEngineeering.net

25 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

} temp = start; cout<<"Elements of list are: "<info<<"->"; temp = temp->next; } cout<<"NULL"<
APPLICATION OF LIST POLYNOMIAL MANIPULATION Polynomial addition, multiplication (8th degree polynomials) using arrays: //Addition of Two Polynomial #include #include #include struct poly{

int coeff; int pow; poly *next; }; class add2poly { poly *poly1, *poly2, *poly3; public: add2poly(){poly1=poly2=poly3=NULL;} void addpoly(); void display();

Visit : www.EasyEngineeering.net

26 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

}; void add2poly :: addpoly(){ int i,p; poly *newl=NULL,*end=NULL; cout<<"Enter highest power for x\n"; cin>>p; //Read first poly cout<<"\nFirst Polynomial\n"; for(i=p;i>=0;i--)

{ newl=new poly; newl->pow=p; cout<<"Enter Co-efficient for degree"<>newl->coeff; newl->next=NULL; if(poly1==NULL) poly1=newl; else end->next=newl; end=newl; } //Read Second poly cout<<"\n\nSecond Polynomial\n"; end=NULL; for(i=p;i>=0;i--) { newl=new poly; newl->pow=p; cout<<"Enter Co-efficient for degree"<>newl->coeff;

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

newl->next=NULL; if(poly2==NULL) poly2=newl; else end->next=newl; end=newl; } //Addition Logic poly *p1=poly1,*p2=poly2; end=NULL; while(p1 !=NULL && p2!=NULL){ if(p1->pow == p2->pow){ newl=new poly; newl->pow=p--; newl->coeff=p1->coeff + p2->coeff; newl->next=NULL; if(poly3==NULL)

Visit : www.EasyEngineeering.net

27 Visit : www.EasyEngineeering.net

poly3=newl; else end->next=newl; end=newl; } p1=p1->next; p2=p2->next; } } void add2poly :: display(){ poly *t=poly3; cout<<"\n\nAnswer after addition is : "; while(t!=NULL){

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

cout.setf(ios::showpos); cout<coeff; cout.unsetf(ios::showpos); cout<<"X"<pow; t=t->next; } } void main(){ clrscr(); add2poly obj; obj.addpoly(); obj.display(); getch();

}

//Multiplication of 2 polynomials #include class poly

{ private: struct polynode { float coeff ; intexp; polynode*link ; }*p ; public: poly(); void poly_append (float c, int e ); void display_poly();

Visit : www.EasyEngineeering.net

28 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

void poly_multiply ( poly &p1, poly &p2 ); void padd (float c, int e ); ~poly(); }; poly ::poly() { p =NULL; } void poly ::poly_append(float c, int e ) { polynode*temp ; temp= p ; if( temp ==NULL) { temp=new polynode ; p =temp ; } else { while( temp -> link !=NULL) temp= temp -> link ; temp-> link =new polynode ; temp= temp -> link ; } temp-> coeff = c ; temp->exp= e ; temp-> link =NULL;

} void poly ::display_poly() { polynode*temp = p ; int f =0; while( temp !=NULL) { if( f !=0) {

Visit : www.EasyEngineeering.net

29 Visit : www.EasyEngineeering.net

if( temp -> coeff >0) cout<<" + ";

else cout<<" "; } if( temp ->exp!=0) cout<< temp -> coeff <<"x^"<< temp ->exp; else cout<< temp -> coeff ; temp= temp -> link ; f =1; } } void poly ::poly_multiply( poly &p1, poly &p2 ) { polynode*temp1, *temp2 ; float coeff1, exp1 ; temp1 =p1.p; temp2 =p2.p;

if( temp1 ==NULL&& temp2 ==NULL) return; if( temp1 ==NULL) p =p2.p; else

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

{ if( temp2 ==NULL) p =temp1 ; else

{

while( temp1 !=NULL) { while( temp2 !=NULL) { coeff1 = temp1 -> coeff * temp2 ->coeff ; exp1 = temp1 ->exp+ temp2 ->exp; temp2 = temp2 >link ;

Visit : www.EasyEngineeering.net

30 Visit : www.EasyEngineeering.net

padd( coeff1, exp1 ); } temp2 =p2.p; temp1 = temp1 ->link ; } } } } void poly ::padd(float c, int e ) { polynode*r, *temp ; temp= p ; if( temp ==NULL|| c > temp ->exp) { r =newpolynode ; r-> coeff = c ; r->exp= e ; if( p ==NULL) {

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

r-> link =NULL; p =r ; } else { r-> link = temp ; p =r ; } } else { while( temp !=NULL) {

Visit : www.EasyEngineeering.net

31 Visit : www.EasyEngineeering.net

if( temp ->exp== e ) { temp-> coeff += c ; return; } if( temp ->exp> c &&( temp -> link ->exp< c || temp-> link ==NULL)) { r =newpolynode ; r-> coeff = c; r->exp= e ; r-> link =NULL; temp-> link = r ; return; } temp= temp -> link ; }

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

r-> link =NULL; temp-> link = r ;

} } poly :: ~poly() { polynode*q ; while( p !=NULL)

{ q = p ->link ; delete p ; p =q ; } } void main() { poly p1 ; p1.poly_append(3, 5); p1.poly_append(2, 4); p1.poly_append(1, 2);

cout<<"\nFirst polynomial: "<< endl ; p1.display_poly();

Visit : www.EasyEngineeering.net

32 Visit : www.EasyEngineeering.net

poly p2 ; p2.poly_append(1, 6); p2.poly_append(2, 5); p2.poly_append(3, 4);

cout<<"\nSecond polynomial: "<< endl ; p2.display_poly(); poly p3 ;

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

p3.poly_multiply( p1, p2 ); cout<<"\nResultant polynomial: "<< endl ; p3.display_poly(); } Logic 3

2

Polynomial A: 3x +2x +x+1 3

Polynomial B: 5x +7x Step 1: 3x

3

2x

2

x

1

A

i 5x

3

7x

B

j 8x

3

C

k Step 2: 3x

3

2x

2

x

1

A

i 5x

3

7x

B

j 8x

3

2x

2

C

Visit : www.EasyEngineeering.net

33 Visit : www.EasyEngineeering.net

k Step 3: 3x

3

2x

2

x

1

A

Visit : www.EasyEngineeering.net

34 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year i

5x

3

7x

B

j 8x

3

2x

2

8x

C

k Step 4: 3x

3

2x

2

x

1

i 5x

3

7x

j 8x

3

2x

2

8x

1

k

3.4 STACK ADT A stack is an ordered collection of items accessed as last-in-first-out order. A stack is a list of elements in which insertions and deletions are restricted to one end. The end from which the elements are added / removed is referred to as top of the stack. Stack is also referred as piles and push down lists. The last element placed in the stack will be at the top of the stack. The last element added to stack is the first element to be removed. Hence, the stacks are referred to as Last-in-first-out lists. A stack is referenced via a pointer to the top elements of the stack referred as top pointer. The top pointer keeps track of the top element in the stack.

Visit : www.EasyEngineeering.net

35 Visit : www.EasyEngineeering.net

Initially, when the stack is empty, the top pointer has a value zero and when the stack contains a singly element the top pointer has a value one and so on. Example

EC6301 / OOPS AND DS   



Bangles in a lady hand



Coaches of train

BE (ECE) III Sem / II Year

Piles of notebook. Basic Operations of Stack ADT The primitive operations of the stack include PUSH and POP. PUSH: Allows adding an element at the top of the stack. A push () operation adds (or) inserts a new element to the stack. Each time a new element is inserted in the stack, the top pointer is incremented by one before the element is placed on the stack. The general syntax for inserting a new element into the stack. Push(S, X); The element „x‟ is inserted into the stack„s‟. POP: Allows removing an element from the top of the stack. A pop() operation deletes the top most element in the stack. Each time, an element is removed from the stack; the top pointer is decremented by one. The general syntax for removing an element from the stack. Pop(S); Used to delete the top element from the stack. PEEK: Allows displaying top element of the stack. A peek() is an operation used to display the element from the top of the stack, pointed by the top pointer. The general syntax is used to return the element at the top of the stack. Top(S); Implementation of the Stack ADT

A  

stack can be implemented in two ways. 

Array Implementation Linked list Implementation

Array Implementation of Stack ADT

Visit : www.EasyEngineeering.net

36 Visit : www.EasyEngineeering.net

  



An array is a place holder to store the elements of the stack.



The size of an array should be fixed. An integer variable top can be used to mark the top of the stack.

EC6301 / OOPS AND DS    

BE (ECE) III Sem / II Year

The notation top = -1 is used for initializing the top variable.  Top can be made to point to the top element of the stack.  When a new element is to be pushed then the top can be incremented and the element can be added.  In this notation, top will be -1 for an empty stack. Push operation



If the elements are added continuously to the stack using the push operation then the stack grows at



one end.  Initially when the stack is empty the top = -1. The top is a variable which indicates the position of the topmost element in the stack.

Visit : www.EasyEngineeering.net

37 Visit : www.EasyEngineeering.net

 

If arrays are used for implementing the stacks,

it would be very easy to manage the stacks.  However, the problem with an array is that we are required to declare the size of the array before using it in a program.   This means the size of the stack should be fixed. We can declare the array with a maximum size



large enough to manage a stack.  As result, the stack can grow or shrink within the space reserved for it. Pop operation On deletion of elements the stack shrinks at the same end, as the elements at the top get removed.

Visit : www.EasyEngineeering.net

38 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

#include #include #include class stack { int stk[5]; int top; public:

stack() { top=-1; } void push(int x) { if(top >4) { cout<<"stack over flow"; return; } stk[++top]=x; cout<<"inserted"<
Visit : www.EasyEngineeering.net

39 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

if(top <0) { cout<<"stack under flow"; return; } cout<<"deleted"<=0;i--) cout<
main() { int ch; stack st;

while(1) { cout<<"\n1.push 2.pop 3.display 4.exit\nEnter ur choice"; cin>> ch; switch(ch) { case1:cout<<"enter the element";

Visit : www.EasyEngineeering.net

40 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

cin>> ch; st.push(ch); break; case2: st.pop();break; case3: st.display();break; case4:exit(0); } } return(0); } Implementation of Stack ADT using Linked Lists The

stack can be implemented by using the singly linked list. This type of the

representation has more advantage than representing stack using array.They are, 

It is not necessary to specify the no of elements to be stored in a stack during its



declaration. (memory is allocated dynamically at run time when an element is added to the stack).  Insertion and deletion can be handled easily and efficiently.  Linked list representation of stack can grow and shrink in size without wasting the



memory space depending upon the insertion and deletion that occurs in the list. Initially, when the stack is empty, top points to NULL. When an element is added using the push operation, top is made to point to the latest element whichever is added. Push operation  



Create a temporary node and store the value of x in the data part of the node. Now make link part of temp point to Top and then top point to Temp. That will make the

new node as the topmost element in the stack.

Visit : www.EasyEngineeering.net

41 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Pop operation   



The data in the topmost node of the stack is first stored in a variable called item. Then a temporary pointer is created to point to top. The top is now safely moved to the

next node below it in the stack.  Temp node is deleted and the item is returned.

#include #include #include class node { public: class node *next; int data; }; class stack :public node

Visit : www.EasyEngineeering.net

42 Visit : www.EasyEngineeering.net

{

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

node *head; int tos; public:

stack() { tos=-1; } void push(int x) { if(tos <0) { head =new node; head->next=NULL; head->data=x;

tos ++; } else { node *temp,*temp1; temp=head; if(tos >=4) { cout<<"stack over flow"; return; } tos++; while(temp->next !=NULL) temp=temp->next; temp1=new node; temp->next=temp1;

Visit : www.EasyEngineeering.net

43 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

temp1->next=NULL; temp1->data=x;

} } void display() { node *temp; temp=head; if(tos <0) { cout<<" stack under flow"; return; } while(temp !=NULL) { cout<data<<" "; temp=temp->next; } } void pop() { node *temp; temp=head; if( tos <0) { cout<<"stack under flow"; return; } tos--; while(temp->next->next!=NULL)

Visit : www.EasyEngineeering.net

44 Visit : www.EasyEngineeering.net

{ temp=temp->next; } temp->next=NULL; } }; main() { stack s1; int ch; while(1) { cout<<"\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n enter ur choice:"; cin>> ch; switch(ch) { case1:cout<<"\n enter a element"; cin>> ch; s1.push(ch); break; case2: case3:

s1.pop();break; s1.display();

break; case4:exit(0); } } return(0); } Applications of Stack ADT Some of the applications of the stack include,

Visit : www.EasyEngineeering.net

45 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS    



Towers of Hanoi



Reversing the String



Recursion using stack

BE (ECE) III Sem / II Year

Evaluation of Arithmetic Expressions Towers of Hanoi

            



Towers of Hanoi is a gaming puzzle.



Invented by French Mathematician Edouard Lucas in1883. The objective of this puzzle is to transfer the entire disks from Tower1 to Tower3 using

Tower2.  The rules to be followed in moving the disks from tower1 to tower3 using tower2.  Only one disc can be moved at a time.  Only the top disc on any tower can be moved to any other tower.  A larger disc cannot be placed on a smaller disc.  It can be implemented using recursion. To move the largest disc to the bottom of tower3.  We move the remaining n-1 disks to tower2 and then move the largest disc to tower 3.  This process is continue until to place the entire disc in towerr3 in order.  Since, disc are moved from each tower in a LIFO manner each tower may be considered as stack.  The least no of moves required to solve the problem according to our algorithm is given by O(N)= 2N-1.  The time complexity is measured in no of movements. Reversing the String

  



Main characteristics of the stack are reversing the order of its contents.



The tasks can be accomplished by pushing each character until the end of the string.



Now, the individual characters are popped off from the stack.

Visit : www.EasyEngineeering.net

46 Visit : www.EasyEngineeering.net

 

Since the last character pushed into the stack would be the first character to be popped off from the stack.  The string will come off in the reverse order.

EC6301 / OOPS AND DS 

BE (ECE) III Sem / II Year

Since, the individual character are moved from the stack in a LIFO manner, the stack



operation is implemented.  For example,The input string is Kumar. The output string is ramuk.  Recursion Using Stack:  Recursion is a process by which a function calls itself repeatedly until some specified



condition has been satisfied.  When a recursive program is executed, the recursive function calls are not executed



immediately.  They are placed on a stack (LIFO) until the condition that terminates the recursive

 

function.   The function calls are then executed in reverse order, as they are popped off the stack. For example,  #include  #include void main() {  int num,fac; cout<<”Enter the no”; cin>>num; fac=fact(num); printf(“The factorial val %d is”,fac); } int fact(int x) { if(x<=1) return 1; else

Visit : www.EasyEngineeering.net

47 Visit : www.EasyEngineeering.net

return (x*fact(x-1)); } Evaluation of Arithmetic Expression

EC6301 / OOPS AND DS    

BE (ECE) III Sem / II Year



An expression consists of two components namely Operands and Operators.



Operators indicate the operation to be carried out operands.



Operands are the variables and constants. There are three ways of representing expression in computers. They are,

o

Infix Notation

o

Prefix Notation

o

Postfix Notation

Infix Notation   



The normal way of representing mathematical expression is called as infix expression. In this form of expressing an arithmetic expression the operator comes in between its

operands.  For example,(a+b). The operator „+‟ is written in between the operands “a” and “b”. Advantages

 



It is the mathematical way of representing the expression. It‟s easier to see visually which operation is done from the first to last.

Prefix Notation  



Also referred as polish notation. It is a way of representing algebraic expression without the use of parenthesis (or) rules of



operator precedence.  In this form of expressing an arithmetic expression the operator is written before its



operands.  For example,(+ab). The operator „+‟ is written before the operands “a” and “b”. Postfix Notation

Visit : www.EasyEngineeering.net

48 Visit : www.EasyEngineeering.net

  



Also referred as suffix notation (or) reverse polish notation. In this form of expressing an arithmetic expression the operator is written after its

operands.  For example,(ab+). The operator „+‟ is written after the operands “a” and “b”. Conversion of Notations Rules to be followed during infix to postfix conversion

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year



Fully, parenthesize the expression starting from left to right. (During parenthesizing the



operators having higher precedence are the first parenthesized)  Move the operators one by one to their right such that each operator replaces their corresponding right parenthesize.



The part of the expression, which has been converted into postfix, is to be treated as single operand.  Once, the expression is converted into postfix form remove all the paranthesis. For example, The infix expression is, 3 + 8 * 4 / 2 – (8 -3) 3+8*4/2–83-3+84*/2–83–3+84*2/–83–384*2/+-83–384*2/+83-The postfix expression is,3 8 4 * 2 / + 8 3 - Rules to be followed during infix to prefix conversion



Fully, parenthesize the expression starting from left to right. (During parenthesizing the



operators having higher precedence are the first parenthesized).  Move the operators one by one to their right such that each operator replaces their corresponding right parenthesis.



The part of the expression, which has been converted into postfix, is to be treated as single operand. 

Once, the expression is converted into postfix form remove all the paranthesis.

Visit : www.EasyEngineeering.net

49 Visit : www.EasyEngineeering.net

3 + 8 * 4 / 2 - (8 - 3) 3 + 8 * 4 / 2 - - 8 3 +* 84/

2

--83

+/ *84

2-

-83

+3/*842

--83

+3 /*84 2 -83

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

The prefix expression is,+ 3 / * 8 4 2 – 8 3

Conversion of Infix to Postfix Form Using Stack The following procedure is used to convert infix to postfix expression.        



Read the infix string.



Traverse from left to right of the expression.



If an operand is encountered, add to the postfix string. If the item is an operator push it on the stack , if any of the following conditions are

satisfied.  

The stack is empty. If the precedence of the operator at the top of the stack is of lower priority than the

operator being processed.  If all the above condition fails, then pop the operator being processed to the postfix string.  When the infix string is empty, pop the elements of the stack onto the postfix string to get the result. Example:The infix expression is,a + b *c + (d* e + f) * g INFIX STRING

STACK

a+b*c+(d*e+f)*g +b*c+(d*e+f)*g

POSTFIX STRING a

+

a

Visit : www.EasyEngineeering.net

50 Visit : www.EasyEngineeering.net

b *c+(d*e+f) *g

+

ab

*c+(d*e+f)*g

+

ab

c + (d*e+f)*g

+*

abc

+ ( d*e+f)*g

+

abc*+

(d*e+f)*g

+(

abc*+

d*e+f)*g

+(

abc*+ d

*e + f )*g

+( *

abc *+ d

e +f)*g

+(*

abc *+ de

f)*g

+(+

abc *+de *f

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

)*g

+(+

abc *+de*f+

*g

+*

abc*+de*f+

G

+*

abc * + de * f+g*+

Evaluation of Postfix Expression Using a Stack Rules for evaluating a postfix expression using stack   



Traverse from left to right of the expression.



If an operand is encountered push it onto the stack. If an operator is encountered pop two elements from the stack evaluate those operands



with that operator and push the result back in the stack.  When the evaluation of the entire expression is over, the only thing left on the stack



should be the final result.  If there are zero (or) more than one operands left on the stack either your program is inconsistent (or) the expression was invalid. Example:The postfix expression is4 5 7 + *

scan 457: push(4), push(5), push(7) scan +: op2=7, pop(), op1=5, pop(), push(op1+op2) scan *: op2=12, pop(), op1=4, pop(), push(op1*op2) expression end ==> return 48!

Visit : www.EasyEngineeering.net

51 Visit : www.EasyEngineeering.net

3.5      

QUEUE ADT 

A queue is a linear data structure. A queue is an ordered collection of elements in which are accessed in a first-in-first-

out(FIFO) order.  In a queue, the elements which are inserted at one end and deletions are made at another end.  

The end at which the insertions are made is referred to as the rear end.



The end at which the deletions are made is referred to as the front end. In a queue , the first element inserted will be the first element to be removed. So a queue

is referred to as FIFO List.(First-in-First-out List).

Visit : www.EasyEngineeering.net

52 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Deletion

Insertion

Front

Rear

Representation of Queue Example 



A Reservation Counter   Jobs in a printer  A queue of ready jobs waiting for the processor.

Basic Operations of Queue ADT The basic operations that can be done on a queue are,  



Enqueue() Dequeue()

Enqueue()  



An enqueue() operation adds a new element in a queue. This process is carried out by incrementing the rear end and adding a new element at the



rear end position.  The syntax for inserting a new element into a queue is,

o

Enqueue(Q,X) (or) Insert(Q,X)



The element 'X' inserted into a queue 'Q'.



Dequeue()    o





A dequeue() operation removes the first element from the queue. A dequeue() operation is carried out by incrementing the front end and deleting the first

element at the front end position.  The syntax for removing a first element from the queue. Dequeue(Q) (or) Delete(Q) Here, the first element is removed from the queue.



Types of Queue ADT

Visit : www.EasyEngineeering.net

53 Visit : www.EasyEngineeering.net

There are different types of queue.  



Linear Queue Circular Queue

EC6301 / OOPS AND DS 

BE (ECE) III Sem / II Year

Deque Linear Queue

    



A queue is referred to as the linear queue.



The queue has two ends such as front end and rear end. The rear end is where we insert the elements and the front end is where we delete the

elements.  In a linear queue, we can traverse in only one direction.  In a linear queue if the front pointer is in first position, and the rear pointer is in the last



position then the queue is said to be fully occupied.  Initially, the front and rear ends are at the same position(Initialized to -1.)  When we insert the elements, the rear pointer moves one by one until the last index



position is reached.(the front pointer doesn't change.)  When we delete the elements, the front pointer moves one by one until the rear pointer is



reached.(the rear pointer doesn't change.)  If the front and rear pointer positions are initialized to -1, then the queue is said to be



empty. Circular Queue 

Circular Queue is another form of a linear queue in which the last position is connected to



the first position of the list.  It is similar to linear queue has two ends such as front and rear ends.  The rear end is where we insert the elements and front end is where we delete the

  

elements.  In a circular queue we can traverse in only one direction.  Initially, front and rear ends are at the same position.

Visit : www.EasyEngineeering.net

54 Visit : www.EasyEngineeering.net



 When we insert an element, the rear pointer moves one by one until the front end is



reached.(front end doesn't change.)  If the next position of the rear is front, then the queue is said to be fully occupied.  When we delete an element, the front pointer moves one by one until the rear end is



reached.  If the front end reaches the rear end, then the queue is said to be empty.



EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Representation of Circular Queue Deques   



Deque means Double-Ended Queue. It is another form of a queue in which insertion and deletions are made at the both front

and rear ends of the queue.  There are two types of deque. o

Input Restricted Deque.

o

Output Restricted Deque.

Input Restricted Deque The input restricted deque allows insertions at one end (it can be either front (or) rear). Output Restricted Deque The output restricted deque allows deletions at one end(it can be either front (or) rear).

Visit : www.EasyEngineeering.net

55 Visit : www.EasyEngineeering.net

Represent ation Of Deque Implementation of Queue ADT A queue can be implemented in two ways.  



Array Implementation of Linear Queue. Linked list Implementation Of linear Queue.

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Array Implementation of Queue  



Queues and Arrays are ordered collection of elements. The number of elements in the array is fixed. But the size of the queue is constantly



changed when the elements are enqueued and dequeued.  The queue is stored in a part of the array, so an array can be declared large enough to



hold the maximum no of elements of the queue.  During execution of the program, the queue size can be varied within the space reserved

 

for it.  

All the basic operations performed on the queue by using array. The basic operations are,

o

Creation

o

Enqueue (or) Insertion

o

Dequeue (or) Deletion

Operations on a Queue     



There are two common operations in a queue.



They are addition of an element to the queue and deletion of an element from the queue.



Two variables front and rear are used to point to the ends of the queue. The front points to the front end of the queue where deletion takes place and rear points

to the rear end of the queue, where the addition of elements takes place.  Initially, when the queue is empty, the front and rear is equal to -1.

Visit : www.EasyEngineeering.net

56 Visit : www.EasyEngineeering.net

Creation() Creation of a queue requires the declaration of an array and initializing front and rear end indicates to -1 respectively. Enqueue(X)   



An element can be added to the queue only at the rear end of the queue.



Before adding an element in the queue, it is checked whether queue is full. If the queue is full, then addition cannot take place. Otherwise, the element is added to

the end of the list at the rear side.

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Dequeue( )  



The dequeue ( ) operation deletes the element from the front of the queue. Before deleting and element, it is checked if the queue is empty. If not the element

pointed by front is deleted from the queue and front is now made to point to the next element in the queue.

Queue using array #include #include #include class queue { int queue1[5]; int rear,front; public: queue() {

Visit : www.EasyEngineeering.net

57 Visit : www.EasyEngineeering.net

rear=-1; front=-1;

} void insert(int x) { if(rear >4) { cout<<"queue over flow";

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

front=rear=-1; return; } queue1[++rear]=x; cout<<"inserted"<
Visit : www.EasyEngineeering.net

58 Visit : www.EasyEngineeering.net

for(int i=front+1;i<=rear;i++) cout<
EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

while(1) { cout<<"\n1.insert 2.delet 3.display 4.exit\nEnter ur choice"; cin>> ch; switch(ch) { case1:cout<<"enter the element"; cin>> ch; qu.insert(ch); break; case2: qu.delet();break; case3: qu.display();break; case4:exit(0); } } return(0); } Linked list implementation of queue    



Queue can be represented using a linked list.



Linked lists do not have any restrictions on the number of elements it can hold. Space for the elements in a linked list is allocated dynamically; hence it can grow as long

as there is enough memory available for dynamic allocation.  The queue represented using linked list would be represented as shown. The front pointer points to the front of the queue and rear pointer points to the rear of the queue.

Visit : www.EasyEngineeering.net

59 Visit : www.EasyEngineeering.net

      

This representation has more advantages than representing queue using arrays. The advantages are,

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year



It is not necessary to specify the no of elements to be stored in a queue during its



declarations.  Insertions and deletions can be handled easily and efficiently.  Linked list representation of queue can grow and shrink in size without wasting the



memory space depending upon the insertion and deletion that occurs in the list. Basic Operations The basic operations can be performed on the queue are,  



Enqueue() Dequeue()

Enqueue Operation In linked list representation of queue, the addition of new element to the queue takes place at the rear end. It is the normal operation of adding a node at the end of a list.

Dequeue Operation The dequeue( ) operation deletes the first element from the front end of the queue. Initially it is checked, if the queue is empty. If it is not empty, then return the value in the node pointed by front, and moves the front pointer to the next node. #include #include #include class node { public:

Visit : www.EasyEngineeering.net

60 Visit : www.EasyEngineeering.net

class node *next; int data; }; class queue :public node {

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

node *head; int front,rare;

public: queue() { front=-1; rare=-1;

} void push(int x) { if(rare <0) { head =new node; head->next=NULL; head->data=x;

rare ++; } else { node *temp,*temp1; temp=head; if(rare >=4) { cout<<"queue over flow"; return; } rare++; while(temp->next !=NULL) temp=temp->next; temp1=new node;

Visit : www.EasyEngineeering.net

61 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

temp->next=temp1; temp1->next=NULL; temp1->data=x;

}}

void display() { node *temp; temp=head; if(rare <0) { cout<<" queue under flow"; return; } while(temp !=NULL) { cout<data<<" "; temp=temp->next; } } void pop() { node *temp; temp=head; if( rare <0) { cout<<"queue under flow"; return; } if(front == rare)

Visit : www.EasyEngineeering.net

62 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

{ front = rare =-1; head=NULL; return; } front++; head=head->next; } }; main() { queue s1; int ch; while(1) { cout<<"\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n enter ru choice:"; cin>> ch; switch(ch) { case1: cout<<"\n enter a element"; cin>> ch; s1.push(ch);break;

case2: s1.pop();break; case3: s1.display();break;

case4:exit(0); } } return(0);

Visit : www.EasyEngineeering.net

63 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

} Applications Of Queue Adt The applications of the queue such as,  



Priority Queue Scheduling Algorithms

Priority queue 

A priority queue is a collection of elements in which the elements are added to the end



and the high priority element is deleted.  In a priority queue, each and every element containing the key referred as the priority for



the elements.  The operations performed in a queue are similar to the queue except that the insertion and



deletion elements made in it.  Elements can be inserted in any order, but are arranged in order of their priority value in

 

the queue.  The elements are deleted from the queue in the order of their priority.  The elements with the same priority are given equal importance and processed accordingly. The priority queue can be implemented in the following ways.

 



Ordered List Implementation of Priority Queue Heap Implementation of Priority Queue

Applications of Priority Queue 

Modeling of systems. Where the keys might correspond to event times, to be processed in



chronological order.  CPU scheduling in computer systems, where the keys might correspond to priorities



indicating which processes are to be served first.  Numerical computations, where the keys might be computational errors indicating that the largest should be dealt with first.

Visit : www.EasyEngineeering.net

1 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

UNIT IV NON LINEAR DATA STRUCTURES Syllabus: Trees – Binary Trees – Binary tree representation and traversals – Application of trees: Set representation and Union-Find operations – Graph and its representations – Graph Traversals – Representation of Graphs – Breadth-first search – Depth-first search – Connected components.

4.1 TREE ADT Definition A tree is a non-linear data structure that is used to represents hierarchical relationships between individual data items. A tree is a finite set of one or more nodes such that, there is a specially designated node called root. The remaining nodes are partitioned into n>=0 disjoint sets T1, T2,..Tn, where each of these set is a tree T1,…Tn are called the subtrees of the root. Basic Terminologies Branch Branch is the link between the parent and its child. Leaf A node with no children is called a leaf. Sub tree A Subtree is a subset of a tree that is itself a tree. Degree The number of subtrees of a node is called the degree of the node. Hence nodes that have degree zero are called leaf or terminal nodes. The other nodes are referred as non-terminal nodes. Children The nodes branching from a particular node X are called children of its parent. Siblings Children of the same parent are said to be siblings. Degree of tree

Visit : www.EasyEngineeering.net

2 Visit : www.EasyEngineeering.net

Degree of the tree is the maximum of the degree of the nodes in the tree.

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Ancestors Ancestors of a node are all the nodes along the path from root to that node. Hence root is ancestor of all the nodes in the tree. Level Level of a node is defined by letting root at level one. If a node is at level L, then its children are at level L + 1. Height or depth The height or depth of a tree is defined to be the maximum level of any node in the tree. Climbing The process of traversing the tree from the leaf to the root is called climbing the tree. Descending The process of traversing the tree from the root to the leaf is called descending the tree.

4.2 BINARY TREE ADT

Visit : www.EasyEngineeering.net

3 Visit : www.EasyEngineeering.net

Binary tree has nodes each of which has no more than two child nodes. A binary tree is a finite set of nodes that either is empty or consists of a root and two disjoint binary trees called the left subtree and right subtree. Left child The node present to the left of the parent node is called the left child.

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Right child The node present to the right of the parent node is called the right child.

Types of Binary tree ADT Skewed Binary tree If the new nodes in the tree are added only to one side of the binary tree then it is a skewed binary tree. A B C

Complete binary tree A binary tree in which every non leaf node has exactly two children not necessarily to be on the same level.

Visit : www.EasyEngineeering.net

4 Visit : www.EasyEngineeering.net

A B

D

H

C E

I

F

G

J

K

Visit : www.EasyEngineeering.net

5 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Full binary tree A binary tree in which all the leaves are on the same level and every non leaf node has exactly two children. A

B

D

C

E

F

G

4.3 BINARY TREES REPRESENTATION There are two ways in which a binary tree can be represented. They are: (i)

Array representation of binary trees.

(ii)

Linked representation of binary trees Array Representation of Binary Trees An array can be used to store the nodes of a binary tree. The nodes stored in an array are accessed sequentially. Linear representation of binary tree uses a single dimensional array of size 2

h+1

– 1, where „h‟ is the height of the tree.

Visit : www.EasyEngineeering.net

6 Visit : www.EasyEngineeering.net

A

B

C

1

2

3

D

E

F

G

4

5

6

7

C

D

A B D

C

A 1

B 2

3

4

5

6

7

Linked Representation Of Binary Trees In linked representation of binary trees, instead of arrays, pointers are used to connect the various nodes of the tree. Hence each node of the binary tree consists of three parts namely, the info, left and right. The info part stores the data, left part stores the address of the left child and the right part stores the address of the right child. Logically the binary tree in linked form can be represented as shown.

Visit : www.EasyEngineeering.net

7 Visit : www.EasyEngineeering.net

4.4 BINARY TREE TRAVERSALS There are three standard ways of traversing a binary tree T with root N. They are: ( i ) Preorder Traversal (ii ) Inorder Traversal (iii) Postorder Traversal General outline of these three traversal methods can be given as follows: Preorder Traversal 1.

Process the root N.

2. preorder.

Traverse the left subtree of N in

3. Traverse the right subtree of N in preorder. Algorithm ( Preorder) PREORDER( ROOT ) Temp = ROOT If temp = NULL Return End if Print info(temp) If left(temp) ≠ NULL PREORDER( left(temp)) End if If right(temp) ≠ NULL PREORDER(right(temp)) End if End PREORDER

Visit : www.EasyEngineeering.net

8 Visit : www.EasyEngineeering.net

Inorder Traversal 1.

Traverse the left subtree of N in inorder.

2.

Process the root N. 3.

Traverse the right subtree of N in inorder.

Algorithm ( Inorder) INORDER( ROOT ) Temp = ROOT If temp = NULL Return End if If left(temp) ≠ NULL

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

INORDER(left(temp)) End if Print info(temp) If right(temp) ≠ NULL INORDER(right(temp)) End if End INORDER Postorder Traversal Traverse the left subtree of N in postorder. Traverse the right subtree of N in postorder. Process the root N. Algorithm ( Postorder) POSTORDER( ROOT ) Temp = ROOT If temp = NULL Return End if

Visit : www.EasyEngineeering.net

9 Visit : www.EasyEngineeering.net

If left(temp) ≠ NULL POSTORDER(left(temp)) End if If right(temp) ≠ NULL POSTORDER(right(temp)) End if Print info(temp) End POSTORDER

Example

Pre-order: F, B, A, D, C, E, G, I, H

Visit : www.EasyEngineeering.net

10 Visit : www.EasyEngineeering.net

In-order: A, B, C, D, E, F, G, H, I

Visit : www.EasyEngineeering.net

11 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Post-order: A, C, E, D, B, H, I, G, F

4.5 APPLICATION OF TREES: SET REPRESENTATION AND UNIONFIND OPERATIONS Representation using Lists One obvious way to implement sets is to use lists.The code would have a variable of type list. The operations are:    



addElt would add the element to the list.



remElt would require a method that traverses the list and removes the given element



size would return the length of the list

hasElt would traverse the list to check for the element  addElt could check whether the given element is in the list, and only modify the list if the element is not already there. There are other ways to do this though: the constraint on "no duplicates" is reflected in the behavior of the size method. Representation using Binary Search Tree

Visit : www.EasyEngineeering.net

12 Visit : www.EasyEngineeering.net

One obvious way to implement sets is to use Binary Search Tree. The code would have a variable of type list. The operations are: 

size behaves as in a plain binary tree.

Visit : www.EasyEngineeering.net

13 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

hasElt optimizes on hasElt on a plain binary tree: if the element you‟re looking for is not



in the root, the search recurs on only one of the left subtree (if the element to find is smaller than 

that in the root) or the right subtree (if the element to find is larger than that in the root).  addElt always inserts new elements at a leaf in the tree. It starts from the root, moving to the left or right subtree as needed to maintain the invariant. When it hits a empty tree, addElt



replaces it with a new node with the data to add and two empty subtrees.  remElt traverses the BST until it finds the node with the element to remove at the root. If the node has no children, remElt returns the empty tree. If the node has only one child, remElt replaces it with its child node. If the node has two children, remElt replaces the value in the node with either the largest element in the left subtree or the smallest element in the right subtree; remElt then removes the moved node value from its subtree. Union-Find Operations Operations supported Union( x, y ) - Performs a union o f the sets containing two elements x and y. Find( x ) - Returns a pointer to the set Returns a pointer to the set containing element x. Example applications

  



Electrical cable/internet connectivity network



Cities connected by roads Cities belonging to the same country

Algorithm function MakeSet(x) x.parent := x function Find(x) if x.parent == x return x else return Find(x.parent) function Union(x, y) xRoot := Find(x)

Visit : www.EasyEngineeering.net

14 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

yRoot := Find(y) xRoot.parent := yRoot

4.6 GRAPH AND ITS REPRESENTATIONS Definition Graph is a non-linear data structure used to represent the network structure. A graph is a collection of nodes (or) vertices and edges. A graph G= (V, E) consists of a set of vertices (v) and set of edges (E). Each edge has a pair (v, w), where v, w ε V Edges are also called arcs. Basic Terminologies Directed Graph (or) Digraph If the pair of edges are ordered or directionally oriented, then it is called directed graph or digraph. Note: The directed edge is also called arcs.

A

B

C

Undirected Graph If the edge in a graph is not directionally oriented, then it is called undirected graph.

A

B

C

Visit : www.EasyEngineeering.net

15 Visit : www.EasyEngineeering.net

Path It is a sequence of vertices w1, w2…..wn such that (wi, wi+1) ε V for 1≤i≤N.

Visit : www.EasyEngineeering.net

16 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Path length It is the number of edges present in the path, which is equal to N-1 , where N is the number of vertices.

1

2

3

4

Path from 1 to 4 is 1-> 2-> 3-> 4 Path length is 3. Cycle graph It is a path, in which starting and ending vertices are the same one (i.e.) the path with will start and end in the same vertices.

1

2

3

Path: 1 2 3 1 Acyclic graph A directed graph is said to be acyclic when there is no cyclic path in it. It is also called DAG (Directed Acyclic graph). Complete graph A graph is said to be complete graph in which there is an edge between every pair of vertices.

Visit : www.EasyEngineeering.net

17 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

A

B

C

Strongly Connected In a digraph, if there is a path from every vertex to every other vertex is called strongly connected. Otherwise it is said to be weakly connected graph. A

A

B

C

Strongly Connected

B

C

Weakly Connected

Loop A loop is a special case of a cycle in which a single arc Begins and ends with the same vertex

A Disjoint A graph is said to be disjoint, if it is not connected.

A

B

D

C

E

Degree

Visit : www.EasyEngineeering.net

18 Visit : www.EasyEngineeering.net

The degree of a vertex is the number of arcs or edges incident to it.

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Indegree The indegree is the numbers of arcs are entering into the vertex. Outdegree The outdegree of a vertex is the number of arcs exiting (or leaving) from the vertex.

A

B

E C

D

Degree of D = 4 Indegree of D is 3 Outdegree of D is 1 Representation Adjacency Matrix Having mapped the vertices to integers, one simple representation for the graph uses an adjacency matrix. Using a |V| x |V| matrix of booleans, connects i and j. Edges can be

we set aij = true if

undirected, in which case if aij = true,

or directed, in which aij != aji, unless there

are two edges,

one in

an edge

then aji = true also, either

direction,

between i and j. The diagonal elements, aii, may be either ignored or, in cases such as state machines, where the presence or absence of a connection from a node to itself is relevant, set to true or false as required.

Visit : www.EasyEngineeering.net

19 Visit : www.EasyEngineeering.net

When space is a problem, bit maps can be used for the adjacency matrix. In this case, an ADT for the adjacency matrix improves the clarity of your code immensely by hiding the bit twiddling that this space saving requires. In undirected graphs, only one half of the matrix needs to be stored. If the graph is dense, i.e most of the

nodes are connected

the O(|V|2) cost of initializing an adjacency matrix is

matched by the cost

EC6301 / OOPS AND DS

by edges, then of inputting and

BE (ECE) III Sem / II Year

setting the edges. However, if the graph is sparse, ie |E| is closer to |V|, then an adjacency list representation may be more efficient. Adjacency List Representation Adjacency lists are lists of nodes that are connected to a given node. For each node, a linked list of nodes connected to it can be set up. Adding an edge to a graph will generate two entries in adjacency lists - one in the lists for each of its extremities. Following is an example undirected graph with 5 vertices.

Adjacency Matrix is,

Visit : www.EasyEngineeering.net

20 Visit : www.EasyEngineeering.net

Adjacency List is,

4.7 

GRAPH TRAVERSALS There are two methods for traversing through the nodes of the graph. They are.

 *

Breadth First Search Traversal

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

* Depth First Search Traversal

Breadth first search traversal 

As the name implies, this method traverse the nodes of the graph by searching through the nodes breadth wise. Rules

 



Select an unvisited node V, visit it. It‟s level is called the current level. From each node X in the current level, in the order in which the level nodes were visited. Visit

all the unvisited neighbors of X. The newly visited nodes from this level form a new level. This new  

level becomes the next current level.  Repeat step 2 for all unvisited vertices.  Repeat from step 1 until no more vertices are remaining. Algorithm Algorithm BFT ( G , n ) Begin repeat for i=1 to n visited[i] = 0

Visit : www.EasyEngineeering.net

21 Visit : www.EasyEngineeering.net

end repeat repeat for i=1 to n if visited[i] = 0 BFS(i)

end if end repeat end Algorithm BFS ( v) u=v visited [ v ] = 1 repeat while ( true ) repeat for all vertices w adjacent from u if visited [w] = 0 Add w to Queue visited [ w ] = 1 end if end repeat if Queue is empty return end if delete u from Queue End while End BFS

Visit : www.EasyEngineeering.net

22 Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

23 Visit : www.EasyEngineeering.net

Depth First Search Traversal 

As the name implies, this method traverse the nodes of the graph by searching through the nodes depth wise.

Rules      

Select an unvisited node V, visit it. It‟s level is called the current level.



Find unvisited neighbors of the current node, visit it and make it the current node.



If more than one unvisited neighbors then resolve the tie by following the alphabetical order.



If the current node has no unvisited neighbors, backtrack to its parent and make it new current node.  Repeat from step 2 and 3 until no more nodes can be visited.



Repeat from step 1 for the remaining nodes. Algorithm Algorithm DFT ( G , n ) Begin repeat for i=1 to n visited[i] = 0 end repeat repeat for i=1 to n if visited[i] = 0 DFS(i)

end if end repeat end Algorithm DFS ( v) u=v visited [ v ] = 1 repeat for each vertex w adjacent from v if visited [w] = 0 DFS( w )

Visit : www.EasyEngineeering.net

24 Visit : www.EasyEngineeering.net

end if End

Visit : www.EasyEngineeering.net

25 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Depth First Search Traversal

Breadth First Search Traversal

This traversal is done with This traversal is done with the help of the help of stack queue data structure.

data structure.

It works using two ordering. The first order is the order in which the vertices are reached for the first time and second order in which the

It works using one ordering. The order in which the vertices are reached in the same order they get removed from the queue.

vertices become dead. DFS sequence is composed BFS sequence is composed of tree of tree edges and edges and back edges.

cross edges.

The efficiency of the adjacency matrix graph is

The efficiency of the adjacency matrix graph is

2

2

O(V )

θ(V )

The efficiency of the adjacency list graph is

The efficiency of the adjacency list graph is

O(|V|+|E|)

θ(|V|+|E|)

4.8 CONNECTED COMPONENTS A directed graph is strongly connected if there is a path between all pairs of vertices. A strongly connected component (SCC) of a directed graph is a maximal strongly connected subgraph. For example, there are 3 SCCs in the following graph.

Visit : www.EasyEngineeering.net

26 Visit : www.EasyEngineeering.net

We

can

find

all

strongly

connected

components

in

O(V+E)

time.

1) Create an empty stack „S‟ and do DFS traversal of a graph. In DFS traversal, after calling

recursive DFS

vertice a vertex, for adjacent s of push

he

2)Reverse

directionsof all

he

arcs toobtain

vertex to stack. transpo se graph.

3) One by one pop a vertex from S while S is not empty. Let the popped vertex be „v‟. Take v as source and do DFS .The DFS starting from v prints strongly connected component of v. Working The above algorithm is DFS based. It does DFS two times. DFS of a graph produces a single tree if all vertices are reachable from the DFS starting point. Otherwise DFS produces a forest. So DFS of a graph with only one SCC always produces a tree. The important point to note is DFS may produce a tree or a forest when there are more than one SCCs depending upon the chosen starting point. For example, in the above diagram, if we start DFS from vertices 0 or 1 or 2, we get a tree as output. And if we start from 3 or 4, we get a forest. To find and print all SCCs, we would want to start DFS from vertex 4 (which is a sink vertex), then move to 3 which is sink in the remaining set (set excluding 4) and finally any of the remaining vertices (0, 1, 2).Unfortunately, there is no direct way for getting this sequence. However, if we do a DFS of graph and store vertices according to their finish times, we make sure that the finish time of a vertex that connects to other SCCs (other that its own SCC), will always be greater than finish time of vertices in the other SCC. For example, in DFS of above example graph, finish time of 0 is always greater than 3 and 4 (irrespective of the sequence of vertices considered for DFS). And finish time of 3 is always greater than 4. DFS doesn‟t guarantee about other vertices, for example finish times of 1 and 2 may be smaller or greater than 3 and 4 depending upon the sequence of vertices considered for DFS. So to use this property, we do DFS traversal of complete graph and push every finished vertex to a stack. In stack, 3 always appears after 4, and 0 appear after both 3 and 4. In the next step, we reverse the graph.

Visit : www.EasyEngineeering.net

27 Visit : www.EasyEngineeering.net

Consider the graph of SCCs. In the reversed graph, the edges that connect two components are reversed. So the SCC {0, 1, 2} becomes sink and the SCC {4} becomes source. In stack, we always have 0 before 3 and 4. So if we do a DFS of the reversed graph using sequence of vertices in stack, we process vertices from sink to source. Print SCCs one by one.

Visit : www.EasyEngineeering.net

1 Visit : www.EasyEngineeering.net

UNIT V SORTING AND SEARCHING Syllabus: Sorting algorithms: Insertion sort - Quick sort – Merge sort – Searching: Linear search – Binary search.

5.1 SORTING Sorting is an operation of arranging data, in some given order such as increasing (or) decreasing with numerical data (or) alphabetically with character data.Sorting methods can be characterized into two categories:  



Internal sorting External sorting

Internal Sorting Internal sorting methods are the methods that can be used when the list to be sorted is small enough so that the entire sort can be carried out in main memory.The key principles of internal sorting is that all the data items to be stored are retained in the main memory and random access in the memory space can be efficiently used to sort the data items.The various internal sorting techniques are:     



Bubble sort



Selection sort



Insertion sort



Shell sort Quick sort

External Sorting External sorting methods are the methods to be used when the list to be sorted is large and cannot be accommodated entirely in the main memory. In this case, some of data is present in the main memory and some is kept in auxiliary memory such as hard disk, floppy disk, tape etc. The key principle of external sorting is to move data from secondary storage to main memory in large blocks for ordering the data.The various external sorting methods are: Merge sort

Visit : www.EasyEngineeering.net

2 Visit : www.EasyEngineeering.net



 Tape sort

 

5.2

INSERTION SORT The main idea behind the insertion sort is to insert the ith element in its correct place in the ith pass.Suppose an array A with n elements A[1],A[2],………….A[N] is in main memory.The insertion sort algorithm scans A from A[1] to A[N] inserting each element A[K] into its proper position in the previously sorted subarray A[1],A[2],………….A[k-1]. Principle In insertion sort algorithm, each element A[k] in the list is compared with all the elements before it (A[1] to A[k-1]).If any element A[1] is found to be greater than A[k] then A[k] is inserted in the place of A[1]. This process is repeated till all the elements are sorted. Program #include #include main() { int i,j,temp,a[10],n; clrscr();

cout << "Enter the Limit :"; cin >> n; cout << "Enter the elements :"; for(i=0;i> a[i]; for(i=1;i<=n-1;i++)

{ temp=a[i]; for(j=i;j>=1;j--)

{ if(temp < a[j-1])

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

a[j]=a[j-1]; else break;

Visit : www.EasyEngineeering.net

3 Visit : www.EasyEngineeering.net

} a[j]=temp; } cout << "The Sorted List is :"; for(i=0;i
Advantages  



Sorts the list faster when the list has less number of elements. Efficient in cases where a new element has to be inserted into a sorted list.

Disadvantages  



Very slow for large value of n. Poor performance if the list is in almost reverse order.

Visit : www.EasyEngineeering.net

4 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

5.3 MERGE SORT Merge sort is one of the external sorting technique.Merge sort algorithm follows divide and conquer strategy.Given a sequence of „n‟ elements A[1],A[2],………A[N].The basic idea behind the merge sort algorithm is to split the list into two sub lists A[1],…….A[N/2] and A[(N/2)+1],…….A[N].If the list has even length, split the list into equal sub lists.If the list has odd length, divide the list in two by making the first sub list one entry greater than the second sub list.Then split both the sub list is to two and go on until each of the sub lists are of size one.Finally, start merging the individual sub list to obtain a sorted list.Time complexity of merge sort is O(n log n). Principle The given list is divided into two roughly equal parts called the left and right sub files. These sub files are sorted using the algorithm recursively and then the two sub files are merged together to obtain the sorted file. Program #include #include void mergesplit(int a[],int first,int last); void merge(int a[],int f1,int l1,int f2,int l2); int a[25],b[25]; main() { int i,n; cout << "Enter the limit :"; cin >> n; for(i=0;i> a[i];

mergesplit(a,0,n-1); cout << "The Sorted List is:"; for(i=0;i
Visit : www.EasyEngineeering.net

5 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

getch(); } void mergesplit(int a[],int first,int last) { int mid; if(first < last)

{ mid=(first+last)/2; mergesplit(a,first,mid); mergesplit(a,mid+1,last); merge(a,first,mid,mid+1,last); } } void merge(int a[],int f1,int l1,int f2,int l2) { int i,j,k=0; i=f1; j=f2; while(i <= l1 && j <= l2) { if(a[i] < a[j]) b[k]=a[i++];

else b[k]=a[j++]; k++; } while(i <= l1) b[k++]=a[i++]; while(j <= l2) b[k++]=a[j++];

Visit : www.EasyEngineeering.net

6 Visit : www.EasyEngineeering.net

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

i=f1; j=0; while(i <= l2 && j < k) a[i++]=b[j++]; }

Example

Advantages  

Very useful for sorting bigger lists.



Applicable for external sorting also. Disadvantages



5.4

 

Needs a temporary array every time, for sorting the new list.

QUICK SORT Quick sort is very popular sorting method.It is also referred as partition exchange sort was developed by C.A.R.Hoare.Quick sort can sort a list of data significantly faster than any of

Visit : www.EasyEngineeering.net

7 Visit : www.EasyEngineeering.net

the common sorting algorithm.It is a sorting algorithm, which performs very well on larger list than any other sorting methods.The basic strategy of quick sort is to divide and conquer.

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

The main idea of the quick sort is to divide the initial unsorted list into two parts, such that the every element in the first list is less than all the elements present in the second list.The procedure is repeated recursively for both the parts, upto relatively short sequence which can be sorted until the sequences reduces to length one.The first step of the algorithm requires choosing a pivot value that will be used to divide large and small numbers. The first element of list is chosen as a pivot value.Once, the pivot value has been selected, all the elements smaller than the pivot are placed towards the beginning of the set and all the elements larger than the pivot are placed at the right.This process essentially sets the pivot value in the correct place each time.Each side of the pivot is then quick sorted. The quick sort algorithm reduces the unnecessary swaps and moves an item a great distance in one move.The median-of-three portioning method is used to select the pivot. In this method, three elements are randomly chosen and the median of these three values is chosen as the pivot element. Principle A pivot item near the middle of the list is chosen, and the items on either side are moved so that the data items on one side of the pivot element are smaller than the pivot element where as those on the other side are larger. The middle (or) the pivot element is now in its correct position. This procedure is then applied recursively to the 2 parts of the list, on either side of the pivot element until the whole list is sorted. Program #include #include int i,j,n,pivot,a[20]; void quick(int a[],int left,int right); void swap(int a[],int i,int j); main()

Visit : www.EasyEngineeering.net

8 Visit : www.EasyEngineeering.net

{ int i,n,a[20]; cout << "Enter the limit";

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

cin >> n; cout << "Enter the elements"; for(i=0;i> a[i]; quick(a,0,n-1);

cout << "Sorted List is:"; for(i=0;i
{ while(a[i] <= pivot && i < last) i++; while(a[j] >= pivot && j > first) j--; if(i < j) swap(a,i,j); } swap(a,first,j); quick(a,first,j-1); quick(a,j+1,last);

}

Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

9

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

} void swap(int a[],int i,int j) { int t; t=a[i]; a[i]=a[j]; a[j]=t; }

Example 45

28

90

1

46

39

33

i/pivot

87 j

Increment i till the element pointed by i is less than pivot. Decrement j till the element pointed by j is greater than the pivot element. 45

28

90

1

pivot

46

39

i

33

87

j

Now, swap the elements pointed by i and j. 45

28

33

1

pivot

45

46

39

i

28

33

1

pivot

90

87

j

46

39

i

90

87

j

Now, swap the elements pointed by i and j. 45 Pivot

28

33

1

39 i

46

90

87

j

Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

10

45

28

33

1

39

Pivot

46

j

EC6301 / OOPS AND DS

90

87

i

BE (ECE) III Sem / II Year

Once, i and j crosses swap the element pointed by j and pivot and fix the position of the pivot element. 39

28

33

1

45

46

90

87

Consider the elements left to pivot element as one sub array and the elements right to the pivot as another sub array. Apply quick sort to the sub arrays separately. 39

28

33

1

Pivot/i 39

45

46

90

87

45

46

90

87

j 28

33

1

Pivot

j/i

If i and j stops at same position, swap the element pointed by j and pivot and fix the position of the pivot element. 1

28

33

39

45

46

90

87

39

45

46

90

87

39

45

46

90

87

Apply quick sort to the list left to 39. 1

28

33

Pivot/i 1

j 28

Pivot/j

33

i

Once, i and j crosses swap the element pointed by j and pivot and fix the position of the pivot element. 1

28

33

39

45

46

90

87

Apply quick sort to 28,33.

Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

11

1

28

Pivot/i

33

39

45

46

90

87

33

39

45

46

90

87

j

1

28

Pivot/j

i

Once, i and j crosses swap the element pointed by j and pivot and fix the position of the pivot element.

EC6301 / OOPS AND DS 1

28

BE (ECE) III Sem / II Year 33

39

45

46

90

87

Repeat the process with 46,90, and 87. 1

28

33

39

45

46

90

87

90

87

Pivot/i j 1

28

33

39

45

46

Pivot/j

i

Once, i and j crosses swap the element pointed by j and pivot and fix the position of the pivot element. 1

28

33

39

45

46

90

87

39

45

46

90

87

Apply quick sort to 90 and 87. 1

28

33

Pivot/i

j

Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

12

1

28

33

39

45

46

90

87

Pivot i/j If i and j stops at same position, swap the element pointed by j and pivot and fix the position of the pivot element. 1

28

33

39

45

46

87

90

39

45

46

87

90

The final sorted array is, 1

28

33

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

Advantages 

Faster than any other commonly used sorting algorithm. It has a

best average case behavior.   Reduces complexity. Disadvantages 

 

As it uses recursion, stack space consumption is high.

5.5 SEARCHING Searching is the process which is used to find the location of a target element among a list of elements. It is used in situation where we want to find whether a particular item is present in a list or not. For eg, in a given voter list of a colony, a person may search his name to ascertain whether he is a valid voter or not. There are two types of searching namely,    

Linear search Binary search

Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

13

5.6 SEQUENTIAL / LINEAR SEARCH A list can be searched sequentially wherein the search for the data item starts from the beginning and continues till the end of the list. This simple method of search is known as linear search. It has the following characteristics:   

The search is linear. The search starts from the first element and continues in a sequential fashion from

element to element till the desired element is found.   In the worst case, a total number of N steps need to be taken for a list of size N.   Thus, the linear search is slow and to some extent inefficient. Program #include #include void main() { clrscr();

EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

int a[100],i,n,item,s=0; cout<<"\n------------ LINEAR SEARCH ------------ \n\n"; cout<<"Enter No. of Elements="; cin>>n; cout<<"\nEnter Elements=\n"; for(i=1;i<=n;i++) { cin>>a[i]; } cout<<"\nEnter Element you want to Search="; cin>>item; for(i=1;i<=n;i++)

//Array Elements Comparison with Item

Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

14

{ if(a[i]==item) { cout<<"\nData is Found at Location : "<
EC6301 / OOPS AND DS

BE (ECE) III Sem / II Year

5.7 BINARY SEARCH The input should be sorted. The search in the list can be made faster by using “divide and conquer” technique.It has the following characteristics:   

The input list must be sorted It is faster as compared to linear search.

Program #include #include void main()

{ clrscr(); int a[100],n,i,beg,end,mid,item;

cout<<"\n------------ BINARY SEARCH ------------ \n\n"; cout<<"Enter No. of Elements= "; cin>>n;

Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

15

cout<<"\nEnter Elements in Sorted Order=\n"; for(i=1;i<=n;i++) { cin>>a[i]; }

cout<<"\nEnter Item you want to Search= "; cin>>item;

beg=1; end=n;

mid=(beg+end)/2;

// Find Mid Location of Array

EC6301 / OOPS AND DS

while(beg<=end && a[mid]!=item)

BE (ECE) III Sem / II Year

// Compare Item and Value of Mid

{ if(a[mid]
Visit : www.EasyEngineeering.net

Visit : www.EasyEngineeering.net

16

} Example Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}. Step 1

(middle element is 19 > 6):

-1 5 6 18 19 25 46 78 102 114

Step 2

(middle element is 5

< 6):

-1 5 6 18 19 25 46 78 102 114

Step 3

(middle element is 6

== 6):

-1 5 6 18 19 25 46 78 102 114

Visit : www.EasyEngineeering.net

EE6301 PEC ECE_OOPSDS_Unit-1 - 5- By EasyEngineering.net.pdf ...

Page 3 of 3. EE6301 PEC ECE_OOPSDS_Unit-1 - 5- By EasyEngineering.net.pdf. EE6301 PEC ECE_OOPSDS_Unit-1 - 5- By EasyEngineering.net.pdf. Open.

2MB Sizes 2 Downloads 78 Views

Recommend Documents

EE6301 PEC ECE_OOPSDS_Unit-1 - 5- By EasyEngineering.net.pdf ...
Page 3 of 261. EE6301 PEC ECE_OOPSDS_Unit-1 - 5- By EasyEngineering.net.pdf. EE6301 PEC ECE_OOPSDS_Unit-1 - 5- By EasyEngineering.net.pdf.

Access 2_3 pec Sheet
Page 1. Specifications. LOA. 3.60M. Beam. 1.35M. Draft. 1.10M. Main. 5.60sqM. Jib. 1.75sqM. Hull. 72Kg. Keel. 72Kg. Access Liberty.

Access 2_3 pec Sheet
Page 1. Specifications. LOA. 2.3M. Beam. 1.25M. Draft. 0.9M. Sail. 3.8sqM. Hull. 52Kg. Keel. 20Kg. International Access 2.3.

PEC CFATORRENTMELIS.pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item.

Primary EyeCare (PEC)_Member.pdf
mark, of Vision Service Plan. Questions? vsp.com | 800.877.7195. 100%. SATISFACTION. GUARANTEED. Page 1 of 1. Primary EyeCare (PEC)_Member.pdf.

PEC Dinner Invitation 2016.pdf
The Northeast Office serves a sixteen county area including Bradford, Carbon, Columbia, Lackawanna, Lehigh, Luzerne,. Monroe, Montour, Northampton, Northumberland, Pike, Schuylkill, Sullivan, Susquehanna, Wayne and Wyoming Counties. The Council has o

PEC- Image of Success Oct. 2012.pdf
AKAD NOTARIS. Serius Hub. : Dr. DJAFAR. Raya Kutisari Utara 46 Surabaya,. Telp : 081217185318. AIR ZAM-ZAM. istimewa. Direktur GTK Madrasah Suyitno (tengah mengenakan udeng) sedang bercengkrama dengan guru. Page 3 of 5. PEC- Image of Success Oct. 201

PEC- Image of Success Oct. 2012.pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. PEC- Image of Success Oct. 2012.pdf. PEC- Image of Success Oct. 2012.pdf. Open. Extract. Open with. Sign In.

PEC - Plum Interim Superintendent Jan. 2012.pdf
Page 1 of 6. Page 1 of 6. Page 2 of 6. Page 2 of 6. Page 3 of 6. Page 3 of 6. PEC - Plum Interim Superintendent Jan. 2012.pdf. PEC - Plum Interim Superintendent Jan. 2012.pdf. Open. Extract. Open with. Sign In. Main menu. Displaying PEC - Plum Interi

PEC DEFINITIVO 13-11-09.pdf
Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. PEC DEFINITIVO 13-11-09.pdf. PEC DEFINITIVO 13-11-09.pdf.

Invitation for Internal audit of accounts for PEC University of ...
Invitation for Internal audit of accounts for PEC University of Technology.pdf. Invitation for Internal audit of accounts for PEC University of Technology.pdf. Open.

092545_IBVQ-SGQ-PE01-PEC-R4-PEC_2016-17.pdf
socials que han repercutit en les expectatives que el municipi, i l'entorn, tenen del centre com a ... 092545_IBVQ-SGQ-PE01-PEC-R4-PEC_2016-17.pdf.