programming in c++ and algorithms subject code :...

110
PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : 1BIT3C1,4BIT3C1 HANDLED BY PR,RAJESH MCA.,B.Ed CORE COURSE V PROGRAMMING IN C++ AND ALGORITHMS Unit I Principles of object oriented programming Introduction to c++ Tokens, Expressions and Control Structures Functions in c++ Classes and Objects:- Introduction, C Structures Revisited, Specifying a Class, Defining Member Functions, A C++ Program with Class, Making an Outside Function Inline, Nesting of Member Functions, Private member Functions, Array within a class, Memory Allocation for Objects, Static Data Members, Static Member Functions, Array of Objects, Objects as Function Arguments, Friendly Functions, Returning Objects, Const Member Functions, Pointer to Member. Unit II Constructor and Destructors Introduction, Constructors, Parameterized Constructors, Multiple Constructors in a class, Constructors with Default Arguments Dynamic Initialization of Objects, Copy Constructor, Dynamic Constructors, Constructing Two-Dimensional Arrays, Destructors. Unit III Operator Overloading and Type Conversion Introduction, Defining Operator Overloading Overloading Unary, Binary Operators Inheritance Introduction, Defining Derived Class, Single Inheritance, Making Private Member inheritable, Multilevel Inheritance, Multiple Inheritance, Hierarchical Inheritance Hybrid Inheritance, Virtual Base Class, Abstract Classes Pointers, Virtual Functions and Polymorphism Introduction, pointers to objects, this pointer, pointer to Derived Classes, Virtual Functions, Pure Virtual Functions. Unit IV[only the algorithm and examples no theorems] Binary search Depth-first search Breadth-first search topological sort Backtracking Mergesort finding the closest pair of points Strassen’s matrix product algorithm – insertion sort quicksort a lower bound for the sorting problem selection Unit V only the algorithm and examples no theorems] Coin changing Kruskal’s algorithm – Prim’s algorithm – Dijkstra’s algorithm – Huffman codes The continuous Knapsack problem computing Fibonacci number multiplying matrices the longest-common-subsequence problem Algorithm of Floyd and Warshall

Upload: others

Post on 18-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

PROGRAMMING IN C++ and ALGORITHMS

SUBJECT CODE : 1BIT3C1,4BIT3C1

HANDLED BY

PR,RAJESH MCA.,B.Ed

CORE COURSE V – PROGRAMMING IN C++ AND ALGORITHMS

Unit I

Principles of object oriented programming – Introduction to c++ – Tokens, Expressions and

Control Structures – Functions in c++ – Classes and Objects:- Introduction, C Structures

Revisited, Specifying a Class, Defining Member Functions, A C++ Program with Class,

Making an Outside Function Inline, Nesting of Member Functions, Private member

Functions, Array within a class, Memory Allocation for Objects, Static Data Members, Static

Member Functions, Array of Objects, Objects as Function Arguments, Friendly Functions,

Returning Objects, Const Member Functions, Pointer to Member. Unit II

Constructor and Destructors – Introduction, Constructors, Parameterized Constructors, Multiple

Constructors in a class, Constructors with Default Arguments – Dynamic Initialization of Objects,

Copy Constructor, Dynamic Constructors, Constructing Two-Dimensional Arrays, Destructors.

Unit III

Operator Overloading and Type Conversion – Introduction, Defining Operator Overloading –

Overloading Unary, Binary Operators – Inheritance – Introduction, Defining Derived Class,

Single Inheritance, Making Private Member inheritable, Multilevel Inheritance, Multiple

Inheritance, Hierarchical Inheritance – Hybrid Inheritance, Virtual Base Class, Abstract

Classes – Pointers, Virtual Functions and Polymorphism – Introduction, pointers to objects,

this pointer, pointer to Derived Classes, Virtual Functions, Pure Virtual Functions. Unit IV [only the algorithm and examples no theorems]

Binary search – Depth-first search – Breadth-first search – topological sort – Backtracking –

Mergesort – finding the closest pair of points – Strassen’s matrix product algorithm – insertion sort –

quicksort – a lower bound for the sorting problem – selection

Unit V only the algorithm and examples no theorems]

Coin changing – Kruskal’s algorithm – Prim’s algorithm – Dijkstra’s algorithm – Huffman codes –

The continuous Knapsack problem – computing Fibonacci number – multiplying matrices – the

longest-common-subsequence problem – Algorithm of Floyd and Warshall

Page 2: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

1. Data given less importance.

2. Data structure. (The way data is organized becomes very critical. since many functions

access the common data.).

3. Relationship to the real world.

It is difficult to design. The problem is that the main components data structure and

function do not model the real world very well.

Here software maintenance will be easier.

Programs become more readable.

OOPS Concept

Importance of oops

1. Emphasis is on data rather than procedure.

2. Programs are divided into objects.

3. Data structures are designed such that they characterize the object.

4. Functions that operate on the data of an object are tied together in the data structure.

5. Data is hidden and cannot be accessed by external functions.

6. Objects may communicate with each other through functions.

7. New data and functions can be added whenever necessary.

8. Follow bottom up approach in program design.

Characteristics of oops

1. Class

2. Objects

3. Data abstraction.

4. Data encapsulation.

5. Inheritance

6. Polymorphism

7. Dynamic binding

8. Message passing.

1. Class

It is nothing but a user defined data type. It consists of member data and member

functions. Hence a class is a collection of objects of similar type.

The entire set of a data and code of an object can be made a user defined data type

with the help of a class.

Page 3: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

2. Objects

Objects contain data and the code to manipulate that data. It is the runtime entity for a

class. We can access the member variable and member functions of a class by using the

objects only.

Objects are called as instance (variables) of a class. Once a class has been defined we

can create any no of objects belonging to that class.

Objects interact by sending messages to one another.

3. Data abstraction

The way of accessing variables of a class or member functions of a class is called data

abstraction. Class uses the concept of data abstraction, and hence they are known as abstract

base class. (ABC)

4. Data encapsulation

The wrapping up of data and functions into a single unit is known as encapsulation.

The data is not accessible to the outside world and only those functions which are wrapped in

the class can access it.

The insulation of the data from direct access by the program is called data hiding.

5. Inheritance

Inheritance is the process by which objects of one class acquires the properties of

objects of another class.

It provides the idea of reusability. This means that we can add additional features to

an existing class without modifying it.

I.e. we can derive a new class from the existing one. The new class will have the

combined features of both the classes.

6. Polymorphism

Polymorphism is the ability to take more than one form.

It is extensively used in implementing inheritance.

e.g.:

Consider an addition operation. For two no, it will generate a sum.

Similarly if the operands are strings then the operation would produce a third string by

concatenation.

A single object can react on multiple functions.

Overloading

It is same as polymorphism. We can overload functions, operators etc.

7. Dynamic binding

Page 4: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Binding refers to the linking of a procedure call to the code to be executed in response

to the call.

Dynamic binding means that the code associated with a given procedure call is not

known until the time of the call at runtime.

It is associated with polymorphism and inheritance.

8. Message communication

This is done by using the objects. A message for an object is a request for execution

of a procedure and therefore will invoke a function in the receiving object that generates the

desired result.

Functions

Function overloading

It is the logical method of calling the several functions with the same name. Each

redefinition of a function must use different type of parameters, or different no of parameters,

or different sequence of parameters.

The current function to be invoked is determined by checking the number and type of

the arguments but not on the function type.

A function call first matches the prototype having the same no and type of arguments

and then calls the appropriate function for execution. A best match must be unique.

Advantages

1. Eliminating the use of different function name for the same operation.

2. Helps to understand, delay, and grasp easily.

3. Easy maintainability of 1the code.

1. Function overloading with different type of parameters

E.g.: funo1.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

int abs(int);

double abs(double);

void main()

{

int a;

double b;

Page 5: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

clrscr();

cout<<"Enter the value for a:";

cin>>a;

cout<<"Enter the value for b:";

cin>>b;

cout<<abs(a)<<endl;

cout<<abs(b)<<endl;

getch();

}

int abs(int x)

{

return(x<0?-x:x);

}

double abs(double y)

{

return(y<0.0?-y:y);

}

2. Function overloading with different number of arguments

e.g.: uno2.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

int sum(int,int);

int sum(int,int,int);

void main()

{

int a,b,c;

clrscr();

cout<<"Enter any three nos:";

cin>>a>>b>>c;

Page 6: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

cout<<sum(a,b)<<endl;

cout<<sum(a,b,c)<<endl;

getch();

}

int sum(int x,int y)

{

return(x+y);

}

int sum(int p,int q,int r)

{

return(p+q+r);

}

Inline function

Functions are used to save the memory space however when a function is called, it

takes extra time to execute. To avoid this slowdown processing inline functions are used.

When a function is declared as an inline, the actual coding is inserted in the place of function

call while compiling. To make a function as inline, the keyboard inline must be added before

the function definition. While creating an inline function there is no need for function

prototyping.

e.g.: funo3.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

inline int mul(int x,int y)

{

return(x*y);

}

inline int div(int x,int y)

{

return(x/y);

}

void main()

Page 7: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{

int a,b;

clrscr();

cout<<"Enter the value for a and b:";

cin>>a>>b;

cout<<mul(a,b)<<endl;

cout<<div(a,b)<<endl;

getch();

}

Default arguments

C++ allows as calling a function without specifying all its arguments. In the function

prototype declaration, the default values are given. When a call is made to a function without

specifying an argument, the program will automatically assign values to the parameters from

the default function prototype declaration. Default arguments facilitate easy development

and maintenance of program.

e.g.: funo4.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

int sum(int a,int b,int c=10,int d=20);

void main()

{

int a,b;

clrscr();

cout<<"Enter any two nos:";

cin>>a>>b;

cout<<sum(a,b);

getch();

}

int sum(int a,int b,int c,int d)

{

return(a+b+c+d);

Page 8: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

}

Difference between C and C++:-

C C++

1. It is a procedural oriented It is an object oriented programming

programming language (POP) language (OOP).

2. Top down approach Bottom up approach

3. Structures, Unions are used class, object concepts are used

4. Inheritance not allowed Inheritance allowed

5. Data abstraction, encapsul- Data abstraction, and encapsulation

ation not allowed are characteristics of OOPs.

6. Overloading, polymorphism overloading, polymorphism are

are not allowed allowed

Difference between structure and class

Structures Class

1. Variable declarations variable function declarations and

only allowed. definitions are allowed.

2. Default visibility mode public default visibility mode private

3. Inheritance not allowed inheritance is one of the main features of class

4. Only one visibility mode is available three types of visibility mode is available

(Public, private, and protected)

5. Overloading, polymorphism overloading, polymorphism can be used

cannot be used.

Introduction

C++ is an object oriented programming language.

Bjarne stroustrup at AT & T's Bell Lab

C++ is a combination of simula 67 and C.

Program features

Similar to C

Structure of C++ program

Page 9: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

It contains four sections.

1. Declaring header files

2. Class declaration.

3. Class functions definitions

4. Main function program

Operators in C++

1. Arithmetic operators

2. Unary operators

3. Relational and logical operators

4. Assignment operator

5. Conditional operator

In addition to this C++ introduces some new operators.

<< - insertion operator

>> - extraction operator

:: - scope resolution operator

::* - pointer to member

declaratory

->* - pointer to member operator

.* - pointer to member operator

new - memory allocation operator

delete - memory release operator

. - member operator

Input and output operator

Output operator

cout

Description

The operator << is called as insertion or put to operator. It inserts the contents of the

variable on its right to the object of its left.

Syntax:

cout<<variable 1<<variable 2<<....................<<variable n;

e.g.:

Page 10: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

cout<<"C++ is better than C";

cout<<a<<b;

Input operator

cin

Description

The operator >> is called as extraction or get from operator. It extracts the value from

the keyboard and assigns it to the variable on its right.

Syntax:

cin>>variable 1>>variable 2>>.................>>variable n;

e.g.:

cin>>a>>b;

Note

The multiple use of >> and << is called as cascading. The header file to be included

for this operator is <iostream.h>

Manipulators

These are special stream functions that change certain characteristics of the

input and output. These are operators that are used to format the data display.

All the manipulators functions prototypes are defined in the header file <iomanip.h>

1. endl

This is used to generate a carriage return or line feed character.

e.g.:

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

void main()

{

clrscr();

cout<<"Welcome to c++"<<endl;

cout<<"Thank you";

getch();

}

Page 11: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

2. setw ()

This is used to set the width of the output field.

Syntax:

setw(int width);

e.g.: man2.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

void main()

{

int a=10,b=20;

clrscr();

cout<<setw(5)<<a<<setw(5)<<b<<endl;

cout<<setw(10)<<a<<setw(10)<<b;

getch();

}

3. setfill()

This fills the given character in the unused field.

Syntax:

setfill(char)

e.g.: man3.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

void main()

{

int a=2,b=4;

clrscr();

cout<<setfill('*');

Page 12: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

cout<<setw(5)<<a<<setw(5)<<b<<endl;

cout<<setfill('$');

cout<<setw(7)<<a<<setw(7)<<b<<endl;

getch();

}

4. setprecision()

It controls the display of the number of digits after the decimal point for the floating

point number.

Syntax:

setprecision(int)

e.g.: man4.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

void main()

{

int a=10,b=3;

clrscr();

float c=(float)a/b;

cout<<setprecision(1)<<c<<endl;

cout<<setprecision(2)<<c<<endl;

cout<<setprecision(3)<<c;

getch();

}

Classes and Objects

Class

A class is a unit which combines both data and the functions that operates on the data.

These functions and dates are collectively called as members. The variables declared inside

the class are known as data members and the variables declared functions are called as

member functions.

Generally a class specification has been two parts.

Page 13: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

1. Class declaration

2. Class function definition

The class declaration describes its type and scope of its members.

The class function definitions describe how the class function is implemented.

Class declaration

Syntax:

class user defined name

{

access specifier:

member data;

member function;

};

There are three types of access specifier

1. Private

2. Public

3. Protected

1. Private

The members that have been declared as private can be accessed by the member

function and friend functions of this class. It is not accessible from the outside of the class.

2. Public

The members that have been declared as public can be accessed by any function in the

outside of the class.

3. Protected

These members can be accessed by the member functions and friend functions and

also by the member functions and friend functions derived form this class. It is not accessible

from the outside functions.

The keyword private, public, and protected is known as visibility labels.

e.g.:

class item

{

private:

int no;

Page 14: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

float cost;

public:

void getdata(int a, float b);

void putdata()

};

Defining the object of a class

Once a class has been declared, we can create variables of that type by using the class

name.

In C++, the class variables are known as objects. We may also declare more than one

object in one statement.

Syntax:

class name object name 1, object name 2,.......object name n;

e.g.:

class item x, y, z;

All the member object shares the same copy of the member functions but maintains a

separate copy of the member data.

Accessing class members

The class or member functions of a class are accessed using a dot operator.

Before a dot operator there must be a class object and after a dot operator there must

be a member function.

Syntax:

class object name. member function();

e.g.:

x.getdata ();

y.getdata ();

x.putdata ();

y.putdat ();

The objects cannot access the member data directly. The dates are accessed only by using the

member function.

Objects communicate by sending and receiving messages. This is achieved through

the member functions.

Member functions definitions

Page 15: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Member functions can be defined in two ways.

1. inside the class definitions

2. outside the class definitions.

1. Member function inside the class definition

When a function is defined inside the class it is treated as inline.

e.g.: classa1.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class sample

{

private:

int x,y;

public:

void getdata()

{

cout<<"Enter any two nos:"<<endl;

cin>>x>>y;

}

void putdata()

{

cout<<"Sum="<<sum()<<endl;

cout<<"Diff:"<<diff()<<endl;

cout<<"mul:"<<mul()<<endl;

cout<<"Div:"<<div()<<endl;

}

int sum()

{

return(x+y);

}

Page 16: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

int diff()

{

return(x-y);

}

int mul()

{

return(x*y);

}

int div()

{

return(x/y);

}

};

void main()

{

sample o;

clrscr();

o.getdata();

o.putdata();

o.sum();

o.diff();

o.mul();

o.div();

getch();

}

Member function outside the class definition

Member functions can be defined outside the class using scope resolution operator.

Syntax:

return type class name:: function name()

Page 17: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{

body of the function;

}

e.g.:

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class sample

{

private:

int x,y;

public:

void getdata();

void putdata();

int sum();

int diff();

int mul();

int div();

};

void sample::getdata()

{

cout<<"Enter any two nos:"<<endl;

cin>>x>>y;

}

void sample::putdata()

{

cout<<"Sum="<<sum()<<endl;

cout<<"Diff:"<<diff()<<endl;

cout<<"mul:"<<mul()<<endl;

cout<<"Div:"<<div()<<endl;

Page 18: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

}

int sample::sum()

{

return(x+y);

}

int sample::diff()

{

return(x-y);

}

int sample::mul()

{

return(x*y);

}

int sample::div()

{

return(x/y);

}

void main()

{

sample o;

clrscr();

o.getdata();

o.putdata();

o.sum();

o.diff();

o.mul();

o.div();

getch();

}

Making an outside function inline

Page 19: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

We can make a member function outside the class definition as inline by just adding

the keyword inline in the header line of the function definition.

Objects as arguments

An object may be used as a function argument. This can be done in two ways.

1. A copy of the entire object is passed to the function. (Call by value).

2. Only the address of the object is transferred to the function. (Call by reference).

In the first method a copy of the object is passed to the function, any changes made to

the object inside the function do not affect the object used to call the function.

When an address of the object is possessed, the called function works directly on the

actual object used in the call. This means that any changes made to the object inside the

function will reflect in the actual object. This method is efficient since it requires passing

only the address of the object and not the entire object.

e.g.: classa2.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class time

{

int hours,minutes;

public:

void gettime(int h,int m)

{

hours=h;

minutes=m;

}

void puttime()

{

cout<<hours<<"hours and";

cout<<minutes<<"minutes"<<endl;

}

void sum(time t1,time t2)

Page 20: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{

minutes=t1.minutes+t2.minutes;

hours=minutes/60;

minutes=minutes%60;

hours=hours+t1.hours+t2.hours;

}

};

void main()

{

time t1,t2,t3;

clrscr();

t1.gettime(2,45);

t2.gettime(3,30);

t3.sum(t1,t2);

cout<<"T1=";t1.puttime();

cout<<"T2=";t2.puttime();

cout<<"T3=";t3.puttime();

getch();

}

Array of class objects

Arrays can be used as member variables in a class.

Syntax:

class user defined name

{

member data’s;

member functions();

};

class user defined name object[max];

Where max is a user defined size of the array of the class object.

e.g.: classa3.cpp

Page 21: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class student

{

private:

int rollno,tm,pm,tot;

char name[20];

public:

void getdetail()

{

cout<<"Enter rollno:";

cin>>rollno;

cout<<"Enter name:";

cin>>name;

cout<<"Enter marks:";

cin>>tm>>pm;

}

void showdetail()

{

tot=tm+pm;

cout<<"Roll no:"<<rollno<<endl;

cout<<"Name:"<<name<<endl;

cout<<"Theory:"<<tm<<endl;

cout<<"Practical:"<<pm<<endl;

cout<<"Total:"<<tot<<endl;

}

};

void main()

{

Page 22: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

student obj[10];

int i,n;

clrscr();

cout<<"Enter how many students:";

cin>>n;

for(i=0;i<n;i++)

obj[i].getdetail();

for(i=0;i<n;i++)

obj[i].showdetail();

getch();

}

Static data members

A static member variable has certain special characteristics.

1. It is initialized to zero when the first object of its class it’s created. No other initialization

is permitted.

2. Only one copy of that member is created for the entire class and is shared by all the objects

of that class. No matter how many objects are created.

3. It is visible only within the class, but its lifetime is the entire program.

Uses

It is normally used to maintain value common to the entire class.

The type and scope of each static member variable must be defined outside the class

definition. This is necessary because it is stored separately rather than as a part of an object.

Since they are associated with the class itself rather than with any class object, they

are also known as class variables.

e.g.: classa4.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class item

{

private:

static int count;

Page 23: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

int number;

public:

void getdata(int a)

{

number=a;

count++;

}

void getcount()

{

cout<<"Count:";

cout<<count<<endl;

}

};

int item::count;

void main()

{

item a,b,c;

clrscr();

a.getcount();

b.getcount();

c.getcount();

a.getdata(100);

b.getdata(200);

c.getdata(300);

cout<<"After reading data "<<endl;

a.getcount();

b.getcount();

c.getcount();

getch();

}

Page 24: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Static Member Functions

A member function that is declared static has the following properties.

1. A static function can have access to only other static members (functions or variables)

declared in the same class.

2. A static member function can be called using the class name (instead of its objects) as

follows.

class name ::function name();

e.g.: classmf.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class test

{

private:

int code;

static int count;

public:

void setcode()

{

code=++count;

}

void showcode()

{

cout<<"Object no:"<<code<<endl;

}

static void showcount()

{

cout<<"Count:"<<count<<endl;

}

};

int test::count;

Page 25: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

void main()

{

test t1,t2;

clrscr();

t1.setcode();

t2.setcode();

test::showcount();

test t3;

t3.setcode();

test::showcount();

t1.showcode();

t2.showcode();

t3.showcode();

getch();

}

Nested classes

A class declared as a member of another class is called as nested class or a class

within another class.

Syntax:

class outer class name

{

private:

member datas of outer class

public:

class inner class name

{

private:

member datas of inner class

public:

member functions of inner class

};

Page 26: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

member functions of outer class

};

e.g.: classnes.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class emp

{

private:

int empno;

char name[20];

public:

class emp1

{

private:

float salary;

public:

void getsal()

{

cout<<"Enter salary:";

cin>>salary;

}

void putsal()

{

cout<<"Salary:"<<salary;

}

};

void getdetail()

{

cout<<"Enter emp no:";

Page 27: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

cin>>empno;

cout<<"Enter emp name:";

cin>>name;

}

void putdetail()

{

cout<<"Emp No:"<<empno<<endl;

cout<<"Name:"<<name<<endl;

}

};

void main()

{

emp e;

emp::emp1 e1;

clrscr();

e.getdetail();

e1.getsal();

e.putdetail();

e1.putsal();

getch();

}

Friend Function

We know that private data members cannot be accessed from outside the class. In

some situations we need to access private data members. In that case we can use friend

function.

A friend function is a nonmember function which has full access rights to the private

data members of the class and is declared with the keyword friend.

A friend function possesses certain special characteristics.

1. It is not in the scope of the class to which it has been declared as friend.

2. Since it is not in the scope of the class, it cannot be called using the object of that class. It

can be invoked like a normal function without the help of any object.

Page 28: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

3. Unlike member functions, it cannot access the member names directly and has to use an

object name and dot membership operator with each member name

e.g. A.x

4. It can be declared either in the public or the private part of a class without affecting its

meaning.

5. Usually, it has the objects as arguments.

The friend functions are often used in operator overloading.

Syntax:

friend return type function name( argument list);

e.g.: frifa.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class sample

{

private:

int a,b;

public:

void setvalue()

{

a=25;

b=40;

}

friend float mean(sample s);

};

float mean (sample s)

{

return(float(s.a+s.b)/2.0);

}

void main()

{

Page 29: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

sample s;

clrscr();

s.setvalue();

cout<<"Mean value="<<mean(s)<<endl;

getch();

}

Friend Classes

The private members of one class can be accessed from the member functions of

another class by make them as friends.

For e.g. consider two classes first and second. If the class first grants its friendship

with the other class, second then the private data members of the class first are permitted to

be accessed by the public members of the class second.

e.g.: frie.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class first

{

private:

int firstnum;

public:

friend class second;

first(int i)

{

firstnum=i;

}

};

class second

{

public:

void showdata(first f)

Page 30: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{

cout<<"The value is:"<<f.firstnum;

}

};

void main()

{

first f(10);

second s;

clrscr();

s.showdata(f);

getch();

}

Dynamic Memory allocation

C++ uses two unary operators new and delete to allocate and freeing the memory.

Since those operators manipulate memory on the free store, they are also known as freestore

operators.

New operator

New can be used to create a memory space for any data type including user defined

type such as arrays, structures, and classes.

Syntax:

data type pointer variable = new data type;

e.g.:

new int;

new sample;

new int[10];

Delete operator

This is used to destroy the memory space allocated by new.

Syntax:

delete pointer variable;

delete [size] pointer variable;

Page 31: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Advantages of new operator

1. It automatically computes the size of the data object. We need not use the operator sizeof.

2. It automatically returns the correct pointer type, so that there is no need to use a typecast.

3. It is possible to initialize the object while creating the memory space.

4. Like any other operator, new and delete can be overloaded.

e.g.: dyno1.cpp

#include<iostream.h>

#include<iomanip.h>

#include<conio.h>

void main()

{

int *ptr,i;

ptr=new int[5];

clrscr();

cout<<"Enter 5 integers:"<<endl;

for(i=0;i<5;i++)

cin>>ptr[i];

cout<<"The five integers are:"<<endl;

for(i=0;i<5;i++)

cout<<ptr[i]<<endl;

delete[] ptr;

getch();

}

Eg:dyno2.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class book

{

private:

Page 32: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

int bookno;

char bookname[10],author[10];

public:

void getdetail();

void showdetail();

};

void book::getdetail()

{

cout<<"Enter the bookno:"<<endl;

cin>>bookno;

cout<<"Enter the book name:"<<endl;

cin>>bookname;

cout<<"Enter the author name:"<<endl;

cin>>author;

}

void book::showdetail()

{

cout<<"Book no:"<<bookno<<endl;

cout<<"Book name:"<<bookname<<endl;

cout<<"Author:"<<author<<endl;

}

void main()

{

book b1,*b2;

b2=new book;

clrscr();

b1.getdetail();

b2->getdetail();

b1.showdetail();

b2->showdetail();

Page 33: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

getch();

}

This pointer

C++ uses a unique keyword called this to represent an object that invokes a member

function.’ this' is a pointer that points to the object for which " this " function was called.

"this" is used to access the address of the class itself and may return data items to the

caller.

e.g.; thispa.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class rectangle

{

private:

int length,breadth;

public:

void setdata(int l,int b)

{

this->length=l;

this->breadth=b;

}

void showdata()

{

cout<<"Length:"<<this->length<<endl;

cout<<"Breadth:"<<this->breadth<<endl;

}

};

void main()

{

rectangle r;

clrscr();

Page 34: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

r.setdata(10,20);

r.showdata();

getch();

}

Constructor

Constructor is a special member function which enables an object to initialize itself

when it is created. This is known as automatic initialization of object. It is called constructor

because it construct the values of data members of the class.

The constructor function has some special characteristics...

1. They should be declared in the public section.

2. They are activated automatically when the objects are created.

3. They do not have return types, not even void and therefore they cannot return values.

4. They cannot be inherited though a derived class can call the base class constructor.

5. Like other c++ functions, they can have default arguments.

6. Constructors cannot be virtual.

7. We cannot refer to their addresses.

8. An object with a constructor cannot be used as a member of a union.

9. They make implicit calls to the operators new and delete when memory allocation is

required.

Declaration

Syntax:

class user defined name

{

private:

members;

public:

user name();

protected:

members;

};

user name::user name()

Page 35: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{

body of the function;

}

The constructor name and class name must be same.

A constructor is invoked automatically under the following circumstances.

1. The constructor is called before main () starts for execution.

2. Whenever an object is created in any one of the following ways.

1. Global variable.

2. Local variable.

3. Static variable

3. An auto variable of class is defined within a block and the location of its definition is

reached.

4. A temporary instance of class is to be created.

5. during use of the dynamic memory allocation operator new.

Types of constructors

1. Default constructor

2. Parameterized constructor

3. Copy constructor

4. Overloaded constructor

1. Default constructor

A constructor that accepts no parameter is called as default constructors... It is a

special member function which is invoked automatically without any arguments for

initializing the objects of a class

Syntax:

class user defined name

{

private:

datas;

public:

methods( user name);

Page 36: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

protected:

datas;

};

user name:: user name()

{

body of the function;

}

e.g.: defcon.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class sample

{

private:

int a,b;

public:

sample()

{

a=10;

b=20;

}

void show()

{

cout<<"A="<<a<<endl<<"B="<<b;

}

};

void main()

{

sample s;

clrscr();

Page 37: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

s.show();

getch();

}

2. Parameterized constructor

The constructor that takes arguments is called as parameterized constructor.

Syntax:

class user defined name

{

private:

datas;

public:

user defined name( arg1, arg 2);

protected:

datas;

};

user defined name:: user defined name ( arg 1, arg2)

{

body of the function;

}

e.g.: paracon.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class sample

{

private:

int a,b;

public:

sample(int x,int y)

{

Page 38: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

a=x;

b=y;

}

void show()

{

cout<<"A="<<a<<endl<<"B="<<b;

}

};

void main()

{

sample s(20,30);

clrscr();

s.show();

getch();

}

3. Copy constructor

Constructor which takes a reference to an object of the same class as itself as an

argument is called as copy constructor.

It is always used when the compiler has to create a temporary object of a class object.

It is used in the following situations.

1. The initialization of an object by another object of the same class.

2. Return of an object as a function value.

3. Stating the object as by value parameters of a function.

Syntax:

class name::class name ( class name & ptr)

{

body of the function;

}

where

class name - user defined name

ptr - pointer to a class object.

Page 39: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

e.g.: copcon.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class fibonacci

{

private:

unsigned long int f0,f1,fib;

public:

fibonacci()

{

f0=0;

f1=1;

fib=f0+f1;

}

fibonacci(fibonacci &ptr)

{

f0=ptr.f0;

f1=ptr.f1;

fib=ptr.fib;

}

void increment()

{

f0=f1;

f1=fib;

fib=f0+f1;

}

void display()

{

cout<<fib<<"\t";

Page 40: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

}

};

void main()

{

fibonacci number;

int i;

clrscr();

for(i=0;i<=15;i++)

{

number.display();

number.increment();

}

getch();

}

4. over loaded constructor

Constructors can be overloaded by passing different no of arguments or different type

of arguments.

E.g. overcon.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class sample

{

private:

int a,b;

public:

sample()

{

a=10;

b=20;

Page 41: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

}

sample(int x,int y)

{

a=x;

b=y;

}

void show()

{

cout<<"A="<<a<<endl<<"B="<<b<<endl;

}

};

void main()

{

sample s,s1(30,40);

clrscr();

s.show();

s1.show();

getch();

}

Destructor

A destructor is a function that automatically executes when an object is destroyed. A

destructor function gets executed whenever an instance of the class to which it belongs goes

out of existence. The primary usage of destructor function is to release space on the heap. A

destructor may be invoked explicitly.

Syntax rules

1. A destructor function name is the same as that of the class it belongs except that the first

character of the name must be tilde (~).

2. It is declared with no return types.

3. It cannot be declared static, constant, or volatile.

4. It takes no argument and therefore cannot be overloaded.

5. It should have public access in the class declaration.

Syntax;

Page 42: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

class user defined name

{

private:

datas;

public:

user name();

~ user name();

protected:

datas;

};

It is invoked under the following circumstances.

1. after the end of the main for all static, local to main and global instances of class.

2. At the end of each block containing the auto variable of class.

3. At the end of each function containing an argument of class.

4. To destroy any unnamed temporaries of class after their use. When an instance of class

allocated on the is destroyed via delete.

eg:dest.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

#include<string.h>

class book

{

private:

int bookno;

char bname[20];

public:

book()

{

bookno=10;

strcpy(bname,"c++ courseware");

Page 43: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

}

~book()

{

strcpy(bname," ");

cout<<"Destructor invoked";

}

void showdetail()

{

cout<<"Book no:"<<bookno<<endl;

cout<<"Book name:"<<bname<<endl;

}

};

void main()

{

book b;

clrscr();

b.showdetail();

getch();

}

Inheritance

The mechanism of deriving a new class from an existing base class is known as inheritance...

The old class is referred to as base class and the new one is called as the derived class. The

derived class inherits same or all the properties from the base class. Inheritance supports the

concept of reusability.

There are five types of inheritance.

1. Single inheritance

2. Multiple inheritances

3. Multi level inheritance.

4. Hybrid inheritance

5. Heirarchical inheritance.

Page 44: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Defining derived class

Syntax:

class derived class name : visibility mode base class name

{

members of derived class;

};

e.g.: 1

class abc:public xyz

{

members of abc;

};

e.g. 2:

class abc:private xyz

{

members of abc;

};

Making a private member inheritable

Private member of a base class cannot be inherited and therefore it is not available for the

derived class. directly.

C++ provides a third visibility mode protected which serve a limited purpose in inheritance.

A member declared as protected is accessible by the member functions within its class and

any class immediately derived from it. It cannot be accessed by the functions outside these

two classes.

Visibility of inherited members

Base class Visibility Derived class visibility

Public derivation Private derivation

1. Private not inherited not inherited

2. Protected protected private

3. Public public private

Page 45: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

1. Single Inheritance

A derived class with only one base class is called single inheritance

A – Base class

B – Derived class

E.g.: Inherit1.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class emp

{

protected:

int eno;

char name[20];

public:

void getdetails()

{

cout<<"Enter eno:";

cin>>eno;

cout<<"Enter name:";

cin>>name;

}

void putdetails()

{

cout<<"Employee no:"<<eno<<endl;

cout<<"Employee name:"<<name<<endl;

}

};

class emp1:public emp

{

private:

Page 46: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

float salary;

public:

void getsal()

{

cout<<"Enter salary:";

cin>>salary;

}

void putsal()

{

cout<<"Basic salary:"<<salary;

}

};

void main()

{

emp1 e;

clrscr();

e.getdetails();

e.getsal();

e.putdetails();

e.putsal();

getch();

}

2. Multiple Inheritances

A multiple inheritance is a one which has two base classes and one derived class.

A & B – base class

C- Derived class

Eg:inherit2.cpp

#include<iostream.h>

#include<iomanip.h>

#include<conio.h>

Page 47: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

class M

{

protected:

int m;

public:

void getm(int x)

{

m=x;

}

};

class N

{

protected:

int n;

public:

void getn(int y)

{

n=y;

}

};

class P:public M,public N

{

public:

void display()

{

cout<<"M="<<m<<endl;

cout<<"N="<<n<<endl;

cout<<"m*n="<<m*n;

}

};

Page 48: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

void main()

{

P a;

clrscr();

a.getm(10);

a.getn(20);

a.display();

getch();

}

3.Multilevel

A multilevel inheritance is a one which has one base class and a derived class, and from that

derived class another derived class and so on.

(Derived Class of A)

(Derived Class of B)

(Derived Class of c)

e.g.: inherit3.cpp

#include<iostream.h>

#include<iomanip.h>

#include<conio.h>

class student

{

protected:

int rollno;

public:

void getno(int a)

{

rollno=a;

Page 49: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

}

void putno()

{

cout<<"Rollno"<<rollno<<endl;

}

};

class test: public student

{

protected:

float theory,practical;

public:

void getmarks(float x, float y)

{

theory=x;

practical=y;

}

void putmarks()

{

cout<<"Theory="<<theory<<endl;

cout<<"Practical="<<practical<<endl;

}

};

class result:public test

{

protected:

float total;

public:

void display()

{

total=theory+practical;

Page 50: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

putno();

putmarks();

cout<<"Total="<<total<<endl;

}

};

void main()

{

result s1;

clrscr();

s1.getno(10);

s1.getmarks(98.50,89.50);

s1.display();

getch();

}

4. Hybrid inheritance

It is a combination of multiple and multilevel inheritance.

EG:inherit4.cpp

#include<iostream.h>

#include<iomanip.h>

#include<conio.h>

class student

{

protected:

int rollno;

public:

void getno()

{

cout<<"Enter rollno:";

Page 51: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

cin>>rollno;

}

void putno()

{

cout<<"Rollno:"<<rollno<<endl;

}

};

class test: public student

{

protected:

float theory,practical;

public:

void getmarks()

{

cout<<"Enter theory marks:";

cin>>theory;

cout<<"Enter Practical Mark:";

cin>>practical;

}

void putmarks()

{

cout<<"Marks obtained:"<<endl;

cout<<"Theory="<<theory<<endl;

cout<<"Practical="<<practical<<endl;

}

};

class sports

{

protected:

float score;

Page 52: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

public:

void getscore()

{

cout<<"Enter sports mark:";

cin>>score;

}

void putscore()

{

cout<<"Sports mark:"<<score<<endl;

}

};

class result: public test, public sports

{

protected:

float total;

public:

void display()

{

total=theory+practical+score;

putno();

putmarks();

putscore();

cout<<"Total marks="<<total<<endl;

}

};

void main()

{

result s1;

clrscr();

s1.getno();

Page 53: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

s1.getmarks();

s1.getscore();

s1.display();

getch();

}

5. Hierarchical inheritance

A base class with several derived class is known as hierarchical inheritance.

E.g.: inherit5.cpp

#include<iostream.h>

#include<iomanip.h>

#include<conio.h>

class dept

{

private:

int dno;

char dname[10];

public:

void get()

{

cout<<"Enter dept no:";

cin>>dno;

cout<<"Enter dept name:";

cin>>dname;

}

void show()

{

cout<<"Dept number:"<<dno<<endl;

Page 54: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

cout<<"Dept Name:"<<dname<<endl;

}

};

class emp: public dept

{

private:

int eno;

char ename[10];

public:

void get()

{

dept ::get();

cout<<"Enter eno:";

cin>>eno;

cout<<"Enter ename:";

cin>>ename;

}

void show()

{

dept ::show();

cout<<"Eno:"<<eno<<endl;

cout<<"Ename:"<<ename<<endl;

}

};

class salary:public dept

{

private:

int bs;

public:

void get()

Page 55: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{

cout<<"Enter basic pay:"<<endl;

cin>>bs;

}

void put()

{

cout<<"Basic pay:"<<bs<<endl;

}

};

void main()

{

emp e;

salary s;

clrscr();

e.get();

e.show();

s.get();

s.put();

getch();

}

Virtual base class

The duplication of inherited members due to hybrid inheritance can be avoided by

making the common base class as virtual base class.

Syntax:

class A

{

members;

};

class B1:virtual public A

{

members;

Page 56: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

};

class B2:public virtual A

{

members;

};

class C:public B1,public B2

{

members;

};

Abstract class

An abstract class is one that is not used to create objects. An abstract class is

designed only to act as a base class.

Eg: Multiple inheritances

Polymorphism

It simply means one name multiple forms. There are two types of

polymorphism.

1. Compile time polymorphism

2. Run time polymorphism

1. Compile time polymorphism

It is also known as early binding or static binding or static linkage.

When a function is called through the object the C++ compiler determines which

function is used based on the parameters passed to the function or the function’s return type.

This happens during compilation time and this process is called as early binding.

E.g.;

Function overloading and operator overloading.

2. Runtime polymorphism

It is also known as late binding or dynamic binding.

Some time the type of the object does not known compilation time when the objects

are created dynamically at run time. In these cases the functions are binded with the objects

at runtime. This type of binding is called as late binding.

This is achieved by using virtual function.

Page 57: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Virtual function

Virtual function is used to achieve run time polymorphism. A virtual function is a

function that is declared as virtual in a base class and is redefined in the derived class. To

make a function as virtual, it should be preceded by the keyword “virtual.” A function is

declared as virtual because its execution depends on the context, which is not known at the

time of compilation.

Eg:poly1.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class baseA

{

public:

void display()

{

cout<<"Base class diplay function"<<endl;

}

};

class deriA:public baseA

{

public:

void display()

{

cout<<"Derived class display function"<<endl;

}

};

void main()

{

baseA b1;

baseA *b2;

b2=new deriA;

clrscr();

Page 58: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

b1.display();

b2->display();

getch();

}

e.g.: 2 Poly2.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class base

{

public:

void display()

{

cout<<"Display base"<<endl;

}

virtual void show()

{

cout<<"Show base"<<endl;

}

};

class derived:public base

{

public:

void display()

{

cout<<"Display derived"<<endl;

}

void show()

{

cout<<"Show derived"<<endl; } };

Page 59: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

void main()

{

base B;

derived D;

base *bptr;

clrscr();

bptr=&B;

bptr->display();

bptr->show();

bptr=&D;

bptr->display();

bptr->show();

getch();

}

Note

Run time polymorphism is achieved only when a virtual function is accessed through

a pointer to the base class.

Rules for virtual function

1. The virtual function must be member of some class.

2. They cannot be static members.

3. They are accessed by using object pointers.

4. A virtual function can be a friend of another class.

5. A virtual function in a base class must be defined, even though it may not be used.

6. The prototypes of the base class version of a virtual function and all the derived class

versions must be identical... If the two functions with the same name have different

prototype, c++ considers them as overloaded function, and the virtual function mechanisms is

ignored.

7. We cannot have virtual constructors, but we can have virtual destructors.

8. While a base pointer can point to any type of the derived class object, the reverse is not

true. That is, we cannot use a pointer to a derived class to access an object of the base type.

9. When a base pointer points to a derived class, incrementing or decrementing it will not

make it to point to the next object of the derived class. It is incremented or decremented only

Page 60: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

relative to its base type. Therefore we should not use this method to move the pointer to the

next object.

10. If a virtual function is defined in the base class, it need not be necessarily redefined in the

derived class. In such cases, calls will invoke the base function.

Pure virtual function

A pure virtual function is a function declared in a base class that has no

definition relative to the base class. Such functions are doing nothing functions.

A do- nothing functions may be defined as follows.

Virtual void display()=0;

A class containing pure virtual functions cannot be used to declare any objects of its

own. Such classes are called abstract base class.

Operator Overloading

Definition

The mechanism of giving special meanings to an operator is known as operator

overloading. We can overload all the c++ operators except the following.

. - dot operator

.* - pointer to member operator

:: - scope resolution operator

sizeof - size of operator

conditional operator

Defining operator overloading

Syntax:

return type class name::operaor op(argument list)

{

body of the function;

}

Where return type is the type of the value returned by the specified operations and op is the

operator being overloaded.

e.g.:

Rules for overloading operators

1. Only existing operators can be overloaded. New operators cannot be created.

2. The overloaded operator must have at least one operand that is of user defined type.

Page 61: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

3. We cannot change the basic meaning of an operator.

4. Overloaded operators follow the syntax rules of the original operators. That cannot be

overridden.

5. There are some operators that cannot be overloaded.

6. Operator function must be either friend function or member function. Unary operators,

overloaded by means of a member function, take no explicit arguments and return no explicit

values. But those overloaded by means of a friend function take one reference argument.

e.g.:

vector operator -(); //unary minus

friend vector operator - ( vector); // unary minus

7. Binary operator overloaded through a member function take one explicit argument and

those which are overloaded through a friend function take two explicit arguments.

E.g.:

vector operator +(vector); // addition

friend vector operator + ( vector, vector) ; // addition

vector operator - ( vector &a); //subtraction

int operator ==(vector); //comparison

friend int operator ==(vector, vector) // comparison.

8. When using binary operators overloaded through a member function, the left hand operand

must be an object of the relevant class.

9. Binary arithmetic operators such as +, -, *, and / must explicit return a value. They must

not attempt to change their own arguments.

10. We cannot use friend functions to overload certain operators. However member

functions can be used to overload them.

= - assignment operator

() - Function call operator

[ ] - subscripting operator.

-> - class member access operator

Process of overloading involves the following steps

1. First create a class that defined the data typo that is to be used in the overloading operation.

2. Declare the operator function operator op() in the public part of the class. It may be either a

member function or a friend function.

Page 62: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

3. Define the operator function to implement the required operations.

Overloading unary operator

E.g.: over1.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class space

{

private:

int x,y,z;

public:

void getdata(int a,int b,int c)

{

x=a;

y=b;

z=c;

}

void display()

{

cout<<x<<" "<<endl;

cout<<y<<" "<<endl;

cout<<z<<endl;

}

void operator -()

{

x=-x;

y=-y;

z=-z;

}

};

Page 63: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

void main()

{

space s;

clrscr();

s.getdata(10,-20,30);

cout<<"S:";

s.display();

-s;

cout<<"S:";

s.display();

getch();

}

Over loading binary operator

E.g.: over2.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

class complex

{

private:

float x,y;

public:

complex(){}

complex(float real,float imaginary)

{

x=real;

y=imaginary;

}

complex operator +(complex c)

{

Page 64: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

complex temp;

temp.x=x+c.x;

temp.y=y+c.y;

return(temp);

}

void display()

{

cout<<x<<"+j"<<y<<endl;

}

};

void main()

{

complex c1,c2,c3;

clrscr();

c1=complex(2.5,3.5);

c2=complex(1.6,2.7);

c3=c1+c2;

cout<<"C1=";c1.display();

cout<<"C2=";c2.display();

cout<<"C3=";c3.display();

getch();

}

Program for overloading == operator

E.g.: over3.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

#include<string.h>

class string

{

Page 65: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

private:

char str[10];

public:

void get()

{

cout<<"Enter the string:"<<endl;

cin>>str;

}

friend int operator ==(string s1,string s2)

{

if(strcmp(s1.str,s2.str)==0)

return 1;

else

return 0;

}

};

void main()

{

string s1,s2;

clrscr();

s1.get();

s2.get();

if(s1==s2)

cout<<"Both string are equal";

else

cout<<"Both string are not equal";

getch();

}

Files

In c++ to handle file I/O, special classes have already been defined in the header file

fstream.h.

Page 66: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

The following classes are used to handle file I/O operations

1. ifstream - used whenever the user wishes to read a file.

2. ofstream - used to write the data to the file.

3. fstream - both the read and write operation in the file.

1. open ()

This function is used to open a file

Syntax:

return type open( const char *fname, int file mode)

mode

Name Meaning

ios::in Input mode( default for input file)

ios::out Output mode(default for output file)

ios::app Append to an output file rather than

updating an existing record

ios::ate Position the file marker at the end of the

file

ios::trunc Delete the file if exists and recreate it

ios::nocreate open a file if the file does nort exist

ios::noreplace opens a file if a file does exist

ios::binary opens a file in binary mode . default mode is

text

egs:

1. ifstream in;

in.open("employee.dat");

or

ifstream in("employee.dat");

2.ofstream out;

out.open("employee.dat");

or

ofstream out("employee.dat");

3. fstream inout;

Page 67: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

inout.open("employee.dat");

or

fstream inout("employee.dat");

2. close()

This function is used to close a file.

egs:

1. in.close();

2. out.close();

Stream state member function

These functions give the information status like end of file has been reached or file

open failure and so on.

1. eof()

This function is used to check whether a file pointer has reached the end of the file

character or not. If it is successful the eof() returns a nonzero, otherwise returns 1.

e.g.;

while(!in.eof())

{

body of the function;

}

2. fail()

This is used to check whether a file has been opened for input or output successfully,

or any valid operations are attempted or there is an unrecoverable error. If it fails it returns a

nonzero character.

egs:

if(in.fail())

cout<<"File open error";

Reading and writing characters into the file

1. get()

It is used to read a single character from the file

syntax:

variable name= file object.get();

e.g.: fil1.cpp

Page 68: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#include<fstream.h>

void main()

{

ifstream infile;

char fname[10];

char ch;

clrscr();

cout<<"Enter the filename:";

cin>>fname;

infile.open(fname);

if(infile.fail())

{

cout<<"File does not exist:";

exit(1);

}

while(!infile.eof())

{

ch=infile.get();

cout<<ch;

}

infile.close();

getch();

}

2. put()

It is used to write a character to a specified file or specified area.

syntax:

file object.put(variable name);

Page 69: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

eg:fil2.cpp

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#include<fstream.h>

void main()

{

ofstream outfile;

ifstream infile;

char source[10],target[10];

char ch;

clrscr();

cout<<"Enter the source file name:";

cin>>source;

cout<<"Enter the target file name:";

cin>>target;

infile.open(source);

if(infile.fail())

{

cout<<"File does not exist";

exit(1);

}

outfile.open(target);

if(outfile.fail())

{

cout<<"File does not exist";

exit(1);

}

while(!infile.eof())

{

Page 70: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

ch=infile.get();

outfile.put(ch);

}

infile.close();

outfile.close();

getch();

}

3.get()

The get() member function is used to read only one character at a time. But it can be

used to read a complete string also.

syntax:

get(char * str, int length,char delimiter = '\n');

eg:fil3.cpp

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

#include<fstream.h>

#include<stdlib.h>

void main()

{

ifstream infile;

char fname[10],str[26];

clrscr();

cout<<"Enter file name:";

cin>>fname;

infile.open(fname);

if(infile.fail())

{

cout<<"File does not exist";

exit(1);

}

Page 71: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

while(!infile.eof())

{

infile.get(str,25);

cout<<str;

}

infile.close();

getch();

}

Object I/O to the files

1. write()

This function is used to write a stream of object into the file.

syntax:

object name.write((char *)&object,sizeof(object));

e.g.: fil4.cpp

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#include<fstream.h>

class item

{

private:

int itno,stock;

char itname[10];

float pprice,sprice;

public:

void get_item()

{

cout<<"Enter the item no:";

cin>>itno;

cout<<"Enter item name:";

Page 72: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

cin>>itname;

cout<<"Enter purchase price:";

cin>>pprice;

cout<<"Enter selling price:";

cin>>sprice;

cout<<"Enter current stock:";

cin>>stock;

}

};

void main()

{

fstream f;

item i;

char wish;

clrscr();

f.open("item.dat",ios::app);

do

{

i.get_item();

f.write((char *)&i,sizeof(i));

cout<<"Wish to add another item:";

cin>>wish;

}while(wish=='y');

f.close();

getch();

}

2. read()

This function read a stream of object from a specified file.

Page 73: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

syntax:

object name.read( char *)&object,sizeof(object));

eg:fil5.cpp

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#include<fstream.h>

#include<iomanip.h>

class item

{

private:

int itno,stock;

char itname[10];

float pprice,sprice;

public:

void show_item()

{

cout<<setw(5)<<itno;

cout<<setw(20)<<itname;

cout<<setw(10)<<pprice;

cout<<setw(10)<<sprice;

cout<<setw(5)<<stock<<endl;

}

void header()

{

cout<<"Item no Item name Pprice Sprice

Stock"<<endl;

}

};

void main()

{

Page 74: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

fstream f;

item i;

char wish;

i.header();

f.open("item.dat",ios::in);

f.read((char*)&i,sizeof(i));

while(!f.eof())

{

i.show_item();

f.read((char*)&i,sizeof(i));

}

f.close();

getch();

}

Positioning the file pointer

1. seekg()

used to position the file pointer.

syntax:

infile.seekg(long n,seek_direction)

values of seek_direction)

ios::beg from the beginning of the file

ios::cur from the current file poinetr position

ios::end from the end of the ifle

egs:

infile.seekg(50)

infile.seekg(50,ios::beg)

infile.seekg(0,ios::end)

infile.seekg(50,ios::cur)

2.seekp()

used to move the file pointer for the output operations.

Page 75: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

syntax:

outfile.seekp(long n,seek_direction)

3.tellg()

returns the current file pointer position.

syntax:

infile.tellg();

UNIT-4,5

Algorithm: Algorithm is the step by step solving some problem every single

procedure that the computer perform is an algorithm.

An algorithm is the process procedure final number of steps.

An algorithm is the wellordered collection of cleared and simple

instruction.

Computable operation that when executed procedures a result

and stacks some point find rather than just going on and on

infinitively.

Properties of algorithm:

Input

Output

Precision

Determinism

Findeness

Correctness

Generality

Input:

The algorithm resources input.

Output:

The algorithm produce output.

Page 76: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Precision:

The algorithm precises.

Determinism:

The intermediate result of each step of unique and are determine

only by the inputs and results of the preciden steps.

Findeness:

The algorithm determine that is stops after finitely many

instructions have been executed.

Correctness:

The output produce by the algorithm is very correct.

Generality:

The algorithm apply to a set of inputs.

A Traversal of algorithm:

VIEW-STACK()

GLOBAL STACK [STACK-SIZE];

TOP: INTEGER

I: INTEGER

Step 1: If(TOP==-1) Then print “stack is empty”

Return

[end of step 1 if]

Step 2: If (TOP== STACK –SIZE-1)

Then print “stack is full”

[end of step2 if]

Step 3: Print “The content of the stack”.

Step 4: Intialize I with 0.

Page 77: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Step 5: Do while(I<=TOP)

Print, STACK[I]

Increment 1 by 1

[end of step-5 while]

Step 6: Print “stack-size”: STACK-SIZE

Step 7: Print,” current stack element:”,TOP+1

END VIEW-STACK()

Binary search:

The binary search algorithm is one of the most efficient

searching techniques which requires the list of to be sorted in

ascending order.

BINARY RESEARCH (ARR,FIND,BEG,END) Where ARR is

an array in which element FIND is to be searched, BEG refers to

the initial index position of the list, END refers to the final

position of the list.

Step 1: if(BEG>END) Then RETURN-1

[end of if structure]

Step 2: Assign MID=(BEG+END)/2.

Step 3: if(FIND=ARR[MID] Then RETURN MID.

else if (FIND<ARR[MID])Then

RETURN BINARY-SEARCH(ARR,FIND,BEG,MID-1)

else

RETURN BINARY-SEARCH(ARR,FIND,MID+1,END)

[end of if]

END BINARY SEARCH.

Graph Traversal:

Page 78: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

A Graph traversal is the systemic way of visting nodes in a specific

order there are two types of graph traversal.

Breadth first universal:

BFS of a graph G starts from an universal vertex U then all

unvisited vertices. Vi adjacent to U are visited and Then all

unvisited vertices Wj adjacent to Vi are visited and so on the

traversal terminates when there are no more nodes to visit.

BFS uses as queue data structure to keep trap to order of nodes

whose adjacent nods are to be visited.

Steps:

Step 1: Choose any node in the graph designate it as the search node

and mark it as visited.

Step 2: Using the adjacent matrix of the graph find all the unvisited

node the search node and enqueue the in to the queue.

Step 3: Then the node is dequeue from the queue. Mark that node has

visited and designate it has the new search node.

Step 4: Repeat step 2 and step 3 using the queue a which keeps track

the adjacent node is empty.

Algorithm:

Void BFS(vertex U)

{ initialize queue Q;

Visited [U]=1;

Enqueue (U,Q);

While(! Is empty (Q))

{ U=Dequeue(Q);

Print U;

For all vertices V adjacent to U do

If(visited [V]==0) then

Page 79: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{ enqueue(V,Q)

Visited [V]=1;

}

}

};

A B C D

x 1 1 x

1 X 1 1

1 1 x 1

x 1 1 X

Application of BFS:

It is used to

check whether the graph is connected or not.

Depth first traversal:

It works by

selecting one vertex V of G. G has a start vertex V is marked

visited. Then each unvisited vertex adjacent to V is searched

in turn using DFS recursively.

Page 80: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

This process

continues until a dead end that is a vertex no adjacent

unvisited vertices is encountered.

At a dead end the

algorithm backup one edge to the vertex it from and tries to

continues visiting unvisited.

The algorithm

eventually halts after backing up to the starting vertex with

latter being a dead end. By then all the vertices in the same

connected component at the starting vertex have been visited.

If unvisited

vertices still remain the DFS must be restarted at any one of

them.

Steps:

Step 1: Choose any one in the graph designate it has the search node

and mark it as visited.

Step 2: Using the adjacent matrix of the graph find a node adjacent to

the search node that has not been visited designate this as the new

search node and mark it as visited.

Step 3: Repeat step 2 using the new search node if no node statisfying

step 2 can be found return to the previous search node and continue

from there.

Step 4: When a return to the previous search node in step 3 is

impossible the search from the originally choosen search node is

complete .

Step 5: If the graph still contains unvisited nodes choose any one node

that has not been visited and repeat step 1 through step 4 .

Structure:

Page 81: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Algorithm:

void DFS (vertex V)

{ visited [V]= true;

For each W adjacent to V

If (! Visited [W])

DFS [W];

}

dfs (adj ,start)

n=adj.last

for i=1 to n

visit [i]=false

dfs.recurs ( adj , start)

}

dfs-recurs (adj , start)

{ print (strat)

visit [start]=true

trav= adj [start]

while (trav !=null)

{ v=trav.ver

if (! Visit [V])

dfs.recurs (adj,V)

trav =trav.next

Page 82: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

}

}

Topological sort:

A topological

sort is a linear ordering of vertices in a directed acyclic graph

such that if there is a path from Vi to Vj then Vj appears after Vi

in the linear ordering.

Topological

ordering is not possible if the graph has a cycle since for two

vertices V and W on the cycle where V proceeds W and W

proceeds V.

Steps:

Step 1: find the indegree for every vertex.

Step 2: place the vertices whose indegree is 0 the empty queue.

Step 3: Dequeue the vertex V and decrement the indegree of all its

adjacent vertices.

Step 4: Enqueue the vertex on the queue of its indegree falls to 0.

Step 5: Repeat from step 3 until the queue becomes empty.

Step 6: The topological ordering is order in which the vertices are

dequeued.

Algorithm:

Void Topsort(Graph G)

{Queue Q;

int counter =0;

vertex V,W;

Q=create queue(Num,vertex);

Make empty(Q);

Page 83: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

For each vertex V

if (indegree[v]==0)

Enqueue(V,Q)

While(! Is empty(Q))

{

TOP NUM=++counter;

For each W adjacent to V

if(-- Indegree (W,Q));

if(counter!=Numvertex)

error(“graph has a cycle”);

Dispose queue(Q);

}

Sort:

It is a group or sequence of a elements or data items means

rearranging them in either ascending among the data items

present in the group.

The factors of sorting:

Programming time of the sorting technique.

Execution time of the sorting technique.

Number of comparisons required for the sorting list.

Main or auxiliary memory space needed for the sorting

technique.

The types of sorting:

Bubble sort

Insertion sort

Selection sort

Shell sort

Page 84: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Quick sort

Merge sort

Radix sort

Heap sort

Bubble sort:

The easiest and most widely used sorting technique among all

of the people is the bubble sort this sort is also referred as

sinking sort.

Algorithm:

Bubble (Arr,N)

When Arr is an array of N elements

Step 1: Repeat for i=0,1,2,…..N-1

Step 2: Repeat for j=i+1 to N-1

Step 3: if(Arr[i]>Arr[j] then Interchange Arr[i] and Arr[j]

End of if

Step 4: Increment 1 by 1

Step 5: end of step 2 for

Step 6: Print the sorted array Arr.

end Bubble()

Insertion sort:

The insertion sort can be easily understood if you know to

play cards imagine that you are rearranging cards after it have

been distributed before you in front of the table.

The main idea of the insertion sort is considered each element

at a time into the appropriate position relative to the sequence of

previously ordered elements such that the resulting sequence is

also ordered.

Page 85: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Insertion sort divides the array to be sorted in to two parts.

The first part consist of everything but the last element and the

second part is last element.

After sorting the first part insertion sort inserts the last element

in the correct position into the now sorted first part.

Algorithm:

Insert (Arr,N)

When Arr is an array of N elements

Step 1: Repeat for i=0,1,2…N-1

Step 2: Assign Temp =Arr[i]

Step 3: Repeat for j=i to 1

Step 4: if (Temp<Arr[j-1] then Arr[i]=Arr[j-1]

else

Go to step 1

End of if

Step 5: Decrement j by 1

Step 6: End of step 3 for

Step 7: Assign Arr[i]=temp

Step 8: End of step1 for

Step 9: Print the sorted array

End insert()

Merge sort:

The most common algorithm used in external sorting is merge

sort. This algorithm follows device and conquer statagy in

dividing face the problem is divided into smaller problem and

solved recursively.

Page 86: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

In conquering face the partient array is merged together

recursively merge sort is to apply to the first half and the second

half of the array this gives two sorted halfs which can then

recursively merged together using the merging algorithm.

Algorithm:

Void mergesort (int A[],int temp[],int n)

{ msort (A,temp,0,n-1);

} void msort (int A[],int temp();

int left, int right)

{ int center;

if (left<right)

{ center=(right+left)/2;

msort(A, temp, left, center);

msort(A, temp, center+1, right);

mergesort(A, temp, left, center+1, right);

Merge routine:

void merge (int A[], int temp[], int left, int center, int right)

{ int i, left end, tmp, num;

left end=center-1;

tmp=left; num=right-left+1;

while(left<=left end)&&(center<=right)

{ if(A[left]<=A[center])

{ temp[tmp]=a[left];

tmp+1; left++;

}

else

Page 87: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

{ temp[tmp]=A[center];

tmp++; center++;

} }

while(left<=left end)

{ temp[tmp]=A[left];

left++; tmp++;

}

while(center<=right)

{ temp[tmp]=A[center];

center++; tmp++;

}

for(i=0;i<=num;i++)

{ A[right]=temp[right];

right++;

} }

Quick sort:

Quick sort is the most efficient internal sorting technique it

possess a very good average case behavior among all the sorting

techniques it is also called as partioning sort which uses divide

and conquer techniques.

The quick sort works by portioning the array A[1],A[2]..A[n]

by portioning or by ticking some key value in the array as the

pivot element.

Pivot element is used to rearrange the element in the array.

Pivot element can be the first element of an array and reset of

the elements on left side of the pivot are lesser than the pivot

whereas those on right side are greater than the pivot.

Algorithm:

Page 88: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Void quick sot(int A[], int left, int right)

{

int i,j,pivot,temp;

if (left<right)

{

Pivot=left; j=right;

while (i<j)

{

while (A[pivot]>=A[i])

i=i+1;

while (A[pivot]<A[j])

j=j-1;

if (i<j)

{

temp=A[i]; A[i]=A[j];

A[j]=temp;

}

}

temp=A[pivot];

A[pivot]=A[j];

A[j]=temp;

qsort(A,left,j-1);

qsort(A,j+1,right);

}

}

Page 89: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Selection Sort:

The easiest method of sorting elements in the list is selection

sort. The main idea of selection sort is to search to the smallest

element in th list when the element is found it is swapped with

the first element in the list.

The second smallest element in the list is then searched.

When the element is found it is swapped with the second

element in the list.

Alogrithm:

Select

Select (Arr,N)

Where Arr is an array of N elements

Step 1: Repeat for I=1,2,3…N-1

Step 2: Assign k=I,MIN=Arr[I]

Step 3: Repeat for j=I+1 toN-1

Step 4: if (Arr[j]<MIN) then

MIN=Arr[j]

K=J

End of if.

Step 5: End of step 3 for

Step 6: Assign Arr[K]=Arr[I],Arr[I]=Min

Step 7: End of step 1 for

Step 8: print the sorted array Arr

Step 9: End select ()

Dijkstras Algorithm :

Page 90: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

The general method to solve the single source shortest path

problem is known as Dijkstras Algorithm. This is applied to the

weighted graph g.

This algorithm is the prime example for greedy technique

which generally solved problem in stages by doing what appears

to be the best thing at each stage the algorithm proceeds just like

the unweighted shortest path algorithm at each stage we selects

a vertex v which has the smallest d we among all the unknown

vertices and declares that has the shortest path from s to v and

mark it to be known.

We should said (dw=dv+cvw) if the new value for dw would

we an improvement structure.

Structure:

2

3 1 2

1

Algorithm:

Void Dijkstra (Graph G,Table T)

{

int i;

vertex v,w;

Read Graph (G,T)

for(i=0;i<=num vertex;i++)

{

T[i].known=false;

T[i].Dist=infinity;

Page 91: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

T[i].path=not a vertex;

}

T[start].dist=0;

for(; ;)

{

V=smallest unknown distance vertex;

if(v==not a vertex) break;

T[v].known=True;

for each W adjacent to V

if(!T[W].known)

{

T[W].dist=Min T[W].dist,T[V].dist+cvw)

T[W].path=v;

} } }

Kruskal’s Algorithm:

This algorithm is used to compute a minimum spanning tree

this algorithm selects the edges in the order of smallest weight

and accept an edge if it does not coils a cycle the algorithm

terminates if enough edges are accepted.

In general kruskal’s algorithm maintain a forest and collection

of trees initially there are |v| single node trees into one when the

algorithm terminates there is only one tree which is called as

minimum spanning tree.

This algorithm uses two data structure namely find and union.

Find(u) returns the root of the tree that contains the vertex u.

Union (s,u,v) merge the two trees by making the root pointer

of one node point to the root node of the other tree.

Structure:

Page 92: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

2

3 1 2

1

Undirected graph

Steps:

Step 1: Initially each vertex is in its own set.

Step 2: Now select the edge with minimum weight.

1

edge (a,d) is added to the minimum spanning tree.

Step 3: select the next edge with minimum weight and check whether

if it forms a cycle then the edge is rejected. Else add the edge to the

minimum spanning tree.

Page 93: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

1

1

(c,d) is the next minimum weighted edge.

Step 4: Repeat step3 all vertices are included is in the minimum

spanning tree.

2 2

1

1

The minimum spanning tree is 4 that is

cost(a,d)+cost(c,d)+cost(a,b)

Edge Weight Action

(a,d) 1 Accepted

(c,d) 1

(a,d) 1

Since all vertices are added the algorithm terminates.

FIND:

settype FIND (vertex V, disjoint set S)

{

if(S[0]<=0)

Page 94: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

return U

else

return find(S[U],S)

}

UNION:

void set union (disjoint set S,settype U set, settype V set)

{ S[V set]=U set;

}

Algorithm:

void kruskal (Graph G)

{ int edges accepted =0;

Disjoint set S;

Heap H;

Vertex U,V;

Settype U set, V set

Edge E;

Initialize(S);

Build Heap(H);

while(edges accepted < Numvertex-1)

{

E=delete min(H);

U set=Find(U,S);

V set=Find(V,S);

if(U set!=V set)

{

Page 95: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

edge accepted ++;

set union(S,U set, V set);

} }

}

Prim’s Algorithm:

This algorithm is one of the way to compute a minimum

spanning tree which uses the critic technique.

This algorithm begins with the set U initialize to U={1}.

If the grows a spanning tree one edge at a time.

At each steps at a finds a shortest edge (U,V) such that the

cost of (U,V) if the smallest among all edges where U is in the

minimum spanning tree and V is not in minimum spanning tree.

Algorithm:

void prim (Graph G)

{

MSTTREE T;

vertex U,V;

set of vertices V;

set of tree vertices U;

T=NULL;

U={1};

while (u≠v)

{

Let (u,v) be a lowest cost such that u is in U and V is in V-U;

T=TU{(U,V)};

T=U U{V};

Page 96: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Continue stage:

void prims (Table T)

{ vertex V,W;

for(i=0;i<Num vertex;i++)

{

T[i].known=false;

T[i].Dist=infinity;

T[i].path= 0;

}

for(; ;)

{ let V be the start vertex with the smallest distance

T[V].dist= 0;

T[V].known=True;

for each W adjacent to V

if(!T[W].known)

{

T[W].dist=Min (T[W].dist Cvw);

T[W].path=v;

} } }

Huffman’s nodes:

Huffman algorithm works by selecting two characters having

the lowest probabilities and replacing them with the single

character whose probability is the sum of probability of the two

characters.

Using this procedure recursively optimal prefix code of the set

of characters are found.

Page 97: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

The weight of the tree is equal to sum of the frequencies of its

leaves.

Steps:

Steps to construct Huffman tree.

Step 1: Initially create single node tree for each character.

Step 2: Select the two trees T1 and t2 o f smallest weight.

Step 3: Form a new tree with subtrees T1 and T2 with T1 as left child

and T2 as right child.

Step 4: The weight of the new tree is calculated as the sum of the

weights of T1 and T2.

Step 5: Repeat the steps recursively until a single tree is form.

Algorithm:

while there is more than one tree in the forest do begin

{ begin

i= index of the tree in forest with smallest height.

j= index of the tree in forest with second smallest height.

create a new node with left child forest[i].root and right child forest

[j].root

Repeat tree i in forest by a tree whose root is the new node and

whose weight is forest[i].weight+forest[j].weight;

Delete tree j from the forest.

end ;

Eg: 121+61+38+23+10=253

Page 98: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Knapsack:

The input to the algorithm is that knapsack capacity c and an

array a of size n.

Each of whose entries specify an id and a profit p and a weight

w.

The output tells how much of each object to select maximize

profit.

Objects not selected do not appear in the output.

The function sorts, sorts the array in non – increasing order of

the ratio of profit to weight.

Algorithm:

Input parameters: a,c

Output parameters: none

Continuous – knapsack (a,c)

{

n=a.last;

for i=1 to n

ratio[i]= a[i].pla[i].w

sort(a,ratio);

Page 99: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

weight=0;

i=1;

while(i<=n && weight<c)

{

if(weight+a[i].w<=c)

{

print (“select all of object”+a[i].id)

weight=c;

}

i=i+1;

}

}

Draft:

Draft report has five chapters, the following table shows the

length of the chapters and their importance where the scale is

one that is low to ten high.

Chapter Pages Importance

1 120 5

2 150 5

3 200 4

4 150 8

5 140 3

The problem is edit the report so that the overall importance is

maximize the draft report the number of pages in each chapter

and the importance of each chapter.

Dynamic programming:

Page 100: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Computing fibbonacci number:

I. That the fibbonacci num sequence f1,f2…..fn is defined by the

reference relation that is fn=fn-1+fn-2…n>=3

II. An initial condition

f1=f2=1

III. Dynamic programming algorithm to compute fn begins by

computing the simplest problem first namely f1 and f2

If then uses equation one, two compute f3…fn in this order.

After each f1 is computed it is stored in an array and when

value is needed later it is obtained from the array.

Algorithm:

This dynamic programming algorithm it uses the following

formulas.

f1=1

f2=2

fn=f(n-1)+f(n-2) where n>=3 at the conclusion of the

algorithm the [f] holds the first number fibbonacci number.

Input parameters: n

Output parameters: none

fibbonacci(n)

{

f[1]=1

f[2]=1

for i=3 to n

f[i]= f[i-1]+f[i-2]

return f[n]

}

Page 101: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Coin changing:

This dynamic programming algorithm computes the minimum

no.of coins to make change for a given amount the input is an

array denomination that’s specifies the denomination of the

coins.

denom [1]>denom [2]>…> denom [n]=1 and an amount a the

output is an [c] whose value is c[i][j] is the minimum no.of

coins to make the change for the amount j using coins i through

n.

1≤i≤n, 0≤j≤A.

This algorithms make change for an amount a using coins of

denomination.

Algorithm:

Input parameters: denom A

Output parameters: none

Greedy coin change (denom,A)

{

i=1;

while (A>0)

{

c= Al denom [i];

print(“use”+c+” coins of denomination”+denom [i]);

A= A-c* denom [i];

i=i+1;

}

}

Matrix multiplication:

Page 102: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

This algorithm computes the minimum no of scalar

multiplications to multiply a sequence of n matrices.

The input is the array size that contains sizes of the matrices to

be multiplied.

The first matrix is size of 0 in to size of the second is size of 1

into size of 2 and so on the nth matrix is size of n-1 into size of

n the ouput is the array s whose value is s[i][j] is the minimum

number of scalar multiplication to multiply matrices i through j.

The value infinity is the largest available integer

value.

Algorithm:

Input parameters: size

Output parameters: s

opt matrix- multi (size)

{

n= size last;

for i=1 to n

s[i][j]=0;

for w=1 to n-1

for i=1 to n-w

{

j= w+i;

s[i][j]= ∞;

for k=i to j-1

{

q=s[i][k]+s[k+1][j]+size[i-1]*size[k]*size[j];

if(q<s[i][j])

Page 103: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

s[i][j]=q;

} }

}

Floyd’s Algorithm:

This algorithm computes the length of a shortest path between

each pair of vertices in a simple, undirected weighted graph g.

All weights are non-negative.

The input is the adjacent c matrix a of g the output is the

matrix a whose i, jth entry is the length of a shortest path from

vertex i to vertex j.

Algorithm:

Input parameters;

Output parameters:

all – path(A)

{ n=A.last;

for k=1 to n

for i=1 to n

for j=1 to n

if (A[i][k]+A[k][j]<A[i][j])

A[i][j]= A[i][k]+A[k][i];

}

Warshell’s Algorithm:

This algorithm computes the transitive closer of a relation are

on {1….. n}

The input of the matrix a of r.

The output is the matrix is a of the transitive closive of r.

Page 104: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

The transitive closure of a diagraph of is the matrix that gives

the information about the existence of directed paths between

vertices of a given graph.

Algorithm:

Input parameters: A

Output parameters: A

Transitive - closure(A)

{ n=A.last;

for k=1 to n

for i=1 to n

for j=1 to n

A[i][j]=A[i][j]* (A[i][k]+A[k][i]);

}

Closest pair coins:

This algorithm finds the distance between a closest pair of

coins.

The input is an array p(1)…p(n) of n>=2 points if *p is the

point p.x is the x co-ordinates of p the function merge is uses as

the key the y co-ordinate of the point.

The function merge sort uses as the key either the x or y co-

ordinate the function distance p,q return eucliten distance

between p and q.

Algorithm:

Input parameters: p

Output parameters: none

Closest pair(p)

{ n=p.last

Page 105: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

mergesort (p,l,n);

}

rec-cl-pair (p,i,j)

{

if (j-1<3)

{

mergesort (p,i,j);

delta=dist (p[i],p[i+1]);

if (j-1==1)

return delta

if (dist (p[i+1],p[i+2]<delta)

delta=dist (p[i+1],p[i+2])

if (dist (p[i],p[i+2]<delta)

delta=dist (p[1],p[i+2]);

return delta

}

k=(i+j)/2;

l=p[k]-x;

delta L= rec-cl-pair (p,i,k);

delta R= rec-cl-pair (p,k+1,j);

Strassen’s matrix product algorithm:

It is divide and conquer approach to compute the matrix

product.

If A is a matrix we let Aij denote the entry in row i and

column as j.

Page 106: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Recall that the matrix product of A and B where A is an (m*p)

and B is an (p*n) matrix is defined as the (m*n) matrix then c

will be defined as

p

Cij=∑ Aik Bkj , 1≤i≤m

K=1 1≤j≤n

Matrix multiplication is the fundamental operation on matrices

and is used in many different contests.

Ak= A….A….A

KA’s.

Algorithm:

Input parameters: A,B

Output parameters: C

Matrix pro (A,B,C)

{ n=A.last;

for i=1 to n

for j=1 to n

{

C[i][j]=0;

for k=1 to n

C[i][j]=C[i][j]+A[i][k]*B[k][i]

}

}

Consider a divide and conquer appoarch to computing the

matrix product where the input is A and B and two (n*n)

Page 107: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

matrices where n is the power of 2. If n>1 we divide each of A

and B into 4 that is (n/2*n/2) matrices.

Eg:

A = a11 a12 B= b11 b12

a21 a22 b21 b22

a11 b11+a11 b12 a12 b11+a12 b12

a21 b21+a21 b22 a22 b21+a22 b22

Each of the term aik bkj is itself a matrix product and is

computed recursively unless aik bkj are (1*1).

Let Cn denote the number of multiplication and additions

required by an algorithm compute the product two of (n*n)

matrices computing the products of the 8(n/2*n/2) sum matrices

requires 8Cn/2 additions and multiplications and combining the

requires 4(n/2)2=n2 thus we obtain the recurrence relation that

is

Cn=8Cn/2+n2.

Strassen showed now to compute the expression using only 7

matrix products and 0(n2) additions and subtractions to

combine them the recurrence relations as follows.

Cn=7Cn/2+f(n)

Where fn is 0(n2) therefore the strassen matrix computes the

quantities as follows.

q1= (a11+a12)*(b11+b22)

q2= (a21+a22)*b11

q3= a11*(b12-b22)

q4= a22*(b21-b11)

q5= (a11+a12)*b22

q6= (a21-a11)*(b11+b12)

Page 108: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

q7= (a12-a22)*(b21+b22)

AB= q1+q4-q5+q7 q3+q5

q2+q4 q7+q3-q2q6

Backtracking:

Backtracking is a technique used to solve problems with a

large search space by systematically trying and eliminating

possibilities.

A standard example of backtracking would be going through a

maze.

One strategy would be to try going through portion A of the

maze.

If you get stuck before you find your way out, then you

“backtrack” to the junction.

At this point is time you know that portion A will not lead you

out of the maze

So you then start searching is portion B.

Clearly at a single junction you could have even more than 2

choices.

The backtrackingstrategy says to try each choice, one after the

other.

If you ever get stuck, “backtrack” to the junction and try the

next choice.

If you try all choices and never found a way out, then there is

no solution to the maze.

Backtracking – eight queens problem:

Find an arrangement of 8 queens a single chess board such

that no two queens are attacking one another.

In chess, queens can move all the way down any row column

or diagonal (so long as no pieces are in the way)

Due to the first two restrictions, it’s clear that each row and

column of the board will have exactly one queen.

Page 109: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Algorithm:

void solve it rec (int perm[],int location, struct one square used list[])

{

if (location==SIZE)

{

print sol (perm);

{

for (int i=0;i<SIZE;i++)

{

if(used list[i]==false)

{

if(!conflict(perm,location,i))

{

perm[location]=i;

used list[i]=true;

solve it rec (perm, location+1, used list);

used list[i]=false;

} } }

}

Perm[] – stores a valid permulation of queens from index 0 to

location-1

Location[] – the column we are placing the next queen.

Used list[] – keeps track of the rows in which the queens have

already been placed.

Found a solution to the problem, so print it.

Loop through possible rows to place this queen.

Only try this row if it hasn’t been used.

Page 110: PROGRAMMING IN C++ and ALGORITHMS SUBJECT CODE : …apsacollege.com/wp-content/uploads/2014/09/CPP_4BIT3C1.pdf8. Follow bottom up approach in program design. Characteristics of oops

Check if this position conflicts with any previous queens on

the diagonal.

1. Mark the queen in this row.

2. Mark the rows are used.

3. Solve the next column location recursively.

4. Un – mark the row as used. So we can get all possible valid

solutions.