0% found this document useful (0 votes)
504 views103 pages

Object-Oriented Programming in C++

this is abeautiful presentation of dbms for 12th class this will gelp you to attain good ranking in exam as well as perform well in the upcomming exams thank you. have a nice night brother
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
504 views103 pages

Object-Oriented Programming in C++

this is abeautiful presentation of dbms for 12th class this will gelp you to attain good ranking in exam as well as perform well in the upcomming exams thank you. have a nice night brother
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15

Object-Oriented Programming in C++


Programming Paradigms
Paradigm means a way of thinking. A programming paradigm is style or discipline of programming.
A paradigm is the organizing principle of program. It is an approach to programming.
Procedural Programming:
Conventional programming using high level languages such as COBOL, FORTAN and C is commonly known
as Procedure-oriented programming. In this type of programming, the problem is solved as a sequence of steps
to be done, such as reading, calculating and printing. A number of functions are written to do these tasks .The
primary focus is on functions. A typical structure for procedure programming is shown as

Procedure-oriented programming basically consists of writing a list of instructions for the computer to follow,
and organizing these instructions for the computer to follow, and organizing these instructions into groups
known as functions.
In multi-function program, many important data items are placed as global as that they may be
accessed by all the functions. Each function may have its own local data. Above figure shows the relationship of
data and functions in a procedure-oriented program
Global data area more prone to an inadvertent change by a function. In large program it is very
difficult to identify what data is used by which function. This is one of the drawbacks of Procedure oriented
programming. Another drawback is that it does not model real world problem very well. This is because
functions are action oriented and do not really corresponding to the elements of the problem.
Characteristics of Procedure –Oriented Programming:
1. Emphases on non-living and non-real items i.e. have algorithmic approach (sequence of steps).
2. Large program are divided into smaller programs known as functions.
3. Most of the function share global data.
4. Data move openly around the system from function to function i.e. there is no control on data.
5. Function transforms data from form to another.
6. Employ top-down approach in program design.
Exemple: PASCAL,COBOL,C,FORTRAN etc.
Object Oriented Programming:
The major motivating factor in the invention of object-oriented approach is to remove the drawbacks of
procedure approach.OOP treats data as critical element in the program development and does not allow it to
flow freely around the system. It ties data more closely to the functions that operate on it and protects it from
accidental modification from outside functions. OOP allows us to decompose a problem into a number of
entities called objects and then builds data and function around these entities.
“Object-oriented is an approach that provides a way of modularizing programs by creating partitioned
memory area for both data and functions that can be used as templates for creating copies of such modules on
demand. “

IT Brainshapers 1 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
The organization of data and functions in object-oriented programming is shown in following figure .The data
of an object can be accessed only by the functions associated with that object. However functions of one object
Object B
can access the functions of other functions of other objects.
Features of Object –Oriented Programming are :
1. Emphases on real world i.e. data and object rather than procedure.
2. Program is divided into what are known as objects.
3. Data structure are designed such that they characterize the objects.
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 the external functions
6. Objects may communicate with each other through functions.
7. Employ bottom-up approach in program design.
Example: Java ,C++, VB.NET,C#.NET etc
Difference between Procedural Oriented and OOPs is as
SNo Procedural Oriented Programming Object Oriented Programming
1 Emphases on non-living and non-real items i.e. Emphases on real world i.e. data and object rather
have algorithmic approach (sequence of steps). than procedure
2 It uses function programming and modular It uses object approach. Here large programs are
approach. Here large programs are divided divided intro smaller modules (called objects)
into smaller programs(called function)
3. Here most of the function share global data Here every object can share global as well as local
data.
4 Data is in shareable mode and also can be Data is non shareable mode and also hidden Data
moved from one function to another function cannot be accessed by external functions.
i.e. any external function can access the data
5 It uses top-down approach in Program design It uses bottom-up approach in Program design
6 Function communicate by transform data from Objects communicate with each other through
one form to another function.
7 It have high level language like C, Fortran It have high Object Oriented language like C++,
,Basic ,Pascal etc. Java, VB.NET,C# etc.
struct student{ class student
int rollno; {
char name[25]; private: int rollno;
} } char name[25];
void main( ) public: void readdata( )
{ {
student s1; cout<<”Enter rollno”;cin>>rollno;
cout<<”Enter rollno”; cout<<”Enter name”;cin>>name;}
cin>>s1.rollno; }
cout<<”\nEnter name” void displaydata( )
cin<s1.name; {
cout<<” Rollno”<<s1.rollno; cout<< ” Rollno:”<<rollno;
cout<<”\n Name”<<s1.name; cout<<”\n Name”<<name;
} }
};
void main( )
{
student s1 //object is created
s1.readdata( );
s1.displaydata( );
}

IT Brainshapers 2 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Basic Elements or Characteristics of Object Oriented Programming
(OPPs):--
The characteristics of an Object Oriented Programming are:-
1) Object :-
“Object is an identifiable entity with some characteristics and behavior”.
It can be item, place or person or any other entity or activity.
An object has state exhibits some well defined behaviour and has a
unique identity
e.g. We can say “Orange is an object..
Identity – Orange i.e. name
State (Characteristics) – Spherical shaped, Color is orange
Behavior- Juicy, Tastes sweet sour
All objects have the following characteristics;-
Identity
Identity is that property of an object which distinguishes it from all
other objects. Normally object is identified by its name.
State :
The state of an object refers to the properties of an object which are usually static in nature plus their
value e.g Tube light is an object and its length, diameter, company and their values at some instant form some
state..
An object can be in many states i.e. TV can be in the following states:-
a) On State ii) Off State iii) Out of Order State.
Behavior :-
Behavior is how object act and react e.g. person can sit, stand, sleep, walk.
In Object programming, the characteristics of an object are represented
by its data and its behavior is represented by its functions associated.
Therefore in object programming. Object represent an entity that can store
data has its interface through functions.
Class:
A class is group of objects that share common properties and relationships.
Thus Class is collection of objects of similar type.
Car have been identified as object. They have characteristics like steering,
wheel, seat and their behaviour is their mobility. Car, however is not an
object it is class (compare with the definition)
„Opel‟, ‟Astra‟ is an object belongs to the class „Car‟. Car is subclass of
another class „automobile „ which again a subclass of vehicles.
Object is an instance of class e.g. we can say „bird‟ is class but „parrot‟ is object
Fruit is a class but orange, mango are objects
Fruit mango // Will create an object mango belonging to the class fruit.

We can create any number of objects belonging to that class


class-name obj1,obj2…..objn;
Here obj1,obj2…….objn are objects of similar class
Employee Principal Teacher Clerk
Class Object
IT Brainshapers 3 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Data Hiding
Data Hiding is a software development technique specifically used in object
oriented programming (OPP) to hide internal object details i.e. data members
.Data hiding ensures exclusive data access to class members and protect object
integrity by preventing unintended or intended changes.
The insulation of data from Direct access or Accidental Access is known as
Data Hiding.
The main difference between data hiding and encapsulation is that data
hiding focus more on data security and encapsulation focuses more on hiding
the complexity of the system

Encapsulation
Encapsulation is an Object oriented programming base concept.
Encapsulation means protect important data inside the class which we do
not want to exposed outside the class. Encapsulation process means
binding data members (variable, properties) and member function
(Methods). It consist of separating the external aspects of an object from
the internal implementation details of the object which are hidden from
other objects i.e. data is not accessible to the outside world and only those function which are wrapped in the
class can access it .In other words the wrapping up of data and functions into a single unit (called Class) is
called Encapsulation. It prevents a program from becoming so interdependent that a small change has massive
ripple effects. Encapsulation is not unique to OOPs .It has a good ability to combine data structure and
behaviors in a single entity .e.g. in an organization different departments access and work with their data on
their own .One department cannot access data of another department directly .They can share their information
only when a special request is made for a required data and the data is handed over by the member of the
requested department
Data Abstraction:
Abstraction means displaying only essential information and hiding the details or
explanation. Data abstraction refers to providing only essential information about
the data to the outside world ,hiding the background details or implementation It
focuses on the outer view of object. Abstraction is the selective examination of
certain aspects of a problem. The goal of abstraction is to isolate those aspects
that are important for some purpose and suppose those aspects that are
unimportant.
To understand abstraction let us take an example we are driving a car. We only know the essential features to
drive a car e.g. a gear handling, steering handling, use of clutch, accelerator brakes etc. but while driving do we
get details of car like wiring, motor working etc ? We just change the gears or apply the brakes etc. What is

IT Brainshapers 4 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
happening inside is hidden from us. This is abstraction, where we only know the essential things to drive car
without including the background details or explanations.
We can implement Abstraction in C++ using classes. Classes help us to group data members and
member function using a vaible access specifier. A class can decide
which data member will be visible to outside world and which is not

Polymorphism:
Polymorphism is key to the object oriented programming. It is most important that languages that don‟t support
polymorphism cannot advertises themselves as OO languages .Language that support classes but not
polymorphism are called object based language .Ada is such a language .
Polymorphism is the ability for a message or data to be processed in
more than one form. Polymorphism is the concept that supports the
capability of an object of a class to behave differently in response to a
message or action. e.g. „Human‟ is a subclass of Mammal. Similarly Dog,
Cat are also subclasses of Mammal .Mammals can see through day-light.
So if a message „see through daylight is passed to all mammals, they all will behave alike .Now if a message
„see through darkness is passed to all mammals, then human and dogs will not be able to view at night whereas
cats will be able to view during the night also. Here cats (mammals can behave differently than other mammals
in response to a message or action. This is Polymorphism.
Polymorphism is a property by which the same message can be sent to
objects of several differently classes and each object can respond in a
different way depending on its class.
The following figure shows that a single function name can be used to
handle different member and different types of arguments. This is
something similar to a particular word having several different meaning depending on the context.
Inheritance Concept
Base Class
The technique of deriving a new class from an existing class is called inheritance. A
class that is inherited is referred to as a base (super) class. The class that does the inheriting
is called the derived (sub) class. Further a, derived class can be used as a base class
Derived Class
for another derived class. The derived class inherits some or all the properties of the
base class. The relationship between base and derived class is known as inheritance Inheritance
hierarchy.

IT Brainshapers 5 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
e.g motorcycle is class in itself. It is also member of two
wheelers class. Two wheelers class in turn is a member of an
automotive class. Thus, the automotive is an example of a
base class and two wheelers is its derived class. In simple
words, we can say that a motor cycle is two wheeler
automotive
In C++, a derived class can be obtained by adding some new
data structure and functions to a base class. The derived class
inherits the members of its base class without the need to
redefine them.
Need for Inheritance
Inheritance is a splendid concept of object-oriented language. There is several reasons why inheritance was
introduced into OO language. Some are
1. Using inheritance, classes/objects in C++ can behave much like real world objects.
2. It is required for extending the functionality of an existing class.
3. It can be used to establish “a kind of ” relationship.
4. It helps in reuse of an existing class by a derived class.
The redundancy among classes can be reduced by abstracting a super class out of them. This property is known
as generalization
Modularity
The act of partitioning a program into individual components is called modularity. The reason for partitioning a
program is that
i it reduces its complexity to some degree and
ii it creates a number of well –defined ,documented boundaries within the program.
A MODULE is a separate init itself .It can be complied separately though it has connections with other
modules.
Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled
modules
e.g. you must have seen as complete music system. The music system comprises of speakers, cassette player,
record player, cd player, tuner etc. Now these parts are complete units in themselves, yet they are sub part of
music system. This is modularity.
In object oriented languages, classes and objects form the logical structure of a system. We place them in
modules to produce the system‟s physical architecture .For example; modularity in C++ is implemented through
separately complied files. The traditional practice in the C+ community is to place module interface in files
named with a .h suffix; these are called header files.
Message Passing
In OPPs, the objects communicate with one another by sending and receiving the information. A message for an
object is request for execution of procedure, and therefore will invoke a procedure in the receiving object that
generates the result. Message passing involves specifying the name of the object, the name of the function and
the information to be sent. Three basic steps involved in message communication in OOP are
Creating classes and defines objects
Creating objects from class definition
Establishing communication among objects
IT Brainshapers 6 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Mainly in
C++ binding are of two types, one is early binding or static binding and second one is Dynamic binding
.Dynamic binding is also called late binding. It refers to run-time determination of the addresses of the function
to be executed in the program .i.e. the code associated with a given procedure call is not known until the tile of
the call at run time .It is associated with polymorphism or inheritance
Advantages of OOP
OOP offers several benefits to both the program designer and the user. The principal advantages are:-
1. It is possible to have multiple instances of an object to co-exist without any interference.
2. It is easy to partition the work in a project based on objects.
3. Message passing techniques for communication between objects makes the interface descriptions with external
system much simpler.
4. The principals of data hiding helps the programmer to build secure programs that cannot be invaded by code in
other parts of the program
5. Through inheritance ,we can eliminate redundant code and extend the use of existing class
6. Software complexity can be easily be managed.
7. Object oriented system can be easily be upgraded from small to large systems.
Disadvantages of OOP
Although OOP has proved revolutionary in software development yet it has some disadvantages too .These are:
1. With OOP, classes tend to be overly generalized.
2. The relations among classes become artificial at times.
3. The OOP program‟s design is tricky.
4. Also one needs to be proper planning and proper design for OOP programming. To program with OOP,
programmer need proper skills such as design skills programming skills, thinking in terms of object etc.
Application of OOP:--
The promising areas for application of OOP includes:-
1. Real time systems
2. Simulation and modeling
3. Object-Oriented databases.
4. Hypertext, hypermedia and hypertext.
5. AI and expert system.
6. Neural network and parallel programming
7. Decision support and office automation system.
8. CIM/CAM/CAD systems.

IT Brainshapers 7 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Implementation of Polymorphism using Function Overloading :
Polymorphism is key to the object oriented programming. It is so important that languages that don‟t support
polymorphism cannot advertises themselves as OO languages .Language that support classes but not
polymorphism are called object based language .Ada is such a language .
Polymorphism is the ability for a message or data to be processed in more than one form.
Polymorphism is the concept that supports the capability of an object of a class to behave differently in
response to a message or action. e.g. Human‟ is a subclass of Mammal. Similarly Dog, Cat are also subclasses
of Mammal .Mammals can see through day-light. So if a message „see through daylight is passed to all
mammals, they all will behave alike .Now if a message „see through darkness is passed to all mammals, then
human and dogs will not be able to view at night whereas cats will be able to view during the night also. Here
cats (mammals can behave differently than other mammals in response to a message or action. This is
Polymorphism.
Polymorphism is a property by which the same message can be sent to objects of several
differently classes and each object can respond in a different way depending on its class.
Following figure shows that a single function name can be used to handle different member and
different types of arguments. This is something similar to a particular word having several different meaning
depending on the context.

Function Overloading
Function overloading implements polymorphism. Function overloading can also be termed as compile –time
polymorphism as the required function gets determined at the compile time.
Function overloading is a logical method of calling several functions by the same name, with different
arguments and data types which basically perform identical things.
A function name having several definitions that are differentiable by the number or types of their
arguments is known as function overloading
Need for Function Overloading
Objects have certain characteristics and associated behavior. But an object may behave in a different manner in
diverse situations.
In order to simulate real-world objects in programming, function overloading becomes essential. For overloaded
functions, the compiler automatically decided the particular function to be executed. It not only reduces the
code by reducing the number of if-else statements but also makes the code execute faster as so many
comparisons are eliminated
Advantages of Function Overloading
The programs become easier to read.
The programmer need not waste time in searching for a new name for similar functions.
The programmer can devote more time on logic development and need not remember different names.
It is used in inheritance and abstraction.
It is possible to speed up the program by inlining the right function
It makes the language extensible.
IT Brainshapers 8 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Disadvantages of Function Overloading
1. Since the complier will copy the entire function body every time the function is called, if it is a large function
(more than three or four lines), inline function can increase the size of the executable program significantly.
Rules for function Overloading
1. Each overloaded function must differ either by number of its formal parameters or their data types.
2. The return type of overloaded functions may or may not be same.
3. The default arguments of overloaded are nor considered by the C++ complier as part of the parameter list.
4. Do not use the same function name for two unrelated functions
Declaration and Defining Overloaded Functions
int area(int); or int area( int s);
int area(int ,int); or int area(int b,int h);
int area( int s)
{
return s*s;
}
int area (int b ,int h)
{
return (0.5*b*h);
}
Calling Overloaded Functions
Overloaded functions can be called just like any other C++ function. The number and type of arguments
determine which function is called
e.g area(5);
area(4,3);
Example1 Example2
/* Different Number of Arguments*/ /* Different Types of arguments*/
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
int area(int); float inc(float);
int area(int ,int); char inc(char);
void main( ) void main( )
{ {
clrscr(); clrscr( );
cout<<area(5); cout<<inc(23.45);
cout<<"\n"<<area(4,3); cout<<inc(A);
getch( ); getch( );
} }
int area( int s) float inc(float x) // Overloaded function
{ {
return s*s; return(++x);
} }
int area (int b ,int h) char inc(char x)
{ {
return (0.5*b*h); return ++x;
} }

IT Brainshapers 9 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Different Number of Arguments
// This program demonstrates the function overloading default:
//with different types of arguments {
#include<iostream.h> cout<<"Invalid choice";
#include<conio.h> }
int max(int x,int y); getch();
int max(int x, int y, int z); }
void main( ) int max(int x, int y)
{ {
clrscr( ); if (x>y)
int a,b,c, choice; {
cout<<"\n Options :"; return x;
cout<<"\n Max of two numbers 1"; }
cout<<"\n Max of three numbers 2"; else
cout<<"\n Enter your choice "; {
cin>> choice; return y;
switch(choice) }
{ }
case 1: int max(int x, int y,int z)
cout<<"\n Enter two integers"; {
cin>>a>>b; if((x>y)&&(x>z))
cout<<"\n The Max is = :"<<max(a,b); return x;
break; else if((y>x)&&(y>z))
case 2: return y;
cout<<"\n Enter three integers"; else
cin>>a>>b>>c; return z;
cout<<"\n The Max is = :"<<max(a,b,c); }
break;
Different Types of Arguments
// This program demonstrates the function overloading cin>>ch;
//with different types of arguments cout<<"\n The incremental value is :"<<inc(ch);
#include<iostream.h> }
#include<conio.h> else
float inc(float); {
char inc(char); cout<<"Invalid choice";
void main( ) }
{ getch();
clrscr(); }
float val; float inc(float x) // Overloaded function
char ch; {
cout<<"\n Enter 'f' for float and 'c' for character:"; return(++x);
cin>>ch; }
if((ch=='f')||(ch=='F')) char inc(char x)
{ {
cout<<"Enter the numerical value :"; return (++x);
cin>> val; }
cout<<"\n The incremental value is :"<<inc(val);
}
else if((ch=='c')||(ch=='C'))
{
cout<<"Enter the character value :";

IT Brainshapers 10 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Implementation of OOP in C++
Definition of Class
A class is a user defined data type which holds both the data and function. The internal data of a class is called
member data and the functions are called member functions.
The member functions are mainly used to manipulate the internal data of a class. The variables of class are
called objects or instance of a class. A class act like an independent program that logically organizes data and
functions together. A collection of classes makes up a larger program. In general, there are three stages to create
and use a class. They are:
1. Class declaration- It describes the data types and scope of its members.
2. Class function definition-It describes the implementation of class function
3. Creation of objects-It describes the method of create variables of type class(ADT)
Class Declaration The general form of a class declaration is as follows:
Syntax1 Syntax2
class user_defined_name class user_defined_name
{ {
access specifier : access specifier :
data members ; data members ;
access specifier : access specifier :
function members function members
}[object_name]; };
user_defined_name object_name;
Example2 Example2
class student class student
{ {
private : private :
int rollno; int rollno;
char name[20]; char name[20];
public: public:
void readdata(void); void readdata(void);
void displaydata(void); void displaydata(void);
}stud; }
student stud;
Properties of Classes
Classes consist of both data (variables) and functions.
Classes allow private as well as public members.
A member function defines inside the class is by default as
inline function.
A member of a class is by default a private member unless
otherwise specified.
A private member is not available outside the class. However
, a member function can always access such a member
A member function can be overloaded.
Objects can be passed as parameters to function.
Objects can be returned from a function.

IT Brainshapers 11 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Access Specifier/Visibility Mode
The access specifier informs the complier about the scope of data members and member functions of a class. By
default, all the class members are treated as private. Classes offer there levels of accessibility, namely private,
protected and public.
Private
Private accessibility means that members within a class can only be accessed by that class.
Protected
Protected accessibility means that members within a class can be accessed by member functions declared by
that class and any classes “inherited “from that class.
Public
Public accessibility means that members within a class can be accessed by any part of a program.
Members of a Class
Members can be either data or function declarations that are contained in the body of the declaration.
Data members: The data type properties that describe the characteristics of a class. Data members are optional
in a class declaration.
Member function The set of operations that are applied to objects of a class .Member function is also optional
in a class declaration .They are referred to as the class interface.
Member Function Definition
Member functions can be defined in two places
1. Outside the class definition
2. Inside the class definition
Member Function Defined Inside the Class Definition
Member function definition is similar to a normal function definition except that it is enclosed within the
body of a class.
By default, all the member function defined within the body of a class are treated as inline
There is no prototype in this method
Member Function Defined Outside the Class Definition
To declare the member function of a class outside the class definition, the function prototype should be
declared within the body of a class and defined outside the body of a class.
Membership identity label (class_name::) differentiates member functions and non member functions in a
program. This uses scope resolution operator (::).
By default, the member function defined outside the class definition is non-inline.
It can be made inline by explicitly adding inline as prefix to the member function the definition
/* Member Function inside the class*/ }
#include<iostream.h> void displaydata( )
#include<conio.h> {
class student // Declaration of class cout<<"\n\nThe details of student";
{ cout<<"\nRollNo :"<<rollno;
private : cout<<"\nName :"<<name;
int rollno; }
char name[20]; };
public: void main()
void readdata( ) {
{ clrscr();
cout<<"Enter the details of student\n"; student stud;
cout<<"\nEnter RollNo :"; stud.readdata();
cin>>rollno; stud.displaydata();
cout<<"\nEnter Name :"; getch();
cin>>name; }

IT Brainshapers 12 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
/* Member Function outside the class*/ void student :: displaydata(void)
#include<iostream.h> {
#include<conio.h> cout<<"\n\nThe details of student";
class student // Declaration of class cout<<"\nRollNo :"<<rollno;
{ cout<<"\nName :"<<name;
private : }
int rollno; void main( )
char name[20]; {
public: clrscr();
void readdata(void); student stud;
void displaydata(void); stud.readdata();
}; stud.displaydata();
void student :: readdata(void) getch( );
{ }
cout<<"Enter the details of student\n";
cout<<"\nEnter RollNo :";
cin>>rollno;
cout<<"\nEnter Name :";
cin>>name;
}

Accessing Class Members


Members of a class may be accessed directly within the scope of the class. Outside the scope of the class, a
member function selection operator must be used .There are two type of member selection operator:
The dot operator (“.”): this is used whenever the user wishes to access a member of a particular class object
or reference.
The arrow operator (“→”): this is used whenever the user wishes to access a member of a particular class
object through a class pointer.
// This program demonstrates the accessing class void main()
//member using dot and arrow operator {
#include<iostream.h> clrscr();
#include<conio.h> student stud;
class student // Declaration of class // using dot memeber selection operator
{ stud.readdata();
private : student *p;
int rollno; p= &stud;
char name[20]; // using arrow memeber seelction operator
public: p->displaydata();
void readdata(void) getch();
{ }
cout<<"Enter the details of student\n";
cout<<"\nEnter RollNo :";
cin>>rollno;
cout<<"\nEnter Name :";
cin>>name;
}
void displaydata(void)
{
cout<<"\n\nThe details of student";
cout<<"\nRollNo :"<<rollno;
cout<<"\nName :"<<name;
}
};
IT Brainshapers 13 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Defining or Creating of Objects
An object is an instance of a class and it can be created of its class type by using the class name .The process of
creating objects (variables) of the class is called class instantiation. In C++, the class variables are called as
objects. The complier allocated required memory for objects. The size of an object is equal to the sum of the
sizes of the individuals data items of a class
The syntax for defining an object is given below:
class_name object_name;
where class _name : is the name of the class
object_name : is the name of the object being defined
e.g we can create an object stud of class student by the following declaration
student stud;
The above declaration says that stud is an object of class student
We can create as many as objects of the class as required
class_name object1_name, object2_name,object3_name……… object n_name;
e.g. student stud1,stud2,stud3,stud4;
Memory Allocations for Objects
At the time of creating objects of a class, the complier allocates the required amount of memory for a class
definition. For each object of a class, a separate copy of data members and one copy of member functions is
created .For each object, a separate memory is allocated and the address of that memory is stored in this pointer.
By using this pointer, the unique copy of member function of all the objects of a class are identified .This
pointer is passed automatically to all the member functions of a class
Arrays within a Class
Arrays can be used as data members in a class .All the possible operations can be carried out by an object on its
array data members .The usage of arrays within a class is illustrated with the help of following example
Example
/* Arrays within a Class */ void mat::print_mat()
#include<iostream.h> {
#include<conio.h> cout<<"\nThe Matrix is\n";
class mat //Defines the class
{ for(i= 0;i<r;i++)
int r,c ,i,j; {
int mat[10][10]; // Arrays within a Class for(j=0;j<c;j++)
public: {
void read_mat(); cout<<mat[i][j];
void print_mat(); }
}; cout<<"\n";
//Read the matrix }
void mat::read_mat() }
{
cout<<"\n Enter the size of the Matrix : Row and Column"; void main()
cin>>r>>c; {
cout<<"\n Enter the elements of matrix :\n"; mat matobj;
for(i= 0;i<r;i++) matobj.read_mat();
{ matobj.print_mat();
for(j=0;j<c;j++) getch();
{ }
cin>>mat[i][j];
}
}
}
IT Brainshapers 14 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Array of Objects: C++ allows declaration of arrays of objects like array of any other type .An individual object
within the array can be accessed by a subscript.
Syntax Example
class user_defined_name class student
{ {
private : private :
data members ; int rollno;
function members ; char name[20];
public : public:
data members ; void readdata(void);
function members void displaydata(void);
}; };
class user_defined_name object[MAX]; student stud[20];
Max is the size of Array of class object
An array of objects is stored inside the memory in the same way as a multi-directional array. The array stud is
represented in the figure given. Note that only the memory space for data members of the objects is allocated
member functions are stored separately and will be shared by all the objects
roll_no
name stud[0]
roll_no
name stud[1]
roll_no
name stud[2]
An array of class

Example1 Inside the Class


/* Array of Objects */ }
#include<iostream.h> };
#include<conio.h> void main( )
class student // Declaration of class {
{ clrscr();
private : student stud[20]; /Declaration of Array of Object
int rollno; int i,n;
char name[20]; cout<<"How many students ";
public: cin>>n;
void readdata(void) // Inside the class cout<<"\nEnter the detail of student";
{ for(i =0; i<n ;i++)
cout<<"\nEnter RollNo :"; {
cin>>rollno; stud[i].readdata( );
cout<<"\nEnter Name :"; }
cin>>name; cout<<"\n\nThe details of student no ";
} for(i= 0; i<n ;i++)
void displaydata(void) {
{ stud[i].displaydata();
cout<<"\nRollNo :"<<rollno; }
cout<<"\nName :"<<name; getch();
} }

IT Brainshapers 15 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
// Example2 Outside the Class cout<<"\nName :"<<name;
//Array of Objects }
#include<iostream.h> void main( )
#include<conio.h> {
class student // Declaration of class clrscr();
{ student stud[20]; //Declaration of Array of Object
private : int i,n;
int rollno; cout<<"How many students ";
char name[20]; cin>>n;
readdata(void); cout<<"\n Enter the details of students ";
displaydata(void); for(i =0; i<n ;i++)
}; {
void student ::readdata(void) //Outside Class stud[i].readdata();
{ }
cout<<"\nEnter RollNo :"; cout<<"\n\nThe details of student no ";
cin>>rollno; for(i= 0; i<n ;i++)
cout<<"\nEnter Name :"; {
cin>>name; stud[i].displaydata();
} }
void student :: displaydata(void) getch();
{ }
cout<<"\nRollNo :"<<rollno;

Functions returning Objects


A function can return an object if it has been declared to return the corresponding class of objects .For example,
a function some() which return an object of class x type can be defined as shown below
x some( ).
{
x temp;
return(temp);
}
Example
// This program illustrates the Returning }
// of objects from a function int set :: find()
#include<iostream.h> {
#include<conio.h> int lar;
class set lar=list[0];
{ for(i=1;i<n;i++)
private : {
int list[20]; if(list[i]>lar)
int i,n; lar=list[i];
public: }
void read_list(); return(lar);
int find(); }
}; //Declaring a function that reads an object of set type and return it
void set::read_list() set read_obj()
{ {
clrscr(); set x; // Declare object x of class set
cout<<"Enter the size of the list"; x.read_list( ); //Read the list of the object x
cin>>n; return(x); //Return the object X.
cout<<"\nEnter the list \n"; }
for(i=0;i<n;i++) void main( )
cin>>list[i]; {
IT Brainshapers 16 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
set objlist;
int largest;
objlist=read_obj( );
largest=objlist.find( );
cout<<"The largest is "<<largest;
getch( );
}
Nesting of member function
A member function can be called by another function of the same class. This activity is known as nesting of
member function.
//This program demonstrates the void list::modify( )
// use of Nesting of member function {
#include<iostream.h> for(i=0;i<n;i++)
#include<conio.h> {
class list list[i]=list[i]*10;
{ }
private: display();
int i,n,list[50]; }
void display(); void list::display( )
public : {
void read_list(); cout<<"\nThe list is \n";
void modify(); for(i=0;i<n;i++)
}; {
void list::read_list() cout<<list[i]<<"\n";
{ }
cout<<"Enter the length of the list"; }
cin>>n; void main()
cout<<"\nEnter the list :\n"; {
for(i=0;i<n;i++) clrscr();
{ list series; // Declare an object called series
cin>>list[i]; series.read_list(); //read list
} series.modify(); //modify and display list
} getch();
}
Friend Function
We know that an individual function cannot access the private data structure of a class. The term individual
means that the function is not part of the class or any other class. If the need be, the access can be given to an
individual function by specifying the function as friend of the class whose data structures are required by
the function. In simple words, we can say that a friend function has an advantage of having an access to the
private data members of its friend class.
A function can be specified as a friend of a class by including its prototyping in the class preceded by the
keyword friend. Friend function can be defined anywhere in the program like any other C++ normal function.
Special Characteristics of friend function
Friend function is not in the scope of class that means it cannot be called by using the object of that class.
The scope of the friend is not limited to the class in which it is declared as a friend.
A function can be friend to multiple classes.
Unlike class member functions, it cannot access the class members directly. However it can use the object
and dot operator with each member name to access both the private members and public members.
Friend function can be declared either in the private part or in the public part without affecting its meaning.
Friendship cannot be inherited.
Friend ship is not mutual i.e. if class A is friend of B then vice versa is not true.
Usually, it has an object as arguments.
IT Brainshapers 17 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
For example, a function xyz can be made friend to a class test as shown below:
class test
{
public:
friend void xyz();
};
void xyz() // Individual function
{
….
}
//This program demonstrates the use of friend //This program demonstrates a function friendly to two
// function //classes
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
class sample class ABC; // Forward declaration
{ class XYZ
int a,b; { int x;
public: public:
void setvalue() void setvalue(int i)
{ {
a=10; x=i;
b=20; }
}; friend void max(XYZ,ABC); //Friend declared
friend float mean(sample s); //Friend declared void max(XYZ m, ABC n)
}; {
float mean(sample s) if(m.x > n.a)
{ cout<<m.x;
return float(s.a+s.b)/2.0; else
} cout<<n.a;
void main() }
{ void main()
sample x; //object x {
x.setvalue(); ABC abc;
cout<<"Mean value ="<<mean(x); abc.setvalue(20);
getch( ); XYZ xyz;
} xyz.setvalue(30);
max(xyz,abc);
getch();
}
};
class ABC
{
int a;
public :
void setvalue(int i)
{
a=i;
}
friend void max(XYZ,ABC);
};

IT Brainshapers 18 Sanjay -7889862407


12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Concept of Scope Resolution Operator(::)
Scope Resolution operator(::) in C++ is used to define a function outside a class or when we want to use a
global variable but also has a local variable with the same name.
#include<iostream.h> // Scope resolution operator in class
#include < conio.h> #include<iostream.h>
char c=‟a‟; // global variable (accessible to all function) #include < conio.h>
void main( ) class Game
{ {
char c =‟b‟; // local variable(accessible only in main public :
function) void play( ); //Function declaration
cout<<”Local Variable :”<<c<<”\n”; }
cout<<”Global Variable :”<<:: c<<”\n”; void class:: play( )
// Using Scope resolution operator {
getch ( ); cout<<”Function defined outside the class\n”;
} }
Output: void main( )
Local Variable: b {
Global Variable: a Game g; // Creating object
g.play( )
<<”\n”; // Using Scope resolution operator
getch ( );
}

IT Brainshapers 19 Sanjay -7889862407


12th Comp Science Unit 2: Constructor and Destructor Marks 05
Constructor
Initialization is an important concept in computer programming. When object is created, its state must be
initialized otherwise object will contain garbage value .C++ provides an elegant way to address this problem i.e.
A constructor may be defined as member function of a class, which is executed automatically, initializing the
objects of the class as soon as these are created. The constructor is a special member function which has
following characteristics
Characteristics of Constructor
Constructor has the same name as the class of which it is a part.
Constructor does not have return type as function of Constructor is of initialization.
Constructor is invoked automatically at the time of creation of object.
Constructor may or may not have arguments.
Constructor must be defined in the public part otherwise it will not be invoked.
Constructor cannot be virtual.
Constructor cannot be volatile.
Constructor cannot be static.
Constructor cannot be const.
Constructor can be overloaded i.e. a class may have any number of constructors.
Declaration and Definition
Syntax: Example
class user_defined_name class student
{ {
private : private :
data member; int roll;
data member; char name[20];
public: public:
user_defined_name ( ); // constructor declaration student ( ) ; // constructor declaration
other member function; void read() ;
}; void show();
}; // end of class declaration }; // end of class declaration
//constructor definition
user_defined_name:: user_defined_name ( ); student :: student ( ); // constructor definition
{ {
………. roll=0;
} name= ‘/0’;
}

IT Brainshapers 1 Sanjay -7889862407


12th Comp Science Unit 2: Constructor and Destructor Marks 05
//This program illustrates the Constructor
#include<iostream.h>
#include<conio.h>
class counter
{
private :
int value;
public:
counter() // this is a constructor
{
value=0;
}
int show()
{
return value;
}
};
void main()
{
clrscr( );
counter c1; //object c1 is created. Constructor is invoked
cout<<"\n Count : "<<c1.show(); //print 0
getch( );
}
Types of Constructor
Constructor

Default Parameterized Copy

Default Constructor
The constructors which do not have no arguments (parameters) or have default arguments are known as Default
constructor. If a class has no explicit constructor defined, the complier will supply a default constructor
provided by the complier does not do anything specifies it initialize the data member by the dummy value. e.g.
class counter
{
private :
int value;
public:
counter( ) // this is default constructor
{
value=0;
}
};
When a class contains a constructor like the one defined above, it is guaranteed that an object created by the
class will be initialized automatically. For example, the declaration not only creates the object c1 of type
counter but also initializes its data member value to zero
counter c1 //object c1 is created

IT Brainshapers 2 Sanjay -7889862407


12th Comp Science Unit 2: Constructor and Destructor Marks 05
.//This program illustrates the default Constructor
#include<iostream.h>
#include<conio.h>
class counter
{
private :
int value;
public:
counter( ) // this is default constructor
{
value=0;
}
int show( )
{
return value;
}
};
void main( )
{
clrscr( );
counter c1; //object c1 is created. Constructor is invoked
cout<<"\n Count : "<<c1.show(); //print 0
getch( );
}

Parameterized Constructor
When parameters are specified but no default values of parameters in the definition of the Constructors, such
constructors are called as Parameterized constructors.
e.g
class counter
{
private :
int value;
public:
counter(int a) //parameterized constructor
{
value=a;
}
};
When a constructor has been parameterized ,the object declaration statement such as
counter c1; //
may not work. We must pass the initial values as arguments to the constructor function when as an object is
declared. This can be done in two ways:
By calling the constructor explicitly.
By calling the constructor implicitly.

IT Brainshapers 3 Sanjay -7889862407


12th Comp Science Unit 2: Constructor and Destructor Marks 05
The following declaration illustrates the first method:
counter c1 = counter(10); //explicit call
This statement creates a counter object c1 and passes the value 10 to it.
The second is implemented as follows:
counter c1(10); //implicit call
This method, sometimes called the shorthand method, is used very often as it is shorter, looks, better and is easy
to implement
// This program illustrates the parameterized constructor
#include<iostream.h>
#include<conio.h>
class counter
{
private :
int value;
public:
counter(int a) //parameterized constructor
{
value=a;
}
int show()
{
return value;
}
};
void main()
{
clrscr( );
counter c1(10); //object c1 is created & initialized with value 10
cout<<"\n Count : "<<c1.show(); //print 10
getch( );
}
Copy Constructors:
When argument to a constructor is an object of that class then it is called copy constructor. Copy constructor is
used to initialize one object by another object of the same class
In simpler words we can say that if we have an object c1 and we desire to create a new object c2 initialized with
the contents of obj1 then the copy constructor should be used Consider the declaration given below:
counter c1 ……….(i)
counter c2(c1); ………..(ii)
The declaration (i) declares an object c1 of class counter
where the declaration (ii) declares another object c2 of class counter as well as initializes it with the contents of
existing object c1.The copy constructor is, however, defined in the class as a parameterized constructor
receiving an object as argument passed by reference as its shown below

IT Brainshapers 4 Sanjay -7889862407


12th Comp Science Unit 2: Constructor and Destructor Marks 05
class counter
{
private :
int value;
public:
counter( counter &a) //Copy constructor
{
value= a.value;
}
};
//This illustrates the copy constructor
#include<iostream.h>
#include<conio.h>
class counter
{
private :
int value;
public:
counter(int a) //parameterized constructor
{
value=a;
}
counter( counter &a) //Copy constructor
{
value= a.value;
}
int show()
{
return value;
}
};
void main()
{
clrscr();
counter c1(10);
cout<<"\n Count : "<<c1.show(); //print 10
//copy constructor is involked
counter c2(c1); //object c2 is created & initialized by object c1
cout<<"\n Count : "<<c2.show(); //print 10
getch();
}
Overloaded Constructor
The process of sharing the same name by two or more functions is referred to as a function overloading.
Similarity when more than one constructor function is defined in a class, it is known as constructor
overloading.
//This program illustrates the overloaded constructor
#include<iostream.h>
#include<conio.h>
class counter
{
private :
IT Brainshapers 5 Sanjay -7889862407
12th Comp Science Unit 2: Constructor and Destructor Marks 05
int value;
public:
counter() //Default constructor
{
value=0;
}
counter(int a) //parameterized constructor
{
value=a;
}
counter( counter &a) //Copy constructor
{
value= a.value;
}
int show()
{
return value;
}
};
void main()
{
clrscr();
counter c1;
cout<<"\n Count : "<<c1.show(); //print 0
counter c2(10); //object c1 is created & initialized with value 10
cout<<"\n Count : "<<c2.show(); //print 10
//copy constructor is invoked
counter c3(c2); //object c2 is created & initialized by object c1
cout<<"\n Count : "<<c3.show(); //print 10
getch();
}

Constructor with Default Argument


We may often allow users of ours classes to pass arguments to the constructor .Rather than providing a separate
default constructor that take no arguments .it is better to provide a constructor with default constructor that can
serve as a default constructor or as a constructor that takes the arguments it specifies .This makes our code more
compact and leads to more code reuse.
A constructor can be defined wiry default arguments .e.g. the constructor counter ( int a = 2)
The default value of the argument a is zero. Then, the statement
counter c1;assigns the value 2 to a.
//This program illustrates the constructor with Default Argument
#include<iostream.h>
#include<conio.h>
class counter
{
private :
int value;
public:

IT Brainshapers 6 Sanjay -7889862407


12th Comp Science Unit 2: Constructor and Destructor Marks 05
counter(int a = 0 ) // this is default constructor, with default value
{
value=a;
}
int show()
{
return value;
}
};
void main()
{
clrscr();
counter c1; //object c1 is created. Constructor is invoked, default value is used
cout<<"\n Count : "<<c1.show(); //print 0
getch();
}

Destructor
Destructors have reverse function as that of constructors. The space which is an allocated dynamically can be
freed by the destructor .So destructor can free the space which has been allocated by new operator only. The
destructor is a special member function whose name is the same as the class name but is preceded by
tilde (‘~’) For example destructor for the class Student will bear the name ~student( ) It has following
characteristics:
Destructor has the same name as the class of which is a part and proceeded by the symbol ~.
Destructor does not have return type as function of destructor is to free space.
Destructor is invoked automatically at the time of death of object.
Destructor cannot have arguments.
Destructor must be defined in the public part otherwise it will not be invoked.
Destructor can be virtual.
Destructor cannot be volatile.
Destructor cannot be static.
Destructor cannot be const.
Destructor cannot be overloaded
Need for Destructor
During construction of an object by the constructor, resources may be allocated for use. e.g.
a constructor may have opened a file and a memory area may be allotted to it.These allocated resources must
be deallocated before the object destroyed. A destructor as per name perform clean up task./Therefore, a
destructor is equally useful as a constructor is.
Declaration and Definition
A destructor is a member function and can be defined like any other member
function. However, it does not take any argument neither does it return any value.
A destructor being a member function follows the access rules for a member function i.e. if defined as
a private or protected member function, it becomes available for a member functions and only these can create,

IT Brainshapers 7 Sanjay -7889862407


12th Comp Science Unit 2: Constructor and Destructor Marks 05
use and destroy objects of this class type. However, if a class defines a public destructor, its objects can be
created, used and destroyed by any function.
Syntax Example
class user_defined_name class student
{ {
private : private :
data member; int roll;
data member; char name[20];
public: public:
user_defined_name ( ); // constructor declaration student ( ) ; // constructor declaration
~user_defined_name ( ); // destructor declaration ~ student( );
other member function; void read( ) ;
}; void show( );
}; // end of class declaration }; // end of class declaration
//constructor defination student::~student ( ); // constructor definition
user_defined_name:: ~user_defined_name ( ); {
{ roll=0;
…. name= ‘/0’;
} }
//This illustrates the use of destructor
#include<iostream.h>
#include<conio.h>
class counter
{
private :
int value;
public:
counter() // constructor
{
value=0;
cout<<"\n Constructor invoked";
}
~counter()
{
cout<<"\n Destructor invoked";
}
int show()
{
return value;
}
};
void main()
{
counter c1; //object c1 is created .Constructor is invoked, default value is used
cout<<"\n Count : "<<c1.show(); //print 0
getch();
}

IT Brainshapers 8 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Inheritance Concept
The technique of deriving a new class from an existing class is called inheritance. A class that is inherited is
referred to as a base(super)class. The class that does the inheriting is called the derived (sub) class. Further a,
derived class can be used as a base class for another derived class. The derived class inherits some or all the
properties of the base class. The relationship between base and derived class is known as inheritance hierarchy.
e.g. motorcycle is class in itself. It is also member of two wheelers class. Two wheelers class in turn is a
member of an automotive class. Thus, the automotive is an example of a base class and two wheelers is derived
class. In simpler words, we can say that a motor cycle is two wheeler automotive.
Base Class

Derived Class

Inheritance

In C++, a derived class can be obtained by adding some new data structure and functions
to a base class. The derived class inherits the members of its base class without the need
to redefine them.
The general syntax for defining a derived class is given below
class <derived class> : visibility mode <base class>
{
body of new class
};
where , class : is a reserved word
<derived class> : is the name of the subclass or new class being derived
visibility mode : is the mode of access to items from the base class.
The access mode is optional and can be either of the following type:
private ,public, protected
<base class> : is the name of the super class i.e. an existing class
//This program illustrates the inheritance int marks;
#include<iostream.h> public: void get_data()
#include<conio.h> {
class person read_data ( ); //read name & age from
{ base class
private: cout<<"\n RollNo: ";
char name[30]; //non-inheritable being private cin>>roll;
int age; cout<<"\nEnter marks: ";
public: cin>>marks;
void read_data() }
{ void show_data()
cout<<"\nEnter Name: "; {
cin>>name; display_data();
cout<<"\nEnter Age: "; cout<<"\nRoll No : "<<roll;
cin>>age; cout<<"\nMarks : "<<marks;
} }
void display_data() }; //end of class student
{ void main()
cout<<"\nName : "<<name; {
cout<<"\nAge : "<<age; clrscr();
} student stud; // create an object of student type
}; //end of class person stud.get_data(); //read data of a student
class student :public person stud.show_data();
{ getch();
private: }
int roll;
IT Brainshapers 1 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05

Need for Inheritance


Inheritance is a splendid concept of object-orieneted language. There is several reasons why inheritance was
introduced into OO language. Some are
1. Using inheritance, classes/objects in C++ can behave much like real world objects.
2. It is required for extending the functionality of an existing class.
3. It can be used to establish “a kind of ” relationship.
4. It helps in reuse of an existing class by a derived class.
5. The redundancy among classes can be reduced by abstracting a super class out of them. This property is
known as generalization.
Parent (Base) Class
A base class is a class, which is used to create other classes. It is the parent of derived class.
Syntax
class base_class_name
{
access specifier:
data member;
access specifier:
member function;
}[object_name];
Derived Class
A derived class is defined by specifying its relationship with base class in addition to its own attributes.
Syntax
class derived_class_name : visibility mode base_class_name
{
………//
………// members of derived class
};
The colon : indicates that derived _class_name is obtained from base_class_name. The construct visibility mode
is called the access specifier. This construct specifies the manner in which the base class is inherited .The
visibility mode of the base class is optional and, if present, may be either private, public or protected .The
default visibility mode is private. The visibility mode specifies whether the features of the base class are derived
privately.
e.g
class D : private B //private derivation
{
members of D
};
class D : public B //public derivation
{
members of D
};
class D : protected B //protected derivation
{
members of D
};
class D : B //private derivation by default
{
members of D
};
IT Brainshapers 2 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Types of Inheritance
Inheritance can take many forms, which are being discussed below
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
When a subclass inherit only from one base class. It is known as single inheritance
X base class

Y derived class

Multiple Inheritance
When a subclass inherit from multiple base classes. It is known as multiple inheritance.

X Y base classes

Z derived class
Multilevel Inheritance
When a subclass inherits from a class that itself inherit from another class. It is known as multilevel inheritance.

X base class of Y

Y
base class of Z

Z Sub class of Y
Hierarchical Inheritance
When many subclasses inherit from a single base class. It is known as hierarchical inheritance.

Z base class

W X Y Sub classes

IT Brainshapers 3 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Hybrid Inheritance
When a derived class inherit from multiple base classes and all of its base classes inherit from a single base
class. It is known as hybrid inheritance.
Z base classes of X &Y

X Hybrid Y base classes of W


Inheritance

W Sub class of X & Y


Accessing the Base Class Members
When a member function in the base class can be used by objects in the derived class. This is known as
accessibility
Visibility Modes
A visibility mode specifies whether the features of the base class are privately derived or publicly derived .The
default visibility mode is private .A visibity_mode may belong to one of the following:
a) Public
b) Private
c) Protected
Public Access Specifier
In the case of public derivation, the derived class can access the public and protected members of the base class,
but not the private members of the base class. The public members of the base class become the public members
of the derived class and the protected members of the base class become the protected members of the derived
class. Public derivation does not change the access specifies for inherited members in the derived class.
Inherited members need not be defined in the derived class.
The following example explains public derivation in class
class B // The base class B
{
//The private members of the class
private : int a;
void test(void);
//The public members of the class
public: int b;
void getdata(void);
//The protected members of the class
protected: int c;
void putdata(void);
};
//The publicly derived class B
class D: public B
IT Brainshapers 4 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
{
//The private members of the class
private : int p;
void input(void);
//The public members of the class
public: int q;
void display(void);
//The protected members of the class
protected: int r;
void large(void);
};
Private Access Specifier
In the case of private derivation, the derived class can access the public and protected members of the base
class privately. With a privately derived class, both the public and protected, members of the base class become
private members of the derived class. This means that in case of private derivation, the inherited members of the
base class can be accessed only through the member functions of the derived class. Also, since inherited
members become private in the derived class, they can be inherited further if the derived class is the base class
of the any other class
The following example explains private derivation in class
class B //The base class B
{
//The private members of the class
private : int a;
void test(void);
//The public members of the class
public: int b;
void getdata(void);
//The protected members of the class
protected: int c;
void putdata(void);
};
//The privately derived class B
class D: private B
{
//The private members of the class
private : int p;
void input(void);
//The public members of the class
public: int q;
void display(void);
//The protected members of the class
protected: int r;
void large(void);
};

IT Brainshapers 5 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Protected Access Specifier
The class derived in the protected mode can access the public and protected members of the base class. With
such a class, the public and protected members of the base class become protected members of the derived
class. That means the inherited members are not accessible to the outside world can be accessed through the
member functions of the derived class and the classes based upon the derived class. These members can be
inherited further if any classes are inherited from the derived class.
The following example explains protected derivation in class
class B //The base class B
{
//The private members of the class
private : int a;
void test(void);
//The public members of the class
public: int b;
void getdata(void);
//The protected members of the class
protected: int c;
void putdata(void);
};
//The protected derived class B
class D: protected B
{
//The private members of the class
private : int p;
void input(void);
//The public members of the class
public: int q;
void display(void);
//The protected members of the class
protected: int r;
void large(void);
};

IT Brainshapers 6 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Significance of Visibility Modes
This type of visibility mode that should be used in the given circumstances is discussed below (if no visibility
mode is specified, then the class will inherit privately
A class should be derived publicly when all the attributes of the base class are required by the derived class.
A class should be derived privately when the derived class needs to use some attributes of the base class and
these attributes need not be inherited further.
A class should be derived protectedly when the attributes of the base class are required by the derived class.
Single Inheritance
When a subclass inherit only from one base class. It is known as single inheritance X base class

Y derived class
//This program illustrates the inheritance void main()
#include<iostream.h> {
#include<conio.h> clrscr();
class person student stud; // create an object of student type
{
private: stud.get_data(); //read data of a student
char name[30]; //non-inheritable being private stud.show_data();
int age; getch();
public: }
void read_data()
{
cout<<"\nEnter Name: ";
cin>>name;
cout<<"\nEnter Age: ";
cin>>age;
}
void display_data()
{
cout<<"\nName : "<<name;
cout<<"\nAge : "<<age;
}
}; //end of class person
class student :public person
{
private:
int roll;
int marks
public:
void get_data()
{
read_data ( ) //read name & age from base class
cout<<"\n RollNo: ";
cin>>roll;
cout<<"\nEnter marks: ";
cin>>marks;
}
void show_data()
{
display_data()
cout<<"\nRoll No : "<<roll;
cout<<"\nMarks : "<<marks;
}
}; //end of class student
IT Brainshapers 7 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Multiple Inheritance
When a subclass inherit from multiple base classes. It is known as multiple inheritance.

X Y base classes

Z derived class

//This program demonstrates the multiple inheritance cout<<"\nAge : "<<age;


#include<iostream.h> cout<<"\nColour : "<<color;
#include<conio.h> }
class Father void Mother:: read_data()
{ {
private : char name[30]; cout<<"\nEnter the height : ";
int age; cin>>height;
public: char color[15]; cout<<"\nEnter the weight : ";
void get_data(); cin>>weight;
void display_data(); }
}; void Mother:: show_data()
class Mother {
{ cout<<"\nHeight : "<<height;
private : int height; cout<<"\nWeight : "<<weight;
public: float weight; }
void read_data(); void son::input()
void show_data(); {
}; get_data();
//derived class:level2 read_data();
class son:public Father,public Mother cout<<"\nEnter the hobby: ";
{ cin>>hobby;
private : char hobby[20]; }
public : void input(); void son::output()
void output(); {
}; display_data();
void Father:: get_data() show_data();
{ cout<<"\nHobby : "<<hobby;
cout<<"\nEnter the name : "; }
cin>>name; void main()
cout<<"\nEnter the age : "; {
cin>>age; clrscr();
cout<<"\nEnter the colour : "; son s;
cin>>color; s.input();
} s.output();
void Father:: display_data() getch();
{ }
cout<<"\nName : "<<name;

IT Brainshapers 8 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Multilevel Inheritance
When a subclass inherits from a class that itself inherit from another class. It is known as multilevel inheritance.

X base class of Y

Y
base class of Z

Z
Sub class of Y
The multilevel inheritance implements the transitive nature of real life objects. There can be any number of
classes in the inheritance hierarchy.
/This program illustrates the multilevel inheritance void grandFather::display_data()
#include<iostream.h> {
#include<conio.h> cout<<"\nName : "<<name;
class grandFather cout<<"\nAge : "<<age;
{ cout<<"\nColour : "<<color;
private : }
char name[30]; void father::read_data()
int age; {
public: get_data();
char color[15]; cout<<"\nEnter the qualification: ";
void get_data(); cin>>quali;
void display_data(); cout<<"\nEnter the salary : ";
}; cin>>salary;
class father: public grandFather //derived class:level1 }
{ void father::show_data()
private : {
char quali[25]; display_data();
public: cout<<"\nQualification : "<<quali;
float salary; cout<<"\nSalary : "<<salary;
void read_data(); }
void show_data(); void son::input()
}; {
class son:public father //derived class:level2 read_data();
{ cout<<"\nEnter the hobby: ";
private : cin>>hobby;
char hobby; }
public : void son::output()
void input(); {
void output(); show_data();
}; cout<<"\nHobby : "<<hobby;
void grandFather::get_data() }
{ void main()
cout<<"\nEnter the name : "; {
cin>>name; clrscr();
cout<<"\nEnter the age : "; son s;
cin>>age; s.input();
cout<<"\nEnter the colour : "; s.output();
cin>>color; getch();
} }
IT Brainshapers 9 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Nested Class or Containership
Presence of one or more classes within an other class as its member or members constitutes a Nested Class, the
process being known as Nesting of classes.
When a class is defined inside the body of another class is called as nested class i.e. class within class
When a class contains another class in it as a member, this class obviously inherits the attributes of the
contained class, without inheriting the contained class explicitly.
Another technique of making A to inherit the properties of another class B is to incorporate the object or objects
belonging to the class B as members of the class A.
The relationship of a class containing the objects belonging to the other class or classes is known as
containership or nesting.
e.g
class B
{
….
};
class A
{
B b; //object of class A
};
//This program illustrates use of nested class class manager
#include<iostream.h> {
#include<conio.h> private :
class employee char desi[30];
{ employee emp; //object of class employee
private: public:
char name[20]; void get_details(void)
int salary; {
public: emp.get_data();
void get_data(void) cout<<"\n Enter designation :";
{ cin>>desi;
cout<<"\n Enter name of employee"; emp.show_data();
cin>>name; cout<<"\n Designation :"<<desi;
cout<<"\n Enter salary"; }
cin>>salary; }; // end of contained class manager
} //the main program start
void show_data(void) void main()
{ {
cout<<"\n Name : "<<name; clrscr();
cout<<"\n Salary: "<<salary; manager m;
} cout<<"Enter data for manager\n";
}; //end of class employee m.get_details();
getch();
}

IT Brainshapers 10 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Virtual Base Class
When two or more objects are derived from a common base class, we can prevent multiple copies of base class
from being present in an object derived from those objects by declaring the base class as virtual when it is
inherited .This is accomplished by putting keyword virtual before the base class name when it is inherited.
class one // this is common base class
{
// body of class one
};
class two: public virtual one // common base class is declared as virtual
{
// body of class two
};
class three: public virtual one // common base class is declared as virtual
{
// body of class two
};
class four: public two, public three
{
//body of class four
};
// This program demonstrates the use of Virtual base class
#include<iostream.h>
#include<conio.h>
class Base
{
public:
int a;
};
class D1:virtual public Base //D1 inherit Base as virtual
{
public :
int b;
};
class D2:virtual public Base //D2 inherit Base as virtual
{
public :
int c;
};
class D3:public D1,public D2 //this time ,there is only one copy of Base
{
public:
int total;
};
void main()
{
clrscr();
D3 ob;
ob.a=20;
ob.b=30;
ob.c=40;
ob.total=ob.a+ob.b+ob.c; //unambiguous
cout<<ob.a<<" + "<<ob.b<<" + "<<ob.c<<" = "<<ob.total;
getch();
}

IT Brainshapers 11 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Abstract Classes
A class that contains one or more pure virtual functions is called as an abstract class. Object of an abstract class
cannot be defined .Compiler recognizes the abstract class from pure virtual function and pure virtual function is
recognized from the initialization of pure virtual function to 0.Abstract classes are used to derive child classes.
The derived class inherits all the members of the abstract class. Abstract classes are used as framework upon
which new classes can be built.

// This program demonstrates the use of abstract class


#include<iostream.h>
#include<conio.h>
class B
{
public:
virtual void display()=0;
};
class D1:public B
{
public:
void display()
{
cout<<"\nThis is in derived class D1";
}
};
class D2:public D1
{
public:
void display()
{
cout<<"\nThis is an derived class D2";
}
};
void main()
{
clrscr();
B *Pbase;
D1 Dobj1;
Pbase=&Dobj1;
Pbase->display();
D2 Dobj2;
Pbase=&Dobj2;
Pbase->display();
getch();
In the above program class Base is a abstract class that is used to inherit only and is not used to create objects

IT Brainshapers 12 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Local Class
When a class is defined inside the body of a function is called as a local class. The local class, of course behaves
like all local variables. The class dies a silent death when a function is exited
Consider the following example
//This progarm demonstrates the local class
#include<iostream.h>
#include<conio.h>
void myfunc(void)
{
class Local
{
public:
void display()
{
cout<<"This is the demo of local class";
}
};
Local Obj;
Obj.display();
}
void main()
{
clrscr();
myfunc();
getch();
}
Virtual Function
Through this concept, member functions of the base class can be overridden by the functions of the derived
class. In C++, the keyword virtual is used with the functions, which are to be bound dynamically
The syntax of defining a virtual function is as given below
class classname
{
public:
….
virtual return type function_name( arguments) //Definition of virtual function
{
// body of the virtual; function
}
};

IT Brainshapers 13 Sanjay -7889862407


12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Pure Virtual Function
A pure virtual function is defined in the base class without its body. This is incomplete function which is
completed and refined in the hierarchy of its derived classes. A pre virtual function has no implementation in
the base class .So it is must to be implemented in every derived class. Its derived classes can invoke it.
Syntax
class className
{
public;
…………
virtual returntype functioname (arguments)=0; //definition of pure virtual function
………..
};
// This program demonstrates the Pure Virtual Function
#include<iostream.h>
#include<conio.h>
class B
{
public:
virtual void display()=0;
};
class D1:public B
{
public:
void display()
{
cout<<"\nThis is in derived class D1";
}
};
class D2:public D1
{
public:
void display()
{
cout<<"\nThis is an derived class D2";
}
};
void main()
{
clrscr();
B *Pbase;
D1 Dobj1;
Pbase=&Dobj1;
Pbase->display();
D2 Dobj2;
Pbase=&Dobj2;
Pbase->display();
getch();

IT Brainshapers 14 Sanjay -7889862407


12th Comp Science Unit 4:Pointer Marks 05
Address or Reference Operator (&)
When a variable x is declared in a program, a storage location of main memory is made available by the
compiler as shown below
int x; ≡ x

The memory is allocated automatically by the compiler and operating system at runtime. But once the operating
system has assigned the address to available we have faculty to know its memory address with the help of
reference or address operator which is represented by ‘&’. Suppose x is the name of the variable then &x is
the address. The address of a variable is constant .It cannot be changed during the program execution.
The memory address of the operator is accessed by mean of address operator & e.g. to print the value of
statement is
cout<<&x;
The address operator & operates on the variable name to produce its address
Consider the following program
//This program illustrates the use of Address &
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a = 10;
cout<<"a = "<< a;
cout<<"\n\n Address of a"<<&a;
getch();
}
Concept of Pointer
A pointer, also known as a Pointer variable, is a special variable that holds the memory address, usually the
location of another variable in memory. If one variable contains the address of another variable, the first
variable is supposed to point to the second.
As a pointer stores the actual address of the memory location containing the data value of a variable, the
complier can locate that value in memory very easily.
Let us assume that y is such a variable .Now, the address of variable x can be assigned to y by the statement
y =&x;

2712 1232
int x =15;
x 15 y 2712
y = &x; ≡

From the illustration given above, it is clear that y is the variable that contains the address (i.e. 2712) of another
variable x whereas; the address of y itself is 1232(assumed value). In other words we can say that y is a pointer
to variable x
x y
y
15 *

IT Brainshapers 1 Sanjay -7889862407


12th Comp Science Unit 4:Pointer Marks 05
Declaration of Pointers
A pointer declaration consists of a base type, an *, and the variable name .The general form for declaring a
pointer variable is:
data type * name;
where data type is an valid (the pointer’s base type) data type in C++ such as char, int ,float or double etc.,
and is also known as pointer base type.
The operator * is called indirection operator also known as dereferencing operator,
and name is the name of the pointer, which is written according to the rules for writing of variable names or
identifiers in C++.
For example, the statement
int *ptr;
informs the compiler that the variable ptr is pointer which points to a variable of data type int, to be stored in
memory. The indirection operator (*) informs the compiler that ptr is not an ordinary or automatic variable
but pointer or a pointer variable.
Initialisation of Pointers
Pointer is always initialized with an address of any variable by using & symbol. The compiler allocates the
required memory and returns the base address back.
Syntax:
Pointer_variable =& variable;
For example:
int i = 25; //declare an int variable i
int *iptr; //declare and int point iptr
iptr=&i //store the memory address of i into iptr
To understand the above statement, assume that variable i uses memory location 1050 to store its value .And the
value is stored in i is 25,then after the preceding assignment ,iptr will have the value 1050.
.

Working of & Operator


The second pointer operator,* does, the reverse of &.The unary operator * returns the value of the variable
located at the address followed by (*) .For example, if iptr contains the memory address 1050, then * iptr
will return the value stored in location 1050

The pointer variable must not remain uninitialized since uninitialized pointer causes the system crashing. Even
if you do not have any legal pointer value to initialize a pointer, you can initialize NULL pointer value.
Assigning NULL to a pointer initialize it to a value which is not a legal pointer but it saves you from the ‘Big’

IT Brainshapers 2 Sanjay -7889862407


12th Comp Science Unit 4:Pointer Marks 05
problem of uninitialized pointers. A program can later test a pointer against NULL (the zero pointer) to see
whether it contains a legal pointer or not. For example, consider the following code snippet:
int *iptr= NULL //iptr gets initialized but does not point to a legal address
if(iptr!-= NULL)
{
}
The expression (iptr!=NULL) is equivalent to(iptr)
//This program demonstrates the initialization procedure in C++
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,q;
int *p;
num=100; // num is assigned 100
p=&num; // p receives num's address
q=*p; // q is assigned num's value indirectly through p
cout<<q; // prints 100
getch();
}
Use of Pointers
A pointer helps in traversing an array.
Pointers are used to pass arguments to functions by reference. The arguments may be array or string.
Pointers are used to obtain memory from system using the dynamic memory allocation operator new.
Pointers can return memory to the system using the dynamic memory allocation operator delete.
Pointers are used for the creation of data structure like linked list.
Dynamic and Static Allocation of Memory
The golden rule of computers states that anything (data or instruction) that need to be processed must be loaded
into internal memory before its processing takes place. Therefore, every data and instruction that is being
executed must be allocated some area in the main (internal) memory. The internal memory is allocated in two
ways: statically and dynamically
Static Memory Allocation
When the amount of memory to be allocated is known beforehand and the memory is allocated during
compilation itself, it is referred to as static memory allocation. For instance, when you decree a variable as
follows:
int age;
then in such case the computer knows that what is the length of a int variable. Generally it is 2 bytes. So, a
chunk of 2 bytes internal memory will be allocated to age during compilation it self. Thus, it is an example of
static memory allocation.
Dynamic Memory Allocation
When the amount of memory to be allocated is not known beforehand rather it is required to allocate(main)
memory as and when required during runtime(when the program is actually executing) itself, then, the
allocation of memory at run time is referred to as dynamic memory allocation.

IT Brainshapers 3 Sanjay -7889862407


12th Comp Science Unit 4:Pointer Marks 05
C++ offer two operators for dynamic memory allocation new and delete. The operator new allocates the
memory dynamically and returns a pointer storing the memory address of the allocated, memory. The operator
delete decollates the memory (the reverse of new) pointed by the given pointer.
Memory Management or Dynamic memory allocation operator
Memory management is very critical and in C++, new operator and delete operator are provided, which give
better control on dynamic management.
New and delete operators internally call same old malloc /free. But they are called by new and delete
operators, which call object constructor and destructor for ionization and clean up.
The New Operator
In order to request dynamic memory, the new operator is used. The new operator is followed by a data type and
optionally the number of elements required within brackets [].It returns a pointer to the beginning of the block
of assigned memory
Syntax
pointer =new type ;
or
pointer=new type[Number of elements];
The first expression is used to assign memory that will hold one single elements of a data type.
The second one is used to assign a block (an array) of an element a data type.
For example:
int *p;
p= new int[3];
In this case, space for 3 elements of type integer is assigned in memory and it has returned a pointer that has
been assigned to variable p.
The Delete Operator
Since the dynamic memory is required only for certain moments within a program, as soon as it is no longer
required, it should be freed, so that it becomes available for future request. For this purpose delete can be used
whose form is:
Syntax delete pointer;
or
delete[] pointer;
The first expression should be used to delete the memory allocated for a single element,
The second one for the memory allocated for multiple elements (array).
//This program demonstrates the new and delete operator for(i=0;i<n;i++)
#include<iostream.h> {
#include<conio.h> cin>>*(p+i);
void main() }
{ cout<<"\nElements entered are \n";
clrscr(); for(i=0;i<n;i++)
int i ,n,*p; {
cout<<"Enter array size "; cout<<*(p+i)<<"\n\n";
cin>>n; }
p = new int[n]; delete p;
cout<<"\n\nEnter array element\n";
getch();
}

IT Brainshapers 4 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
Array
Array is similar type of data collection name i.e. it is a collection of same data type elements. An array is a
group of related data items, which share common name .It is a set of homogeneous data.
e.g. a list of marks of 10 students can be grouped as shown
0 1 2 3 9
Marks 10 20 40 34 ……. …….. ……. 34

Name of the marks[2] marks[9]


array
The list shown in Figure is an example of an array called marks which is a set of 0 to 9 memory locations
sharing a common name i.e. marks. The individual element within the array can be designated by an integer
known as subscript or index number .e.g. the marks of 3rd student in the list will be referred to as marks [2] and
the marks of the Ist student in the list as marks [0].
The individual elements of an array are called subscripted variables .marks [2] and marks [0] are example of
subscripted variables of array marks with subscripted 2 and 0 respectively. A subscript can be integer or a
variable of integer type
The syntax to define or declare array is:
data-type array-name [size];
The data type of array elements is known as the base types of the array
Following statement declares an array mark of base type int and which can hold 10 elements
int marks[10];
The above statement declared an array marks have 10 elements, marks [0] to marks [9].
Memory Allocation in Array
Element a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Address 1000 1002 1004 1006 1008 1010 1012 1014 1016 1018
Types of Array
Array mainly of two types
i) Linear Array
ii) Non-Linear Array

Array

Linear Array Non-Linear Array

One or List or Single Two Dimensional Three Dimensional N-Dimensional or


Dimensional Multi Dimensional
i) Linear Array (One Dimensional Array.)
This types of array is also called one Dimensional Array. This is also called the list array. Another name of
linear array is called single–dimensional array. These arrays are of ladder type. In the linear array only one
subscript is used .It is written either in row or in column form. The syntax to define or declare linear array is:
data-type array-name [size];
where data types are integer(int),real(float),double and character (char);
e.g some of the valid one dimensional array declaration statement s are written as bellow:
int a[5];
float salary[30];
char name[20];
We can declare these numbers in the array form as:
int a[5];
So when assign different values to be declared array-name, then it can be written (in the computer memory) as:
a[0]=55
IT Brainshapers 1 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
a[1]=35
a[2]=40
a[3]=47
a[4]=33
Memory Allocation in Array
Element a[0] a[1] a[2] a[3]
Address 1000 1002 1004 1006

Another name of declaration of array which have fixed or constant value is defined as:
e.g the above said different values can be assigned to the array as :
static int number[5]={55,35,40,47,33};
ii) Non-linear Array:
Non-linear array are further subdivided into n categories as:
a) Two Dimensional Array
b) Three Dimensional Array
c) N Dimensional Array
a) Two Dimensional Array
These arrays are also called double dimensional array or two subscripted array. Another name of two
dimensional array is Tabular or Rectangular Array. These array are in row and column form. So it is called
Row-Column or Square Array. These arrays have two subscripts. We can write the double dimensional array in
tabular form as :
a00 a01 a02 … a0n
a10 a11 a02 … a0n
… … …
an0 an1 an2 … ann

The general syntax used for declaration of two dimensional array is as:
data-type array-name [row size] [column size];
e.g. Some valid declarations are :
int a[10][10];
float b[50][50];
char name [10][20];
Also we can declare two dimensional array in static form i.e. these types of array declarations have fixed or
constant values during declaration. The syntax used is as follows:
static data-type array-name [row size] [column size] ={list values};
e.g Suppose if we want to assign some constant or fixed values to array variables name table then it can be
represented as;
static int table[2] [3] ={5,7,12,2,20,8};
The above declared data be assigned to different array variables are as:
table [0][0] =5
table [0][1] =7
table [0][2] =12
table [1][0] =2
table [1][1] =20
table [1][2] =8
b) Three Dimensional Array
Three Dimensional Array is also called space array or xyz array. As it has three subscripts, so these are also
called triple dimensional array. The general syntax used for declaration of three dimensional array is as:
data-type array-name [space size][row size] [column size];
e.g. It can be declared as:
int st [5][2][3];

IT Brainshapers 2 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
Suppose there are five students in a class and get different marks in three subjects in two house tests, then their
marks to be displayed by using three dimensional array is as :
st[1][1][1]=20,st[1][1][2]=22, st[1][1][3]=25, st[1][2][1]=5
st[1][2][2]=35,st[1][2][3]=22, st[2][1][1]=25, st[1][2][1]=50,…………st[5][2][3]=44
c) N-Dimensional or Multi-dimensional Array
This type of array has n size of rows, columns and spaces and so on. The syntax used for declaration of this type
of array is a follows:
data-type array-name [s1[s2]……..[sn];
In this sn is the nth size of the array .This type of array is less used in C++ language.
Lower and Upper Bounds
The smallest element of the array„s index is called its Lower Bound and will be represented by LB in the
problems and algorithms that follow. Similarly, the index of the highest element of the array is called Upper
Bound and is represented as UB.
In general, N the number of elements, also known as range, is given by
Range or N= UB-LB+1
Example 1 Calculate the range of an Array A whose elements are A(5),A(6),A(7),A(8) ,A(9),A(10) and A(11)
Sol
It is given that UB =11, LB =5
Therefore, Range = 11-2+1 =7
Address Computation of Elements
The array declaration instructs the computer to reserve and assign a block of consecutive memory locations to
the elements of the given array. The memory is sufficient to store all the components of the given array. The
address of the first element is called Base Address of the array and is commonly denoted by BA. The address
or location of the element A(K) can be calculated by the operating system in terms of the base address by using
the relation
Location of A(K)= BA+ W(K-LB)
where LB is lower bound of the given array A and W is the size of array element
Example1 An array HEIGHT consists of 5 real elements. Each element requires three memory words for
storage. Calculate the location of the fourth element of the array HEIGHT if the base address is 1000
Sol Its is given that
BA =1000 LB =1 W=3
We know that Location of A (K) =BA+W (K-LB)
Therefore, Location of HEIGHT [4] = 1000 + 3(4-1)
= 1000 + 3× 3
= 1000 + 9
= 1009
HEIGHT (4) occupies three memory locations starting from 1009 or it occupies memory locations 1009, 1010,
1011
Example2 Consider the single dimensional array B[35] having base address 300 and 4 bytes the size of each
elements of the array. Find the address of B[10]
Sol Its is given that
BA =300 LB =0 W=4
We know that Location of A (K) =BA+W (K-LB)
Therefore, Location of B [10] = 300 + 4(10-0)
= 300 + 4 × 10
= 300 +40
= 340
The address of B[10] is 340
Example 3 What will be the address of 6th element in a integer array? The array is specified as emp[30] the
base address of array is 1200
Sol Its is given that
BA =1200 LB =0 W=2
We know that Location of A (K) =BA+W (K-LB)
IT Brainshapers 3 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
Therefore, Location of emp [5] = 1200 + 2(5-0)
= 1200 + 2 × 5
= 1200 + 10
= 1210
The address of A[5] is 1210
Various Operations on One Dimensional Array
There are various operations that can be performed on one dimensional array. The data processing in array is
easy as the elements of the array are stored at contigeous memory locations .Following are some basic
operations that can be performed on arrays
Operation

Traversal Search Sort Insertion Deletion Merging

Linear Binary Insertion Selection Bubble


Traversal in an Array
Traversing linear arrays means accessing and processing each element of the array exactly once. This operation
is used for the following purpose.
Counting the number of elements of the array.
Printing the contents of the elements of the array.
Arranging the elements in ascending or descending order.
Algorithm Steps: 1 N=0
2 process SERIES[N]
3 N=N+1
4 If(N<M-1) repeat steps 2and 3
5 END
// This program illustrates the traversal in an array
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int marks[50],i,n;
cout<<"Enter the no of students:";
cin>>n;
cout<<"\nEnter the marks\n";
for(i=0;i<n;i++)
{
cin>>marks[i];
}
cout<<"\nMarks of students are\n";
for(i=0;i<n;i++)
{
cout<<marks[i];
cout<<"\n";
}
getch( );
}

IT Brainshapers 4 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
Insertion of Elements in an Array
Insertion is the process of adding a new element at a particular location in an array. An element can be added
very easily at the end of the list in the array provided the space is available. On the other hand if it is desired to
insert an element at ith location of the array then all the elements from the ith location will have to shifted one
step towards right to accommodate the new element. Consider the following array SERIES

Array SERIES before insertion

In order to insert a value 50 in the array SERIES at location 4, the value from 60 to 100 will have to be shifted
one step towards the right .This means SERIES [9] will get the contents of SERIES [8], SERIES [8] will get the
contents of SERIES [7] and so on till the contents of SERIES [4] are copied into SERIES [5].As soon as the
copying operation ends. SERIES [4] is available for storing the incoming value 50.The necessary shift
operations are:
SERIES [9] =SERIES [8]
SERIES [8] =SERIES [7]
…………..
SERIES [5]=SERIES[4]
When all elements have been shifted, the following assignment operation stakes place:
SERIES [4] =50
The array SERIES after the insertion operation is:

Array SERIES before insertion


Algorithm foe Array Insertion
INSERT (SERIES, L, K, ITEM)
The following algorithm inserts an ITEM in an array SERIES [N] at the Kth location K being less then or equal
to L. The location of the last element is L. The array SERIES has L elements
Steps: 1 IF (L<N) then BACK= L+1 ELSE STOP
2 While(BACK>K) repeat steps 3 to 4
3 SERIES[BACK]=SERIES[BACK-1]
4 BACK=BACK-1
5 SERIES[BACK]= ITEM
6 L=L+1
7 END
After insertion, the last element of SERIES will be at the L+1th location
//This program shows the insertion of element in an array if(k<49)
#include<iostream.h> {
#include<conio.h> back=n;
void main() while(back>k)
{ {
clrscr(); series[back]=series[back-1];
int series[50]; back--;
int n,back,i,l,k,item; }
cout<<"Enter the size of the list"; series[back]=item;
cin>>n; n++;
cout<<"\nEnter the list:\n"; cout<<"The final list after insertion is :\n";
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
cin>>series[i]; cout<<series[i]<<"\n";
} }
IT Brainshapers 5 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
cout<<"\nEnter the value to be inserted: "; }
cin>>item; else
cout<<"Enter the location relative to zero location: "; cout<<"Insertion not possible";
cin>>k; getch();
}
Deletion of Elements form an Array
Deletion is the process of removing an element from an array. It is easier to delete an element from the end of
the array. If it is required to delete an element from a desired location of the array, then all the elements form
that location onwards will have to be shifted one step towards the left as shown in the figure.

Array SERIES before deletion

After deleting the values 45 from the array SERIES at location 4, the values from 50 to 100 will have to be
shifted one step towards left. This means SERIES [9] will get the contents of SERIES [10],SERIES[8] will get
the contents of SERIES [7] and so on till the contents of SERIES[5] are copied into SERIES [4].The various
shift operations required as:
SERIES [9]=SERIES[10]
SERIES [8]=SERIES[9]
…………..
SERIES [4]=SERIES[5]
The array SERIES after the deletion operation is as shown in the figure:

Array SERIES after deletion


Algorithm for Array Deletion
Here SERIES is an array with N elements and K is a positive integer such that K<=N-1.The following
algorithm deletes the Kth element from SERIES.
Steps: 1 BACK= K
2 While(BACK<N) repeat steps 3 to 4
3 SERIES[BACK]=SERIES[BACK+1]
4 BACK=BACK+1
5 N=N-1
6 END
//Deletion of element from an array item = series[k];
#include<iostream.h> back=k;
#include<conio.h> while(back<n)
main() {
{ series[back]=series[back+1]; //shift left
clrscr(); back++;
int series[50],n,back,i,k,item; }
cout<<"Enter the size of the list"; n--;
cin>>n; cout<<"The final list after deletion is :\n";
cout<<"\nEnter the list:\n"; for(i=0;i<n;i++)
for(i= 0;i<n;i++) {
{ cout<<series[i]<<"\n";
cin>>series[i]; }
IT Brainshapers 6 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
} cout<<"The deleted value is :"<<item;
cout<<"Enter the location relative to zero location: "; getch();
cin>>k; }
k--;//make the location relative to zero
if(k>n)
{
cout<<"\nInvalid location";
return 0;
}

Searching
Searching is one of the common operations that is extensively used in data processing. The search may involve
large amount of data. The search algorithm accepts the key to be searched; the record where to search and the
number of items to be searched .Search can be performed on any of the data structure.
Linear Search (Sequential Search)
It is an operation in which a given array can be searched for a particular value. The location of the searched
element is informed. It is best used if the array we are searching is unsorted .This method of searching is usually
use on small arrays of less than 16 elements. The sequential search is started by first declaring a target to be
found. The search starts with comparing each element one by one with the given value of the element to be
located.
Algorithm
Linear Search (SERIES, ITEM, COUNT)
Here SERIES is an array with N elements, and ITEM is the value to be searched for. The algorithm given below
finds the location POS of ITEM in the array SERIES.
Steps: 1 COUNT =0; LOC= -1;
2 While(COUNT<N) repeat steps 3 to 4
3 IF (SERIES[COUNT]=ITEM) then LOC =COUNT
4 COUNT = COUNT +1
5 Display LOC
6 END
In the above algorithm, the variable COUNT is updated to keep record of the number of elements visited .Each
element of the array is compared with the given value of ITEM. If the match is found, then the location of the
element i.e. current value of COUNT is stored into a variable called LOC.
If there are duplicate values in the array SERIES, then the variable LOC containing the last duplicate value is
printed

//This program demonstrates the Linear Search count=0;


#include<iostream.h> loc=-1;
#include<conio.h>
void main() while(count<n)
{ {
clrscr( ); if (series[count]==item)
int series[20]; loc=count;
int count,loc,item,n,i; count++;
cout<<"Enter the size of the list"; }
cin>>n; if(loc>-1)
cout<<"\nEnter the list:\n"; cout<<"\nThe position of the element w..r.t zero "<<loc;
IT Brainshapers 7 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
for(i=0;i<n;i++) else
{ cout<<"\nUnsuccesful search";
cin>>series[i]; getch();
} }
cout<<"\nEnter the value to be searched: ";
cin>>item;
Drawbacks of Linear Search
In the linear search method, the search starts from the first element and continues in a sequential manner from
element to element till the desired element is found. If the desired element happens to be the last in the array,
the entire search process will have to be repeated N times, where N is the size of the array being searched.
Binary Search
The search can be made faster by an algorithm called binary search. For this algorithm the list or the array
should be sorted in advance .The search uses the technique –divide and conquer. The array is divided into two
halves. Now the desired element is present either in the first half of the array or the second half of the array. The
operation is done successfully until the element is found
Algorithm
Binary Search (SERIES, LB, UB, ITEM, LOC)
Here SERIES is a sorted array with lower bound LB and Upper bound UB.ITEM is the value to be searched for.
The variables BEG, END, MID denote the beginning, end and middle of the array. The algorithm finds the LOC
of ITEM in the array SERIES
Steps: 1 BEG=LB; END=UB; LOC=-1; FLAG= false
2 While(BEG<=END) and Flag=false) perform steps 3 to 5
3 MID=(BEG+END)/2
4 If(SERIES[MID]=ITEM)then [LOC=MID;FLAG=true]
5 If(SERIES[MID]<ITEM)then BEG=MID+1
Else END =MID-1
6 IF(FAG=true) then display LOC
7 Else print “Unsuccessful Search”
8 END.
In the above algorithms, the value of MID is found for the current values of LB and UB .Initial values of LB
and UB are 0 and N-1 respectively. If ITEM is found in the middle position of the array the FLAG is set to
„true‟ and the while loop terminates. If the desired element is not found in the array, a stage arrives when BEG
becomes greater then END and the while loop terminates.

Binary Search

Binary Search Step 1


In the given array SERIES we have to search for a value (say 44) and to find its position in the array .Binary
array begins by checking the middle value of the array. The middle of the array is found by finding the average
of LB and UB i.e.,(0+6)/2=3.Now the value at 3rd location (counting) from 0) is 24.Since the value we are
searching for(44) is greater than 24,it would be present in the second half of the array which ranges from
SERIES[4] to SERIES[6].Now the middle of this half of the array is found by (4+6)/2=5.When we look at
SERIES[5],we find that the desired element(44) exists at position 5(counting from 0).

IT Brainshapers 8 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
//This program demonstrate the Binary Search
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int series[50];
int i,n,loc,item; Binary Search Step 2
int beg,end,mid;
cout<<"Enter the size of the list";
cin>>n;
cout<<"\nEnter the list:\n";
for(i= 0;i<n;i++)
{
cin>>series[i];
}
beg=0;
loc=-1;
end=n-1;
cout<<"Enter the item to be searched: ";
cin>>item;
// Binary Search
while((beg<=end)&&(loc==-1))
{
mid=(beg+end)/2;
if(series[mid]==item)
loc=mid;
else
if(series[mid]<item)
beg=mid+1;
else
end =mid-1;
}
if(loc>-1)
cout<<"\nThe position of the element w..r.t zero is :"<<loc;
else
cout<<"\n Unsuccessful";
getch();
}
In the program given above, the array of size n will be having elements with subscripts ranging from 0 to
n-1.Due t this reason the variable loc is given an initial value of -1.
Limitations
Binary search is a efficient algorithm but it require two conditions to be fulfilled before its use
The list must be sorted.
One must have direct access to the middle element in any sublist.
Sorting
Sorting is the process of arranging data in a particular order (either ascending or descending).Arrays are
convenient for storing many forms of data because they allow the access of any element via its index. There are
several methods of sorting data held in one dimensional arrays .One of the sorting methods is the sequential
methods .Arrays can be sorted sequentially through the following ways
Selection Sort
Bubble Sort
Insertion Sort

IT Brainshapers 9 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
Stack
A stack is an ordered collection of similar item in which, new item may be inserted and from which items may
be deleted at one end, called the top of the stack. Here the last item inserted will be on the top of the stack. Last
item inserted will be the first one to be deleted out of the stack, hence ,it is sometimes called LIFO(Last in first
Out) data structure
Need for Stack
Stacks are used when the order an sequence of processing data needs to be maintained .The statement of a C++
program are arranged in the form of a stack; instructions are executed from top.
When a subprogram is called by the main program, the subprogram is executed first. To enable this order of
processing, the subprograms and the main program have to be suitably stacked in the primary memory by the
operating system.
Pop Push
↑ ↓ ← Top
Most recently received element→
Stack

Earliest received element →

Push Operation
Push is the operation of adding an element to the stack .In performing this operation; one must first test whether
there is a room in the stack for the new item. If there is no room, the stack is said to be in a condition of
overflow.
Top→ T
Top→ S S
Top→ R R R
Q Q Q
P P P

(a) (b) (c)


Push Operation on a Stack

Algorithm for push operation on a stack


In the algorithm, depicting a push operation a linear array SATC is used to implement
PUSH (STACK, TOP, MAX, ITEM)
(Procedure for pushing ITEM into a stack)
Step 1: (Is stack already filled?)
(If TOP = MAX then print OVEFLOW and Exit.
Step 2: else Set TOP=TOP+1(Increase Top by 1);
Step 3: Set STACK [TOP]=Item
(Insert Item in new position of Top);
Step 4: End
0 1 2 3 4 5 6 7 ←Stack
A B C
↑ ↑
Top MAX

IT Brainshapers 10 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
Pop Operation
Pop is the operation of deleting an element the stack .In order to perform this operation, one must first test
whether there is any element in the stack. If not, the stack is in the condition of underflow.
Top→ T
S Top→ S
R R Top→ R
Q Q Q
P P P

Stack before any Stack after Ist Stack after 2nd


pop operation pop operation pop operation
Algorithm for pop operation on a stack
In the algorithm, depicting a pop operation a linear array SATC is used to implement
// C++ implementation of algorithm for Stack if(top>=0)
// Pushing and Popping {
#include<iostream.h> cout<<"\n";
#include<conio.h> for(i=top;i>=0;i--)
#include<stdio.h> {
class stack cout<<stack[i]<<"\n";
{ }
int stack[30]; //stack declaration }
int top; cout<<"\nEnter a key";
int n; //top of the stack getch();
public: fflush(stdin);
stack() }
{ void main()
top =-1; {
n=30; stack objstk;
}//indicates that stack is empty int ch;
void push(int val); int val;
int pop(); do
void display(); {
}; cout<<" \n Menu ";
void stack::push(int val) cout<<"\n";
{ cout<<"\n Push: 1";
if(top<n) cout<<"\n Pop: 2";
{ cout<<"\n Display 3";
top++; cout<<"\n Quit 4";
stack[top]=val; cout<<"\n";
} cout<<"\nEnter your choice: ";
else cin>>ch;
{ clrscr();
cout<<"\nThe stack is full"; switch(ch)
} {
} case 1:
int stack::pop() cout<<"\nEnter the value to pushed";
{ cin>>val;
int v; objstk.push(val);
if(top>=0) break;
{ case 2:
v = stack[top]; val = objstk.pop();
top--; cout<<"\nThe poped value is "<<val;
return v; break;
} case 3:
else cout<<"\n The stack is ";
{ objstk.display();
cout<<"\nStack is empty"; break;
return(-9999); }
} }while(ch!=4);
} getch();
void stack::display() }
{
int i;

IT Brainshapers 11 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
POP (STACK, TOP, ITEM)
(This procedure deletes the top element of the STACK and assigns it to the variable ITEM)
Step 1: (Is there an item in the STACK for removal?)
(If TOP = NULL then print UNDERFLOW and Exit.
Step 2: else Set ITEM=STACK [TOP]
(assigns TOP element to ITEM);
Step 3: Set TOP=TOP-1; (Decrease TOP by 1);
Step 4: End
0 1 2 3 4 5 6 7 ←Stack
A B C
↑ ↑
Top MAX

Applications of a Stack
The applications of stacks are as follows:
1. Conversion of expressions: The mathematical expression written in one form can be efficiently converted
to another form. Example: infix to postfix, infix, to prefix, postfix to infix, postfix to prefix.
2. Evaluation of expression: An arithmetic expression represented in the form of either postfix or prefix can
be easily evaluated.
3. Recursion: A function which calls it is called recursion function. Some of the problems such a tower of
Hanoi, a very important facility available in a variety of programming languages such as C, C++ etc.
4. Other applications: There are so many other applications where stacks can be used .To list a few: to find
whether the string is palindrome, to check whether a given expression is valid or not, topological sort etc.
Queue
A queue is a dynamic linear list in which deletion takes place only at one end called FRONT or HEAD and
insertions take place at the other end called REAR or TALL. Thus, in a queue, unlike stack, the data item
entered first is popped out first and the one entered last is popped out last. It is for this reason that the queue is
called FIRST IN FIRST OUT (FIFO). Thus logical a queue is a FIFO structure and physically it can be
implemented either as an array or linked list.
The railway reservation counter is also an example of queue where the people collect their tickets on the first
come ,first server basis also known as FIOFO i.e First IN First Out
Deletion ← ←Insertion
↑ ↑
Front Rear
Need for a Queue
A queue is a variable size ordered collection of similar objects. There are two main aspects of a queue that make
it attractive for verification purposes.
First, a queue can have variable length, including a length of zero. This makes a queue an ideal candidate
as a storage element that can shrink or grow as elements are deleted or added to it without fixing an
artificial upper limit on its size as a regular fixed size array.
The other advantage of having a queue is that it provides a way to emulate both Last in First Out (LIFO)
and First in First Out (FIFO) behavior that are required in so many order transactions.
IT Brainshapers 12 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
Characteristics of a Queue
The first element inserted in the queue is the first element that can be taken off.
Insertions can be done at one end i.e. rear and deletions can be done at the other end i.e. front.
It looks like an open tube.
The insertion operation of the queue is called append /enqueue operation.
The deletion operation is called serve /dequeue operation.
Push operation on a full queue causes overflow.
Pop operation on an empty queue causes underflow.
The initial value of the front and rear pointer is always -1.
The front pointer points to the starting of the queue.
The rear pointer points to the rear of the queue.
Queue as an Array
When a queue is created as an array, its space required (no of elements) is declared before processing. The
beginning of the array becomes its “front” end and the end of the array becomes its “rear” end .The term “front”
and “rear” are used in describing a liner list only when it is implements as a queue.
“Front” stores the number of first element in the queue and “rear” stores the number of last element in the
queue. The number of elements in a queue at any given time can be calculated from the values of “front” and
“rear”.
If “front”=0 then no of elements =0 else “no-of-element”= front –rear =1
Size Capacity
0 1 2 3 4 5↓ 6 7 8 9 10↓
A B C D E
↑ ↑
FRONT=0 REAR=5 N-1

Operations of Queue
Array representation of a queue
There are two operations applied on queue .they are
Enqueue/Addition
Dequeue/Deletion
Enqueue or Insertion in an Array Queue
Enqueue operations are used to insert a new element into the queue. At the time of insertion first it is checked
whether the queue is full or not. If the queue is full, it generates an error message „queue overflow‟.
When an element is added to a queue, the position of the rear is increased by 1.This is done by the assignment
statement
REAR=REAR+1;
If we keep on adding elements to the queue, then the stage will be reached when the queue cannot hold any
more elements. It is a condition of
REAR = N-1.
This condition is called Queue-Full. Addition from the queue
0 1 2 3 4 5 6 -------------------------------- N-1
A B C D E F
↑ ↑ ↑
FRONT=0 REAR=6

IT Brainshapers 13 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
Dequeue
Dequeue operation is used to delete an element from the queue. At the time of deletion, first it is checked
whether the queue is empty or not. If the queue is empty it generates an error message „queue underflow‟.
When an element is deleted from a queue, the value of FRONT is increased by 1.This is done by the assignment
statement
FRONT=FRONT+1;
Deletion from the queue

0 1 2 3 4 5 6 -------------------------------- N-1
A B C D E F
↑ ↑ ↑
FRONT=1 REAR=6
If we keep on
deleting elements
to the queue, then the stage will be reached where there will be no item in the queue. It is condition of FRONT
= REAR. This condition is known as Queue Empty or Under Flow.
Initially, when the queue is empty, both FRONT and RAER are set to 0, i.e. FRONT = REAR =0

0 1 2 3 4 5 6 -------------------------------- N-1

↑↑ ↑
FRONT=REAR=0 REAR=6

Condition for FRONT=REAR =0


Algorithm for Add and delete operations of a linear queue
Linear Queue Add
In this algorithm ,an one dimensional array Q[N] is used with the variable FRONT and REAR as pointers .An
item „Val‟ is added to Q. If Rear <=N-1,or when the queue is not full
QINSERT(Q,N,FRONT,REAR,TEM)
Step 1: [Is Q already filled?]
if(REAR= N-1 then write OVERFLOW and Exit;
Step 2: Else find a new value of REAR [REAR = REAR +1];
Step 3: If FRONT = Null then [Q is initially empty]
Set FRONT = 0 and REAR =0
Else
Set REAR = REAR +1;[End of if structure ]
Step 4: Set Q[REAR]=ITEM;
Exit
Step 5: End
Linear Queue Delete
QDELETE(Q,N,FRONT,REAR,ITEM)
This procedure deletes an item from a linear queue and assigns it to the variable ITEM
Step 1: [Is Q already empty?]
if(Front= Null then write UNDERFLOW and Exit;
Step 2: else set ITEM =Q[FRONT] (Copy the contents into the variable ITEM)
Step 3: [Find new value of Front]

IT Brainshapers 14 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
If FRONT = REAR then
Set FRONT = NULL ad REAR = NULL
[Q has only one element and so emptied]
Else Set FRONT = FRONT +1 [End of if structure]
Step 4: Exit;
Step 5: End.
If we keep on deleting from a queue, then stage may arrive when both FRONT and REAR are equal to N-1
leaving the queue useless. Therefore, in such a situation both the pointers are reset to initial condition by
FRONT =REAR=0.BY resetting the pointers, the queue available for further usage.
// C++ implementation of algorithm for Queue cout<<Queue[i]<<"\n";
// Addition and Deletion }
#include<iostream.h> }
#include<conio.h> }
#include<stdio.h> void main()
#include<process.h> {
class Queue clrscr();
{ Queue objQ;
int Queue[30],n ; //Queue declaration int val;
int front,rear; //Front and Rear declaration int ch;
public: int size;
Queue() //Constructor cout<<"Enter the size of Queue";
{ cin>>size;
front=rear=0; //Indicates that the Queue is empty do
n=29; {
} cout<<"\n Menu ";
void add(int val,int size); cout<<"\nAdd 1";
int delet(); cout<<"\nDelete 2";
void display(); //protype for function; cout<<"\nDisplay 3";
}; cout<<"\nQuit 4";
void Queue::add(int val,int size) cout<<"\n";
{ cout<<"\nEnter your choice : ";
if(rear<size) cin>>ch;
{ clrscr();
Queue[++rear]=val; switch(ch)
} {
else case 1:
{ cout<<"\n\nEnter the value to added ";
cout<<"\n The Queue is full"; cin>>val;
} objQ.add(val,size);
} break;
int Queue::delet() case 2:
{ val=objQ.delet();
int v; cout<<"The deleted value is "<<val;
if(front!=rear) break;
{ case 3:
v=Queue[++front]; cout<<"\n The Queue is ....";

IT Brainshapers 15 Sanjay -7889862407


12th Comp Science Unit 5: Data Structure Marks 10
return v; objQ.display();
} cout<<"\nEnter the key";
else getch();
{ fflush(stdin);
cout<<"\n Queue is empty"; break;
return(-9999); case 4:
} exit(1);
} break;
void Queue::display() default:
{ cout<<"Out of choice";
int i; break;
if(front<rear) }
{ }while(ch!=4);
cout<<"\n"; getch();
for(i=front+1;i<=rear;i++) }
{
Drawbacks of Queue
For each and every enqueue operation, the queue needs to be rearranged .Moreover; it is not possible to utilize a
queue having an empty space.
Applications of Queue
Queue can be used to store the interrupts in the operating system.
It is used by an application program to store the incoming data, which determines the order in which it is
be processed.
Queues are used for processes synchronization in OS.
Queues are used for job scheduling.
Linear Queue
A queue is FIFO dynamic data structure whose function can be termed as FIFO (First In First Out).A sequence
requires frequent additions and deletions at the rear end and front end respectively, it is worthwhile
implementing it using a linked list.
The structure of a node of linked queue has two parts INFO and NEXT as shown below:

INFO NEXT

Two pointers FRONT and REAR keep count of the front end and rear end of the queue.
FRONT REAR

NULL

Operations on Linked Queues


Nodes can be added or deleted queue.
Algorithm for addition of a node to a linked queue
In the given algorithm, a node ITEM with value as the information part is added to a linked queue. FRONT and
REAR are two pointers which hold the addresses of the front end and rear ends of the queue respectively. If the
condition REAR=NULL is true the queue is considered to be empty.
Step1 : ITEM= new NODE
IT Brainshapers 16 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
Step2: INFO(ITEM)= VALUE;
Step3: NEXT(ITEM)=NULL;
Step4: if(REAR=NULL) then [REAR=ITEM;FRONT=REAR]
else [NEXT(REAR)=ITEM];
REAR=ITEM;
Step5: END
The linked queue after an addition operation as shown in the figure
Algorithm for deletion of an element or node from a linked queue
In the given algorithm, a node is deleted from the fond end of the linked queue. After the deletion operation the
condition FRONT=NULL is checked .If the condition is true, the queue is considered to be empty.
Step1 : if (FRONT = NULL) then [Print “Queue is empty”; STOP;]
Step2: ITEM=FRONT
Step3: FRONT=NEXT (FRONT)
Step4: VALUE=INFO (ITEM)
Step5: Delete ITEM
Step 6: if(FRONT=NULL ) then REAR=NULL
The linked queue after an addition operation as shown in the figure

IT Brainshapers 17 Sanjay -7889862407


12th Comp Science Unit 6: Databases and SQL Max Marks 10
Introduction to Database
Field
Field is a basic entry or a data elements. such as the Thus NAME, CITY, AGE, STATE, PIN_CODE .
Record
The collection of related fields is called a record. For example Figure contains six records and each record
has five related fields, NAME, LOCALITY, CITY, STATE and PIN_CODE
File
File is the collection of all related records .In figure the file contains the list of addresses of six friends.
Database
Database is a collection of related files. Employee database having related filers containing records of
employee
Database is composed of a collection of files that are linked in such a way that information from one of the
files may be combine with information from other files so that a user may receive the exact information
needed or
A data base may be defined as a collection of interrelated data stored together without harmful or
unnecessary redundancy to serve multiple applications; the data are stored so that they are independent of
programs which use the data common & controlled approach is used in adding new data in modifying &
retrieving existing data within the data base
Components of Database
A database system involves four major components: data, hardware, software and users.
DBMS stands for Database Management System. A DBMS consists of collection of interrelated data
and a set of program to access that data. The collection of data is known as a database. A database consists
of the data related to one organization. Prior to DBMS systems, the data was kept under the file system in
forms of multiple files. The following are the disadvantages of the File system:-
Difficulty in Accessing data:- In the file system it is very difficult to find the data which is needed for
some specific purpose. Like to get the average sale of the quarter needs to process all files for the quarter
and then do some processing.
Data inconsistency and redundancy:- As the files and processing systems created by different vendors
and programmers, so there is a inconsistency of data as different people prefer the different style of data
handling. Also the different systems may use the different programming languages to develop the
processing systems so the multiple copies of the same file kept under various places so redundancy is
another problem we have with file system.
Security Problem:- There is a great risk of unauthorized person access the file system and get the data.
So security is the major concern in the file system.
Integrity Problem:- The integrity issue is also a major concern as the data stored in the file can be
changed easily. While creating files there is no specific rules checked while storing the data.
Advantages of Database Management System:-
Shared Data
Sharing of data mean that individual piece of data in the database may be shared among several different
users ,in the sense that each of those user may have access to the same piece of data and each of them may
use it for different purpose
Control Data Redundancy
Data is recorded in only one place in the database and it is not duplicated.
Data Consistency
Data item appears only once, and the updated value is immediately available to all users

IT Brainshapers 1 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Control over Concurrency
In a computer file based system in updating, one may overwrite the values recorded by the others.
Better Data Security
Data security is the protection of database from an unauthorized access. DBMS allows to keep the data
confidential by providing different levels of security e.g. Manager can be allowed to access the salary of
an employee but the employee other than manager are not allows to access the salary of the employee
Better data accessibility
DBMS allows online access by user by providing query language that permits users particular non-
programming personal to ask question and obtain information as needed without the help of any
programmer
Standard can be enforced
With central control of the database, the DBA can ensured that all applicable standards are followed in the
representation of the data, such as format of data items, conventions on data names ,documentation
standards etc, which will result in uniformity of the entered database as well as its usage .
Interface with the past
Organizations which have been using data processing for some time having a major investment in their
existing programs, procedures and data. When an organization install new database software it is
important that it can work with the existing programs & procedures and that the existing date can be
converted .This need for compatibility can be major constraint in switching to a new database system
Better backup and recovery procedure
Automatically create the backup of data of data and restore if required. Whenever the database is
modified, a log entry is made .If the system fails, the tape and log is used to bring the database in original
state it was in before failure
Data Independence
Because of Physical data independence the file may migrate from one type of physical media to another or
the file structure
Disadvantages
Cost of hardware and Software Processor with high speed of data processing and memory of large size
is required .
Cost of Data Conversion Very difficult and costly method to convert data of data file into database.
Cost of Staff Training A lot of amount for the training of staff to run the DBMS
Appointing Technical Staff Trained technical persons such as DBMS Administrator ,application
programmer, data entry operators etc. are required to handle DBMS.
Database Damage All data is integrated into single database>if database is damaged due to electric
failure or corrupted on the storage media, then your valuable data may be lost forever.
Data Model
A data model is a collection of conceptual tool for describing data, data relationship, data semantics. Data
models describing the organization of different objects namely, records, data dictionary elements etc. Data
Models can be classified into following categories
1 Relational Model Normalize Structure
2 Network Model Plex Structure
3 Hierarchical Model Tree Structure

IT Brainshapers 2 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
1 Relational Model:
The relational model represents data and relationships among data by a collection of tables known as
relation each of which has a number of columns with unique name. Rows of the table are referred to as
tuples and the columns of a table are referred to as attributes.
Advantages: The advantages of this model are:
Since tabular structure is simple and familiar, it is easy to understand.
Data manipulation is easy.
We can apply mathematical operations on tables.
Built in query language support on RDBMS, is available.
Very flexible data organization..
Limitation : The major limitation of this model is that size of database becomes large
Example : Oracle ,Ingres, Sql Server 2000,Unity,My Sql
St_Code St_Name St_Age St_Class
S101 Raj 16 5th
S102 Neha 17 4th

St_Code Course_Code Course_Name Marks


S101 C101 English 70
S102 C102 Arts 80

St_Code St_Name St_Age St_Class Course_Code Course_Name Marks


S101 Raj 16 5th C101 English 70
S102 Neha 17 4th C102 Arts 80

2 Network Model :
The network model represents data by collection of records and relationship among data is
represented by links which can be viewed as pointers. The records in the database are organized as
collection of arbitrary graphs.
School

Science Computer Arts

Fee

Attend Attend Attend

Network Data Model

IT Brainshapers 3 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Advantages: The advantages of this model are:
Many to many relationship can be implemented.
Easier access compared to hierarchical model.
Limitations: The limitations of this model are as under
1. Number of links tends to be extremely large as the complexity increase.
2. New queries cannot be implemented.
3. Extra storage is required for pointers.
4. A high level language is needed to program the database.
5. General purpose Query facility not available .
Examples : UNIVAC‟s ,DMS 1100 and DBMS 10-20 from DEC
3 Hierarchical Model :
Hierarchical model is similar to the network model in the sense that data and relationship among data are
represented by records and links respectively. It differ from the network model is that the records are
organized as collection of trees rather than arbitrary graph. The restriction being that a child can have only
one parent.

School

Science Computer Arts

Attend Fee Attend Fee Attend Fee

Hierarchical Data Model

Advantages: The advantages of this model are:


1. Simple and easy to use.
2. Data with hierarchical relationships can be naturally mapped on this model.
3. One to many relationship can be implemented
Limitations: The limitations of this model are as under
1. Non- hierarchical relationships are difficult to map on this model.
2. Selection of parent deletes its children nodes.
3. Change of relationship requires changes in the entire structure of the database.
Examples : IBM‟s IMS (Information management System) and System 2000
Comparison of the Three Models
SNo Hierarchical Network Relational
Data Model Data Model Data Model
1. Relationship between Relationship between Relationship between records
records is of the parent records is expressed in the
is represented by the relation
child type. form of pointers or links that contains key for each
record involved in the
relationship.
2. Many to Many Many to Many relationship Many to many relationship
relationships cannot be can also be implemented can be easily implemented
expressed.
3. It is simple, straight Record relationship Relationship implementation
forward and natural method implementation is very is very easy through the use of
of implementing record complex due to the use of key or composite key field.
IT Brainshapers 4 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
relationships pointers.
4. This type of model is Network model is useful forRelationship model is useful
useful only when there is representing such records for representing most of the
some hierarchical character which have many-to many real world objects and
in the database. relationships. relations among them.
5. In order to represent links In Network model also the Relational model does not
among records, pointers are record relations aremaintain physical connection
used. Thus relations among physical. among records. Data is
records are physical. organized logically in the
form of rows and columns
and stored in table
6. Searching for a record is Searching a record is easy A unique indexed key field is
very difficult since one can since there are multiple used to search for a data
retrieve a child only after access paths to a data element.
going through its parent element.
record.
7. During updation or deletion No problem of Data integrity maintaining
process, chances of data inconsistencies exists in method like Normalization
inconsistencies is involved Network model because a process etc are adopted for
data element is physically consistency
located at just one place

Database System Architecture

Sales Officer Purchase Office r

View 1 View 1 External Level


Item_Name Item_Name (Individual User Views
Price Price

(Application Programs are


used to fetch the desired
information
Conceptual
Item_Number Charcter(6)
Item_Name Charcter(20)
Price Numeric(5+2)
Reorder_quantity Numeric(4)

Internal
Stored-Item Length(40)
Item_Number Type=Byte(6), offset=0,Index=Ix
Item_Name Type=Byte(20),offset=6
Price Type=Byte(8), offset=26
Numeric(5+2) Type=Byte(4), offtset=34
Reorder_quantity Numeric(4)

A database is implemented through three general levels:


Internal Level (Physical Level)
The lowest level of abstraction, the internal level, is the one closest to physical storage.This level is also
sometimes termed as physical level. It describes how the data are actually stored on the storage medium.
At this level, complex low-level data structure are described in details.
Conceptual Level
This level of abstraction describes what data are actually stored in the database. It also describes the
relationships existing among data. At this level, the database is described logically in terms of simple data-
structure.

IT Brainshapers 5 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
External Level (View Level)
This is the level closest to the users and is concerned with the way in which the data are viewed by
individual users. Only a part of the database relevant to the users is provided to them through this level.
Data Independence
The ability to modify a scheme definition in one level without affecting a scheme definition in the next
level is called data independence .Data Independence implies that the data and application programs
which use them are independent so that either may be changed without changing the other. There are two
types of data independence .They are
1. Logical Data Independence
2. Physical Data Independence
1. Logical Data Independence
Logical data independence means that the overall logical structure of the data may be changed without
changing the application programs. The change must not of course remove any of the data of the
application program‟s use.
2. Physical Data Independence
Physical data independence means that the physical layout and organization of the data may be changed
without changing either the overall structure of the data or application programs.

Conceptual
Model of a Database
Logical
Data Independence
Logical
Model of a Database
Physical
Data Independence
Physical
Model of a Database
Codd's Rules for Relational Databases.
E.F. Codd, the famous mathematician has introduce 12 rules for the relational model for databases
commonly known as Codd's rules. The rules mainly define what is required for a DBMS for it to be
considered relational , i.e., an RDBMS. There is also one more rule i.e. Rule00 which specifies the
relational model should use the relational way to manage the database. The rules and their description is as
follows:-
Rule 000: A RDBMS system should be capable of using its relational facilities (exclusively) to manage
the database.
Rule 1: The information rule : All information in the database is to be represented in one and only one
way. This is achieved by values in column positions within rows of tables.
Rule 2 : The guaranteed access rule : All data must be accessible with no ambiguity. This is achieved in
the RDBMS by using the primary key concept.
Rule 3: Systematic treatment of null values : The DBMS must allow each field to remain null. The null
can be stored in any field of any datatype.
Rule 4: Active online catalog based on the relational model : The authorized users can access the database
structure by using common language i.e. SQL.

IT Brainshapers 6 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Rule 5: The comprehensive data sublanguage rule : The system must support at least one relational
language that has simple syntax and transaction management facilities. It can be used in the application as
well as in the RDBMS systems.
Rule 6: The view updating rule : All views must be updatable by the system.
Rule 7: High-level insert, update, and delete : The system is able to insert, update and delete operations
fully. It can also perform the operations on multiple rows simultaneously.
Rule 8: Physical data independence : Changes to the physical storage structure must not require a change
to an application based on the structure.
Rule 9: Logical data independence : Changes to the logical level (tables, columns, rows, and so on) must
not require a change to an application based on the structure.
Rule 10: Integrity independence : All the Integrity constraints like primary key, unique key etc must be
specified separately from application programs and stored in the catalog.
Rule 11: Distribution independence : The distribution of portions of the database to various locations
should be invisible to users of the database.
Rule 12: The non subversion rule : If the system provides a low-level (record-at-a-time) interface, then
that interface cannot be used to subvert the system, for example, bypassing a relational security or
integrity constraint.
Note:- Any database management system which fulfills 6 or more than 6 rules can be considered as the
RDBMS.
Relational Data Structure
Entity:
Entity is an object that exists and is distinguishable from other objects.
e.g Employee
Entity Attribute Value
Name = Raj

Employee Address = Udhampur

Age = “27”
Entity Set: An entity set is a set of entities of the same type i.e. which share common properties or
attribute
Relation: All data and relationship are represented in a two dimensional table called relation. e.g. the table
shown in figure
A database constructed using relation is referred to as Relational database. Relational database is
constructed from flat arrangement of data items
In following fig there is Person Information. Relation that describe the Student by SNo, Name ,Class
Address
Student
Attribute SNo Name Class Address
1 Raj XI Udhampur
2 Sudha X Jammu
Tuple 3 Sudhir XII Kathua
4 Sita XI Jammu
5 Rahim X Udhampur

IT Brainshapers 7 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Properties of Relation
In a table ,the order of row is immaterial
Order of column is immaterial
In a table, there are no duplicate rows.
Each row of the table contains only one value
Each column is assigned with a distinct heading
Attribute: The column of table (relation) are called attributes.
Tuple : The rows of the table are called tuple .
Name: Name is represented by the title.
Cardinality: The no. of rows in the table is called cardinality.
Degree: The no. of column in the table is called degree.
Domain: A domain is a collection of all possible values from which for a given column or
attributes is drawn .e.g Class values (IX,X,XI,XII)
Student
SNo Name Class Address
6 Raj XI Udhampur
7 Sudha X Jammu
8 Sudhir XII Kathua
9 Sita XI Jammu
10 Rahim X Udhampur
Attribute: SNo,Name ,Class,Address.
Name: Student.
Cardinality: 5
Degree: 4
Types of Relation
There are two type of relation.
Base Relation
The base relations are those relations which are created prior to use. They are also called as „table‟ and
existing as Physical file.
Derived Relation
The derived relations are those relations which are derived from a base relation. They do not exist as
physical file .The derived relations are also called as Views.
Keys in DBMS
The key is defined as the column or attribute that exclusively identifies a record e.g. EmpNo, RollNo etc
are used as key fields because they identifies a record structure stored in a database of the database table.
For example if a table has id, name and address as the column names then each one is known as the key
for that table. We can also say that the table has 3 keys as id, name and address. The keys are also used to
identify each record in the database table. The following are the various types of keys available in the
DBMS system.
Consider a relation STUDENT, having column SRNo,RegNo,Name ,Class,City
SRNo RegNo Name Class City
S01 DSE101 X BCA Udhampur
S02 DSE102 Y BCA Reasi
S03 DSE103 Z BBA Jammu
S04 DSE104 W MCA Ramnagar

IT Brainshapers 8 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Primary Key
An attribute which recognizes tuple uniquely is called a primary key
e.g SRNo is a Primary key.
Primary key can have more than one attribute such as type of key is called Concatenate key
e.g FlightNumber + Date
Secondary Key
Secondary key recognize the tuple but not uniquely. So secondary key recognizes the set of records
(tuples) e.g. Name, Class and City are the Secondary keys in Student relation.
Candidate Key
There may be more than one attribute in a relation such that they recognize a tuple uniquely (i.e. each of
the attribute have the property of primary key).These attributes are called candidate key. In such case, one
of the candidate key is chosen to be Primary key. The remaining candidate keys are called a Alternate key.
There is one Primary key in a table e.g In STUDENT relation SRNo and RegNo are the candidate key.
Alternate Key
From the candidate keys, we choose one as the primary key. Now candidate key which do not primary key
is called alternate key.
e.g If we choose SRNo as a primary key, then RegNo is the alternate key.
Foreign Key
A foreign key is an attribute (or set of attributes) that appears (usually) as a non key attribute in one
relation and as a primary key attribute in another relation.
Employee
EmpNo Name Age DeptNo
E01 X 21 10
E02 U 22 20
E03 Z 26 30
E04 Y 23 10
Department
DeptNo DLocation
10 Jammu
20 Udhampur
30 Kathua
In the example DeptNo is a foreign key in Employee but it is Primary key in Department
Super Key
A set of attributes is called Super key, if it recognizes the tuple uniquely.
e.g. SRNo + Name + City is a super key.
Every relation has atleast one default superkey i.e. the set of all its attributes. A super key can have
redundant attributes. A primary key or a key is a minimal superkey i.e a super key from which we cannot
remove any attributes and still have the uniqueness property.
Relational Algebra
Relation Algebra uses a procedural query language which is collections of operations to manipulate
relations. It consist of a set of operations take one or more relations as input and produce new relation as
their result.
Relation algebra can be divided into two types of operations
Set Oriented Operation
a) Union b) Difference c) Intersection d) Cartesian Product
Relational Oriented Operation
a) Join b) Selection c) Projection d) Division

IT Brainshapers 9 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Set Operation
Set Union
The result of union operation is denoted by the symbol U.
e.g. X U Y(when X and Y are two compatible relations) is a relation that include all tuples that are either
in X or in Y or Both X and Y).Duplicate tuples would be eliminated by using set union
e.g if X and Y are two relation
X Y XUY
abc cif abc
def ghi def
ghi pqr ghi
ci f
pqr
We are able to eliminate the duplicate tuples namely ghi
Set Difference
The Set difference operation s is denoted by-.
e.g. X-Y is a relation which contains the tuples that are in one relation but are not in another relation
X Y X-Y
abc cif abc
def ghi def
ghi pqr
Set Intersection
The Set Intersection operations is denoted by ∩
e.g. X∩Y is a relation which contains the tuples that are present in both relations
X Y X-Y
abc cif ghi
def ghi
ghi pqr
Cartesian Product (Cross Product)
Cross Product is denoted by ×
e.g. X∩Y is a relation which contains the tuples that are present in both relations
X Y X×Y
abc cif abccif
def ghi abcghi
ghi pqr abcpqr
defc if
defghi
defpqr
ghic if
ghighi
ghipqr
Relation Oriented Operation
Select (σ)
The Select operation is denoted by Greek letters sigma (σ).It extracts specific tuples from a relation. One
can consider a Select operation to be filter that keeps only those tuple that satisfy a qualifying condition.
The general formula is
σ <selection condition>(relation name)
where σ denotes the Select operation.
<selection condition> is Boolean expression specified on the attribute.

IT Brainshapers 10 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Suppose we want to extract those tuples which have salary > 900 from Employee. This can be represented
as σ salary > 900 (Employee)
Project (π)
The Project operation is denoted by Greek letters Pi (π).It extracts attribute from a relation. We can use
project operation to be filter that keeps only those attribute that are required
The general formula is
π < attribute list> (relation name)
where π denotes the Project operation.
<attribute list> list of attribute to be needed.
Suppose we want to know the Name, Age from Employee relation. This can be represented as
π Name, Age (Employee)
Division
The division operation is denoted by ÷.The division of X by Y results in another relation table(say XY)
which has those records (tuples) whose domain(A1,A2,A3,A4…..) are appearing X and corresponding
domain(B1,B2,B3,B4…) are appearing in Y. The new relation would have domain A1, A2, A3….An

Language
Employee Language
English
Name Language
Punjabi
Sunil English
Jai Hindi
Sunil Punjabi
Rahim Oriya
The division of table Employee by table language means list of those employee who know both English,
Punjabi
Name Language
Sunil English
Sunil Punjabi
Normalization:
Normalization is step by step decomposition of complex record into simple records with no data loss.
Normalization is the name given to the process of simplifying the relationship among data elements in a
record .Normalization replaces a collection of data in a record structure by another record design which
is simpler more predictable and therefore more manageable .Data normalization is a set of rules and
techniques concerned with:
Identifying relationships among attributes.
Combining attributes to form relations.
Combining relations to form a database.
Need for Normalization: The normalization is required for the following reasons
1. It reduces and control data redundancies (duplication)
2. It improves the database design.
3. It helps to eliminate data anomalies where insertion, deletions and updates destroy the integrity of the
database.
4. It also helps to produce logically correct database.
IT Brainshapers 11 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
The first step towards Normalization is to convert E-R model into tables or Relations.
Normal Forms: A relation is said to be in a particular normal form if it satisfies the constraints set for the
form. There are various types of normal forms.
1. First Normal Form (1NF)
UNNORMALIZED
2. Second Normal Form (2NF) RELATION
3. Third Normal Form (3NF)
The 1NF, 2NF,3NF are originally defined by Dr EF Codd, Latter INF
Boyee and Cod introduced other normal forms called the Boyee 2NF
Codd Normal Form (BCNF).The other are 4NF and 5 NF
e.g Bill 3NF
Bill_No
Bill_Date
Cust_No
Cust_Name
Cust_Address
Item_No
Item _Name
Item_Qty as many Items can occur in the bill
Item_Rate
Item_Value
Total Bill_Value
1. First Normal Form (1NF) A relation is in 1NF if it does not contain repeating elements or group. In other
words all values in every column of the relation have to be atomic.
Bill Bill_Item
Bill_No Bill_No
Bill_Date Item_No
Cust_No Item_Name
Cust_Name Item_Qty
Cust_Address Item_Rate
Total Bill_Value Item_Value
2. Second Normal Form (2NF) : It‟s the first normal form where all non-key attribute are fully functionally
dependent on the whole primary key.e.g In the Bill file in the first normal form Cust_Name and Cust_Add
is only dependent on the Cust_Code and in the Bill_Item file the item_Name is just dependent on the
Item_Code and not on the Bill_No
Bill Cust Item Bill_Item
Bill_No Cust_No Item_No Bill_No
Bill_Date Cust_Name Item_Name Item_No
Cust_No Cust_Address Item_Rate Item_Qty
TotalBill_Value Item_Value
3. Third Normal Form (3NF):It‟s the second normal form where all non-key attribute are dependent on the
whole primary key and independent on each other.
e.g The TotalBill_Value in the Bill file and Item _Value of the Bill_Item can be computed from the
Item_Rate and Item_Qty.
Bill Cust Item Bill_Item
Bill_No Cust_No Item_No Bill_No
Bill_Date Cust_Name Item_Name Item_No
Cust_No Cust_Address Item_Rate Item_Qty

IT Brainshapers 12 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SQL
SQL (Structured Query Language) is a computer language aimed to store, manipulate, and query data
stored in relational databases. The first incarnation of SQL appeared in 1974, when a group in IBM
developed the first prototype of a relational database. The first commercial relational database was
released by Relational Software (later becoming Oracle).
SQL has been a command language for communication with the Oracle 9i Server from any tool or
application. Oracle SQL contains many extensions. When an SQL statement is entered, it is stored in a
part of memory called SQL buffer and remains there until a new SQL statement is entered
SQL *PLUS is an Oracle tool that recognizes and submits SQL statements to the Oracle9i Server for
execution. It contains its own command language.
Features of SQL
 SQL can be used by a range of users, including those with little or no programming experience.
 It is a non-procedural language.
 It reduces the amount of time required for creating and maintaining systems.
 It is English like language.
Advantages
High Speed
SQL queries are deigned to retrieve large amount of records from database quickly and efficiently, when
compared to non-SQL databases. The simple SQL queries can be used to retrieve even highly complicated
combination of data from the database.
Security
SQL provides security by using different constraints on the data, by providing logins and password, which
helps them to manage data efficiently.
Well-defined Standards Exists
SQL databases use the long-established SQL standard, which has been adopted by ANSI in 1986.Since
then, the standards have been continually evolving by the efforts of ANSI and ISO, the latest being SQL
2003.But the non-SQL databases do not have clear standards to adhere.
Compatibility
There are well-defined and established standards that exist, and if the databases adhere to them, then
portability from one SQL database to another is a trivial matter. An SQL database conforming to set
standards can be easily accesses by third party softwares and application tools. This will facilitate the
development of quantity applications and solutions around SQL databases
Non-requirement of Coding
Using standard SQL, it is easier to move applications between different database systems without the
necessity to rewrite a substantial amount of code.
Rules for SQL
 SQL start with a verb (i.e. a SQL action word).Example SELECT statements. This verb may have
additional adjectives. Example: FROM.
 Each verb is followed by number of clauses: Example FROM, WHERE, HAVING
 A space separate clauses Example: DROP TABLE EMP;
 A comma (,) separates parameters without a clause.
 A; is used to end SQL statement.
 Statement may be split across lines but keywords may not.
 Lexical units such as identifiers, operator names, and literals are separated by one or more spaces or other
delimiters that will not confused with the lexical unit.
 Reserved words cannot be used as identifier unless enclosed with double quotes.

IT Brainshapers 13 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
 Identifiers can contain up to 30 characters and must start with an alphabetic character.
 Characters and date literal must be enclosed within single quotes.
 Numeric literals can be represented by simple values such as 0.32,-34, 01991, and so on, scientific
notation as 2E5 meaning 2x10 to the power of 5=200,000.
 Comments may be enclosed between /* and */ symbols and may be multiline. Single line comments may
be prefixed with a-symbol
SQL Delimiters
Delimiters are symbols or compound symbols which have special meaning with in SQL and PL/SQL
statement
+ Addition “ Quote identifier
- Subtraction : Host variable
* Multiplication ** Exponential
/ Division <>!= ^= Relational
=>< Relational <=>= Relational
() Expression or list := Assignment
; Terminator => Association
% Attribute indicator || Concatenation
, Item separator << Label
. Compound selector >> Label
@ Remote access selector -- Comment
„ Character string indicator /* */ Comane(Multiline)
Types of Database Language
There are three types of database languages .These are:
a) DDL(Data Definition Language)
b) DML(Data Manipulation Language)
c) DCL(Data Control Language)
DDL(Data Definition Language)
DDL is language used to define data and their relationship to other types of data. It is mainly used to
create files, databases, data dictionaries and tables within databases. In other word DDL defines the format
or schema of the database.
Functions The primary functions of DDL serves as to
 Describes the schema and subschema of table.
 Describes the fields in each records and record‟s logical name.
 Describes the data type and name of the each field.
 Indicate the key of the record
 Provide means for associating related records or fields
 Provide for logical and physical data interdependence.
 Provide for data security restrictions
The SQL commands that are used to create database objects are known as Data Definition Language or
DDL. The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys),
specify links between tables, and impose constraints between tables. The most important DDL statements
in SQL are:
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
IT Brainshapers 14 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
DML (Data Manipulation Language)
DML is a language which deals with the processing or manipulation of various database objects. It
provides for the program interface to open and close database, find records in files navigate through the
records, add new records, and change or delete existing records.
The SQL commands that are used to manipulate data within database objects are called data
manipulation Language or DML.
DML is used for performing the following operations:
 Retrieving information stored in the database.
 Inserting information into the database
 Deleting the information from the database
 Modifying information stored in the database
The two types of DML are:
 Procedural DML
Procedural DMLs require a user to specify what data are needed and how to get those data
 Declarative DML
Declarative DML require a user to specify what data are needed without specifying how to get
those data
Functions The primary functions of DDL serves as to
Provide techniques for data manipulation as deletion, replacement, retrieval ,sorting, or insertion of datat
on records
The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
DCL (Data Control Language)
DCL is a language which is used to impose security features and thus prevents unauthorized access to data
in the database. Security is provided by granting or revoking privileges on a user. Privilege determines
whether or not a user can execute a given command or a command can be executed on specific groups of
data.
The SQL commands that are used to control the behaviour of database objects are called Data Control
Language or DCL.
Data types in SQL or SQL Data Type
Data type is a name or label for a set of values and some operations, which can be performed on set of
values .Data types restrict the kind of information that can be entered into fields
SQL recognizes four general types of data:
Character strings
Binary
Numerical
Decimal
Character Strings
The character string data type stores a sequence of bytes that represent alphanumeric data. It contains both
fixed length and variable length text (words or numbers).
Data Type Abbreviation Description Range
CHARACTER(n) CHAR(n) Character string, fixed length n. 1≤n≤15000
CHARACTER VARCHAR(n) Variable length character string, 1≤n≤15000
VARYING(n) maximum length n.
CHARACTER or CHAR
The CHARACTER (CHAR) data type stores string values of fixed length in a column.
The length of the CHAR data type can be specified as the length of the column when a table is created.
We can specify the length to be of any value between 1 and 15000

IT Brainshapers 15 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
CHARACTER VARYING or CHAR VARYING or VARCHAR
The CHARACTER VARYING abbreviated CHAR VARYING or VARCHAR data types, stores strings
of varying length.
The varying of the VARCHAR data type can be specified as the length of the column when a table is
created. We can specify the length to be of any value between 1 and 15000
Binary
The binary data types are for binary data (true /false).They store a sequence of bytes that do not represent
alphanumeric characters.
The binary data type category contains the following data types.
Data Type Abbreviation Description Range
BINARY(n) N/A Fixed length binary string, 1≤n≤15000
maximum length n.
BINARY(n) VARBINARY(n) Variable length binary string, 1≤n≤15000
VARYING(n) maximum length n.
NUMERICAL
Numerical data types includes integers and floating –point representations
The binary data type category contains the following data types.
Data Type Abbreviation Description Range
SMALLINT N/A Integral numerical, -32767 through 32767,
precision 5. Corresponds to a 2 bytes
,signed int.
INTEGER INT Integral numerical, -21473648 through
precision 10. 21473648, Corresponds to
a 4 bytes ,signed int.
BIGINT N/A Integral numerical, -9 223 372 036 854 775
precision 19. 808 through 21473648,
Corresponds to a 4 bytes
,signed int.

CREATE TABLE
The create command is used to create a new table and database. Using create command, any number of
columns can be created and the constraints are optional.
The SQL syntax for CREATE TABLE is
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... );
So, if we are to create the customer table specified as above, we would type in
CREATE TABLE customer
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date) ;

IT Brainshapers 16 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Sometimes, we want to provide a default value for each column. A default value is used when you do not
specify a column's value when inserting data into the table. To specify a default value, add "Default
[value]" after the data type declaration. In the above example, if we want to default column "Address" to
"Unknown" and City to "Mumbai", we would type in
CREATE TABLE customer
(First_Name char(50),
Last_Name char(50),
Address char(50) default 'Unknown',
City char(50) default 'Mumbai',
Country char(25),
Birth_Date date)
DROP TABLE COMMAND
To remove the table physically we use DROP TABLE command. The form is as
Syntax Example
DROP TABLE table_name; DROP TABLE EMP;
Note: But before dropping a table it is necessary that all its rows must be deleted .A table with rows
cannot be deleted. We can delete the rows of a table using delete command
Alter Table
This command is used to change the table. We can add new column, change the data type of column or
drop any constraint using alter command.
Add clause Using ADD clause we can add new column into the table.
Syntax Example
ALTER TABLE table_name ALTER TABLE EMP
ADD( column_name datetype); ADD( EMP_AGE number(3,0);
Modify clause Using MODIFY keyword to modify the definition of an existing column..
Syntax Example
ALTER TABLE table_name ALTER TABLE EMP
MODIFY ( column_name datetype); MODIFY( EMP_AGE number(5,0);
Droping a Column To remove a column which is no longer required for your table ,you can use an
ALTER TABLE statement with the DROP COLUMN
Syntax Example
ALTER TABLE table_name ALTER TABLE EMP
DROP COLUMN column_name; DROP COLUMN EMP_AGE;

IT Brainshapers 17 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
The SQL SELECT Statement
The SELECT statement is used to select data from a database. The result is stored in a result table, called
the result-set.
SQL SELECT Syntax
SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
SELECT EMP_NO,EMP_NAME FROM EMP;
EMP_NO EMP_NAME
101 Raj
102 Vijay
103 Sudhir
104 Shekahar
SELECT * Example
Now we want to select all the columns from the "EMP" table.
We use the following SELECT statement:
SELECT * FROM EMP:
The asterisk (*) is a quick way of selecting all columns!
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
Where
The WHERE clause is used to extract only those records that fulfill a specified criterion
Next, we might want to conditionally select the data from a table. For example, we may want to only
retrieve emp_name with salary above 1500. To do this, we use the WHERE keyword. The syntax is as
follows:
SELECT "column_name"
FROM "table_name"
WHERE "condition"

IT Brainshapers 18 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
For example, to select all stores with sales above $1,000 in Table Store_Information,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
we key in,
SELECT EMP_NAME
FROM EMP
WHERE SALARY > 1500
Result:
EMP_NAME
Vijay
Sudhir
In
In SQL, there are two uses of the IN keyword, and this section introduces the one that is related to the
WHERE clause. When used in this context, we know exactly the value of the returned values we want to
see for at least one of the columns. The syntax for using the IN keyword is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)
The number of values in the parenthesis can be one or more, with each values separated by comma.
Values can be numerical or characters. If there is only one value inside the parenthesis, this commend is
equivalent to
WHERE "column_name" = 'value1'
For example, we may wish to select all records for the Raj,Sudhir Table EMP,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we key in,

SELECT *
FROM EMP
WHERE EMP_NAME IN ('Raj', 'Sudhir')

IT Brainshapers 19 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Result:
EMP_NO EMP_NAME Salary
101 Raj 1500
103 Sudhir 2000
105 Raj 1700
Between
Whereas the IN keyword help people to limit the selection criteria to one or more discrete values, the
BETWEEN keyword allows for selecting a range. The syntax for the BETWEEN clause is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'
This will select all rows whose column has a value between 'value1' and 'value2'.
For example, we may wish to select view all salary information between 1500, and 2000, in Table EMP
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we key in,
SELECT *
FROM EMP
WHERE SALARY BETWEEN '1700' AND '2000';
Note that date may be stored in different formats in different databases.
Result:
EMP_NO EMP_NAME Salary
102 Vijay 1800
103 Sudhir 2000
105 Raj 1700
DISTINCT
The SELECT keyword allows us to grab all information from a column (or columns) on a table. This, of
course, necessarily means that there will be redundancies. What if we only want to select each DISTINCT
element? This is easy to accomplish in SQL. All we need to do is to add DISTINCT after SELECT. The
syntax is as follows:
SELECT DISTINCT "column_name" FROM "table_name"
For example, to select all distinct names in Table EMP,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700

IT Brainshapers 20 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
we key in,
SELECT DISTINCT EMP_NAME FROM EMP
Result:
EMP_NAME
Raj
Vijay
Sudhir
Shekahar
Aggregate Functions
Since we have started dealing with numbers, the next natural question to ask is if it is possible to do math
on those numbers, such as summing them up or taking their average. The answer is yes! SQL has several
arithmetic functions, and they are:
AVG: Average of the column.
COUNT: Number of records.
MAX: Maximum of the column.
MIN: Minimum of the column.
SUM: Sum of the column.
The syntax for using functions is,
SELECT "function type" ("column_name") FROM "table_name"
MAX function
SQL uses the MAX function to find the maximum value in a column. The syntax for using the MAX
function is,
SELECT MAX("column_name") FROM "table_name"
For example, if we want to get the highest salary from the following table,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we would type in
SELECT MAX(Salary) FROM EMP
Result:
MAX(Salary)
2000
2000 represents the maximum value of all Salary entries: 1500, 1800, 2000, and 1000..
Min Function
SQL uses the MIN function to find the maximum value in a column. The syntax for using the MIN
function is,
IT Brainshapers 21 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SELECT MIN("column_name") FROM "table_name"
For example, if we want to get the lowest salary from the following table,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we would type in
SELECT MIN(Salary) FROM EMP
MIN(Salary)
1000
1000 represents the minimum value of all Salary entries: 1500, 1800, 2000, and 1000.
AVG function
SQL uses the AVG() function to calculate the average of a column. The syntax for using this function is,
SELECT AVG("column_name") FROM "table_name"
For example, if we want to get the average of all salary from the following table,
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we would type in
SELECT AVG(Salary) FROM EMP
Result:
AVG(Salary)
1575
1575 represents the average of all Salary entries: (1500 + 1800 + 2000 + 1000) / 4.
COUNT Function
Another arithmetic function is COUNT. The COUNT ( ) function returns the number of rows that
matches a specified criteria. The syntax is,
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column:
SELECT COUNT ("column_name") FROM "table_name"
For example, if we want to find the number of Emp_Name entries in our table,
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we'd key in
SELECT COUNT(EMP_NAME) FROM EMP
Result:
Count(EMP_NAME)
5

IT Brainshapers 22 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SQL COUNT (*) Syntax
The COUNT (*) function returns the number of records in a table:
SELECT COUNT (*) FROM table_name
SQL COUNT (DISTINCT column_name) Syntax
The COUNT (DISTINCT column_name) function returns the number of distinct values of the specified
column:
SELECT COUNT (DISTINCT column_name) FROM table_name
Note: COUNT (DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft
Access.
SELECT COUNT (DISTINCT EMP_NAME) FROM EMP
Result: Count(DISTINCT EMP_NAME)
3
Group By
Now we return to the aggregate functions. Remember we used the SUM keyword to calculate the total
sales for all stores? What if we want to calculate the total sales for each store? Well, we need to do two
things: First, we need to make sure we select the store name as well as total sales. Second, we need to
make sure that all the sales figures are grouped by stores. The corresponding SQL syntax is,
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
Let's illustrate using the following table,
Table EMP
EMP_NAME Salary
Raj 1500
Vijay 1800
Sudhir 2000
Shekahar 1000
Raj 1700
We want to find total salary for each employee. To do so, we would key in,
SELECT EMP_NAME, SUM (Salary)
FROM EMP
GROUP BY EMP_NAME
EMP_NAME Salary
Raj 3200
Vijay 1800
Sudhir 2000
Shekahar 1000
The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at
least one arithmetic operator appears in the SELECT statement. When that happens, we need to GROUP
BY all the other selected columns, i.e., all columns except the one(s) operated on by the arithmetic
operator.
HAVING
Another thing people may want to do is to limit the output based on the corresponding sum (or any other
aggregate functions). For example, we might want to see only the stores with sales over $1,500. Instead of
using the WHERE clause in the SQL statement, though, we need to use the HAVING clause, which is
reserved for aggregate functions. The HAVING clause is typically placed near the end of the SQL
statement, and a SQL statement with the HAVING clause may or may not include the GROUP BY
clause. The syntax for HAVING is,
IT Brainshapers 23 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
HAVING (arithmetic function condition)
Note: the GROUP BY clause is optional.
Let's illustrate using the following table,
Table EMP
EMP_NAME Salary
Raj 1500
Vijay 1800
Sudhir 2000
Shekahar 1000
Raj 1700
we would type,
SELECT EMP_NAME, SUM(SALARY)
FROM EMP
GROUP BY EMP_NAME
HAVING SUM(SALARY) > 2100
Result:
EMP_NAME SUM(Salary)
Raj 2300

IT Brainshapers 24 Sanjay-7889862407
12th Comp Science Unit 7 Boolean Logic Marks 10
Introduction to Boolean Algebra
Boolean Algebra was developed by a British mathematician, George Bool, for representing logical expressions
in a mathematical form. A logical expression that can have only two possible results, TRUE or FALSE. To
understand these expressions, let us look at some examples:
Do you know Boolean algebra?
Are you graduate?
All the above statement can have either TRUE or FALSE or YES/NO as possible answers. Boolean algebra is
based on this fact and hence the variables used here can have only one of the two values: either 0 or 1, where 0
denotes FALSE and 1 denotes TRUE.
As in mathematical expressions, the variables are combined with the help of certain mathematical operations
such as +,-,*, or /.Boolean algebra also uses operators, such as AND, OR, and NOT to form Boolean
expressions. Theses operators are called logical operators. The result of a Boolean expression is depicted in the
form of a table known as Boolean Variable and Constant
Boolean valued Quantities
When a variable is used in an algebraic formula, it is generally assumed that the variables may take any
numerical value .For example, in the formula 6A+ 6B= C, it is assumed that A, B, C may possess the value of
any of the real numbers.
But the binary values quantities can assume only one of the two possible values, i.e., true or false. These two
values may be represented by the symbols 0 and 1.
Example .In the equation A+B=C, each of the variables A, B and C can either have the values 0 or 1
Boolean Variables and Boolean Constants
Variable is a named container for data and this data can be changed .Boolean variables are binary values
quantities. Boolean variables can have any of the two vales: true (1) and false (0).
Constants are entries that have a specific fixed value. Boolean constants have affixed value i.e. either true (1)
or false (0)
As stated earlier, Boolean algebra is the algebra of statements .Statements are denoted by letters and referred
to as Boolean variables .A statement can have only two possible value T (signifies true) and F (signifies false)
Suppose A is a Boolean variable denoting ‘
The earth is not flat’, then most people wi
the value of A will be T but, Boolean algebra is not concerned with facts and reality. We define the facts ,and
boolean algebra helps in drawing conclusions from this facts .This means that Boolean algebra is a kind of
moths in which,when told that ‘the moon is squa
Truth Table
Truth table is a type of mathematical table used in logic, to determine whether an expression is true or false. A
logical statement, which contains a finite number of logical variables, can be analyzed using a table .The tables
that lists all possible values of the variables is called a truth table.

IT Brainshapers 1 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
A truth table is a table showing all the input values along with all the possible results of a Boolean expression.
Since each variable can hold only one of the two values, such as true (1) or false (0), a statement with n
variables requires a table with 2n rows
Example A statement with 1 variable require 2 rows, 2 variables require 4 rows and so on.
The letters A, B, C, etc., can be used to represent logical variables and truth table can be constructed for
statement involving any number of varaibels.
The possible values for Boolean expression with 1 variable are
A
0
1
1-Variable Truth Table
The possible values for Boolean expression with 2 variables are
A B
0 0
0 1
1 0
1 1
2-Variable Truth Table
The possible values for Boolean expression with 3 variables are
A B C
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
3-Variable Truth Table
The possible values for Boolean expression with 4 variables are
A B C D
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
4-Variable Truth Table

IT Brainshapers 2 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
The general rules for expressions of more than 4 variables are:
For the first variable, the first half rows are 0s while the second half are 1s.
For the second variables, the rows are split into four sections; the first and third quarters are 0s, while the
second and fourth quarters are 1s.
For the third variables, the rows are split into eight sections, with alternating 0s and 1s in each part.
In general ,for the nth variable ,the rows are split into 2n parts, with alternating 0s and 1s in each part
Boolean Operators
Boolean operators are terms that allow the user to define logical relationships between the words or phrases that
they use to search a database .Examples are OR, AND and NOT.
AND
The AND operator is called the logical multiplication operator. It is represented by* operator.
The result of AND is a 1only when both operands are 1s.
If any of the operand is0, the result is 0
The AND operation is like multiplication, but operates on binary values. The rules of the AND operator are as.
0*0 =0
0*1 =0
1*0 =0
1*1 =1
The truth table for AND operator is as shown
Input Output
A B A B
0 0 0
0 1 0
1 0 0
1 1 1
OR AND Truth Table
The OR operator is called the logical addition operator. It is represented by (+) operator.
The result of OR is a 1 if any of the operands is 1.
The single instance that the result of an OR is 0 is when both operands are 0s.
The OR operation is like addition, but operates only on binary values. The rules of the OR operator are as
shown.
0+0 =0
0+1 =1
1+0 =1
1+1 =1

IT Brainshapers 3 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
The truth table for OR operator is as shown
Input Output
A B A +B
0 0 0
0 1 1
1 0 1
1 1 1
NOT OR Truth Table
The NOT is a unary operator. It operates on one operand.
NOT negates its operand. In other words, this operator provides the complements of 0 and 1.
If the operand is 1,the result of the NOT is 0.In other words:
0` =1
1` =0
The truth table is shown below
Input Output
A A`
0 1
1 0
Precedence of Operator NOT Truth Table
Boolean expression are formed with binary variables (operands), the binary operations (OR, AND and NOT),
parenthesis and an equal sign. An example of a valid expression in Boolean algebra is X*Y+Z. However, there
must be consistency when Boolean expressions are evaluated, as in ordinary algebra.
Example if the expression 5 + 4 * 2 are presented in ordinary algebra, we have to use the rules of algebra by
evaluating the multiple operator followed example:
5+4*2
= 5 +8
= 13
These are known as the rules of precedence .If these are not defined and followed rigorously, then it would
result in confusion as different answers will be evaluated from the same expression.
Similarly, rules of precedence are also used in Boolean algebra .The order of evaluation of expressions is :
Operator Symbol Precedence
Parenthesis () 1
NOT ‘ -or 2
AND * 3
OR + 4

IT Brainshapers 4 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
In other words, any term in parenthesis is evaluated first, followed by any NOT operators AND operators, and
OR operators.
Example: (a + b) * c
a+b is evaluated first and then (a+b)*c
Evaluation of Boolean Expression using Truth Tables
A Boolean expression can be represented using truth tables. The simplification and evaluation of Boolean
expression can be done using truth table
Example 1 Draw the truth table for AB ABC
A B C A AB ABC AB ABC
0 0 0 1 0 0 0
0 0 1 1 0 0 0
0 1 0 1 1 0 1
0 1 1 1 1 0 1
1 0 0 0 0 0 0
1 0 1 0 0 0 0
1 1 0 0 0 0 0
1 1 1 0 0 1 1

Example 2 Using truth table, verify that A(B C) AB

A B C B AB B+C A(B+C) A(B C) AB

0 0 0 1 0 0 0 0
0 0 1 1 0 1 0 0
0 1 0 0 0 1 0 0
0 1 1 0 0 1 0 0
1 0 0 1 1 0 0 1
1 0 1 1 1 1 1 1
1 1 0 0 0 1 1 1
1 1 1 0 0 1 1 1

Prove the following expression, using truth table


a) a*b=b*a
b) a+b=b=a

c) a b= a * b
d) (a b) * a * b =0

e) a+ a *b+ a * b =1
IT Brainshapers 5 Sanjay -7889862407
12th Comp Science Unit 7 Boolean Logic Marks 10
Laws of Boolean Algebra
The laws of Boolean algebra are very useful in simplifying logic at expressions or transforming them into other
useful equivalent expressions.
The different laws of Boolean algebra are
1. Closure Property
2. Commutative Law
3. Associative Law
4. Distributive Law
5. Identity Law
6. Inverse Law
7. Duality Theorem
8. Idempotent Law
9. Absorption Law
10. Involution Law
11. DeMorgan’s Law
Some of the basic operations to be considered in Boolean algebra are:
a+0 = a
a+1 = 1
a*0 = 0
a*1 = a
0`= 1
1`= 0
1. Closure Property
Closure property states that the operations (+) and (*) are closed; that is for all
X a,b Є
a + b ЄX
a * b ЄX
The Boolean system is closed with respect to a binary operator, for every pair of Boolean values, it produces a
boolean result.
For examples
1 + 0 = 1 ЄZ
1 * 0 = 0 ЄZ
Here the logical AND and OR is closed in the Boolean system: it accepts only Boolean operands and produces
only Boolean results.

IT Brainshapers 6 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
Proof using truth table
The truth table for ‘and’ and ‘or’ operations a
a b a*b a+b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
The truth tables shows that a*b and a+b contains the elements 0 and 1.
2. Commutative Law
Commutative law states that the operations (+) and (*) are commutative; that is for all a,b Є X
a+b = b+a
a*b = b*a
These two equations indicates that the order of, logical operations is unimportant because the sane answer is
arrived at either way
Proof using circuit diagram

Circuit Diagram
So, a * b = b * a
a+b=b+a
Proof using truth table
The statement a * b = b * a and a + b = b + a can be proved using the following truth table :
a b a*b b*a a+b b+a
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 0 1 1
1 1 1 1 1 1
As seen in the truth table, it is proved that
a+b = b+a
a*b = b*a

IT Brainshapers 7 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
3. Associative Law
Associative law states that the operations (+) and (*) are associative; that is for all a, b Є X
a+(b+ c) = (a+b)+c
a*(b*c ) = (a*b )*c
Law shows that the order of combining variables has no effect on the final answer
Proof using circuit diagram The circuit diagram of two equations are as shown

So, a + (b + c) = (a + b) + c
a * (b * c) =(a * b) * c
Proof using truth table
The statement a * (b * c) = (a * b) * c can be proved using the following truth table
a b c a*b b*c a * ( b * c) (a* b)*c
0 0 0 0 0 0 0
0 0 1 0 0 0 0
0 1 0 0 0 0 0
0 1 1 0 1 0 0
1 0 0 0 0 0 0
1 0 1 0 0 0 0
1 1 0 1 0 0 0
1 1 1 1 1 1 1
As seen in the truth table, it is proved that a * (b * c) = (a * b) * c
The statement a + (b + c) = (a + b) + c can be proved using the following truth table.
a b c a+b b +c a + ( b + c) (a+b)+c
0 0 0 0 0 0 0
0 0 1 0 1 1 1
0 1 0 1 1 1 1
0 1 1 1 1 1 1
1 0 0 1 0 1 1

IT Brainshapers 8 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
1 0 1 1 1 1 1
1 1 0 1 1 1 1
1 1 1 1 1 1 1
As seen in the truth table, since the final values of a + (b + c) and (a + b) + c are equal
So, a + ( b + c ) = ( a + b ) + c
a*(b*c ) = (a*b )*c
4. Distributive Law
Distributive law states that each operation (+) and (*) is distributive over the other; that is for all a, b Є X
a*(b+c ) = (a*b)+(a * c)
a+(b*c ) = (a+b)* (a+ c)
These laws allow the factorization of expression
Proof using circuit diagram The circuit diagram of two equations are as shown

Proof using truth table


The statement a * ( b + c ) = ( a * b ) + ( a * c ) can be proved using the following truth table
a b c a*b a*c b+c (a*b) + (a*c) a*(b+c )
0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 1 0 0
0 1 1 0 0 1 0 0
1 0 0 0 0 0 0 0
1 0 1 0 1 1 1 1
1 1 0 1 0 1 1 1
1 1 1 1 1 1 1 1
As seen in the truth tables, the values for (a*b) + (a*c) and a * ( b + c ) are equal.

IT Brainshapers 9 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
The statement a + ( b * c ) = ( a + b ) * ( a + c ) can be proved using the following truth table:
a b c b*c a+b a+c a+(b*c ) (a+b)*(a+c)
0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 1 0 0 0
0 1 1 1 1 1 1 1
1 0 0 0 1 1 1 1
1 0 1 0 1 1 1 1
1 1 0 0 1 1 1 1
1 1 1 1 1 1 1 1
As seen in the truth table the values for a + ( b * c ) and ( a + b ) * ( a + c ) are equal.
5. Identity Law
A boolean value 1 is said to be the identity element with respect to the (*) operator if a * 1 = a
Examples
1*1=1
0*1=0
Similarly, a boolean value 0 is said to be the identify element with respect to the (+) operator if
a+0=a
This is for all a,b,c ЄX.
Examples
1+0=1
1+1=1
Proof using truth table
The truth table for a * 1 and a + 0 is given
a a*1 a+0
0 0 0
1 1 1
As shown in the truth table, it is proved that a * 1 = a and a + 0 = a
6. Inverse Law
A boolean value 1 is said to be the inverse element with respect to the (+) operator if a a = 1
Examples
1+1=1+0=1
0+ 0 =0+1=1
A Boolean value 0 is said to be the inverse element with respect to the (*) operator if a a = 0

IT Brainshapers 10 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
Examples
1*1 =1*0=0
0* 0 =0*1=0
This is for all a,b,c ЄX.
Proof using truth table
The truth table for a + a` is given
a a a+ a
0 1 1
1 0 1
As shown in the truth table, it is proved that a + a = 1
7. Duality Theorem
The duality theorem states that, one Boolean relation can be derived from another by:
1. Changing each OR sign to an AND sign.
2. Changing each AND sign to an OR sign.
3. Complementing any 0 or 1 appearing in the expression.
Example:
a +0=a
Using duality theorem:
a * 1=a
Proof using truth table
The truth table for a + 0 is given
a a+0 a*1
0 0 0
1 1 1
As shown in the truth table, it is proved that,
a+0=a*1=a
8. Idempotent Law
Idempotent law states that for each element X in a Boolean algebra
a+a = a
a*a = a
Proof using laws
= a+a
= (a+a )*1 (Identity)
= (a+a )*(a+a) (Inverse)
= a + a * a` (Distributive)

IT Brainshapers 11 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
= a +0 (Inverse)
= a (Identity)
Proof using truth table
The truth table for a + a and a * a is given
a a+a a*a
0 0+0=0 0*0=0
1 1+1=1 1*1=1
As shown in the truth table, it is proved that
a+a = a
a*a = a
9. Absorption Law
For each pair of elements a and b in a Boolean algebra
b*a +a= a
(b + a ) * a = a (Duality Theorem)
Proof using laws
b*a+a
= b*a+a*1 (Identity)
= b*a+1*a (Commutative)
= (b+1)*a (Distributive)
= 1*a (Operations with 0 and 1)
= a (Identity)
Proof using truth table
The truth table for b * a + a = a and (b + a) * a = a is given
a b b*a b+a b*a+a (b+a)*a
0 0 0 0 0 0
0 1 0 1 0 0
1 0 0 1 1 1
1 1 1 1 1 1
As shown in the truth table it is proved that
b*a+a=a
( b + a) * a = a.
10. Involution Law
For every a in a Boolean algebra
(a ) =a

IT Brainshapers 12 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
Proof using truth table
a a (a )
0 1 0
1 0 1
As shown in the truth table it is proved that (a ) =a
11. DeMorgan’s Law
The two DE orem
Morgan’s
are as follows: The
i a b = a* b
ii a *b= a + b
The complement of any Boolean expression is found by using these two rules .The two steps used to form a
complement are:
a The (+) symbol are replaced with (*) symbols and (*) symbols with (+) symbols. This changes ANDs to
ORs and vice versa.
b. Each of the term in the expression is complemented.
Proof using truth table
The truth table for
i a b = a* b
ii a *b= a + b
a b a b a*b a+b a* b a b a *b a +b
0 0 1 1 0 0 1 1 1 1
0 1 1 0 0 1 0 0 1 1
1 0 0 1 0 1 0 0 1 1
1 1 0 0 1 1 0 0 0 0

As shown in the truth table, it is proved that a b = a * b and a * b = a + b since their values are equal.

IT Brainshapers 13 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
Introduction to Logic Gates
A logic gate is an elementary building block of a digital circuit. Digital circuit is an electronic circuit that
accepts and processes binary data (0 or 1) according to the rules of boolean logic (AND, OR, NOT, etc).
A digital circuit having one or more input signals but only one output signal is called logic gate At any
given moment, every terminal is one of the two binary conditions, low(0) or high(1),represented by different
voltage levels. The logic state of a terminal often changes as the circuit processes data. In most logic gates, the
low state is approximately zero voltages (0 V), while the high state is approximately five voltages positive
(+5V)
Basic Logic Gates
There are seven basic logic gates .They are
AND
OR
XOR
NOT
NAND
NOR
XNOR
The logic gates NAND, NOR, XOR, XNOR are ultimately derived from combinations of AND, OR, NOT gates
AND Gate
The AND gate is so named because ,if 0 stands for false and 1 stands for true, the gate acts in the same way as
the logical AND operator
The following illustration and table shows the circuit symbol and logic combination for an AND gate(In the
symbol are on the left and the output terminal is on the right)

Circuit Diagram Truth Table


Input Output
A B A B
0 0 0
0 1 0
1 0 0
1 1 1
The AND gate produces an output of 1 when both the inputs are 1,otherwise the output is 0.The AND gate has
two or more inputs .The output from the AND gate is written as A*B.A dot represents the AND operation.

IT Brainshapers 14 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
There is not limit to the number of inputs that may be applied to an AND function. So there is no functional
limit to the number of inputs an AND gate may have. However, for practical reasons, commercial AND gates
are most commonly manufactured with 2, 3 or 4 inputs
OR Gate
The OR gate is similar to the logical OR operation. The following illustration and table shows the circuit
symbol and logic combination for an OR gate

Circuit Diagram Truth Table


Input Output

A B A +B

0 0 0

0 1 1

1 0 1

1 1 1

The OR gate has two or more inputs .The output from the OR gate is 1 if any of the inputs is 1.The gate output
is 0 if only all inputs are 0.The output from the OR gate is written as A+B. A plus indicates OR operation.
The OR function can have any number of inputs to the AND gate. However, practical commercial OR gates are
mostly limited to 2,3 and 4 inputs .
NOT Gate
The NOT gate is similar to the NOT operation. This gate is unique, since it has only one input. The input to the
NOT gate A is inverted i.e., the binary input state of 0 gives an output of 1 ad the binary input state of 1 gives
an output of 0.
NOT gate is also known as an inverter because it changes the input to its opposite (inverts it).A common way of
using the NOT gate is to simplify attach the circle to the front of another gate.
The truth table and the circuit diagram for the NOT gate are as shown:

Circuit Diagram Truth Table


Input Output
A A
0 1
1 0

A is known as NOT A or alternatively as the complement of A


NAND Gate
The NAND gate is a combination of a NOT gate and an AND gate
In this, the output is 0 only when all the inputs are 1.The symbol is an AND gate with a small circuit on the
output. The small circle represents inversion.

IT Brainshapers 15 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
The output from the AND gate is written A * B

Circuit Diagram Truth Table


Input Output
A B A*B
0 0 1
0 1 0
1 0 0
1 1 0

There is no limit to the number of inputs that may be applied to a NAND function, so there is no functional
limit to the number of inputs a NAND gate may have. However, for practical reasons, commercial NAND gates
are most commonly manufactured with 2, 3, or 4 inputs, to fit in a14-pin or 16-pin package
NOR Gate
The NOR gate is a combination of a NOT gate and an OR gate. In this, the output is 1 when all the inputs are 0
and in all other cases the output is 0.
The symbol is an OR gate with a small circle on the output. The small circle represents inversion.
The output from the AND gate is written as A B

Circuit Diagram Truth Table


Input Output
A B A B
0 0 1
0 1 0
1 0 0
1 1 0

The NOR function can have any number of inputs, but commercial NOR gates are mostly limited to 2, 3, and 4
inputs, as with other gates in this class, to fit in standard IC package.
XOR Gate
The exclusive –OR or XOR function is a useful variation on the basic OR function.Verbally, it can be stated as
either A or B, but not both. The XOR gate produces logic 1 output, only if its two inputs are different. If the
inputs are same, the output is logic 0.
The following illustration shows the circuit diagram and the truth table of the XOR gate. The XOR symbol is
variation on the standard OR symbol. The output from the XOR gate is represented by a symbol consisting of a
plus (+) sign with a circle around it i.e. A B
Unlike standard OR/NOR and AND/NAND functions, the XOR function always has exactly two inputs, and
commercially manufactured XOR gates are the same. Four XOR gates fit in a standard 14-pin IC package

IT Brainshapers 16 Sanjay -7889862407


12th Comp Science Unit 7 Boolean Logic Marks 10
Circuit Diagram Truth Table
Input Output
A B A B
0 0 0
0 1 1
1 0 1
1 1 0
XNOR Gate
The exclusive –NOR or XNOR gate is a combination of a NOR gate and a NOT gate. The circuit diagram and
truth table are as shown in the table
The output from the XOR gate is represented by A B

Circuit Diagram Truth Table


Input Output
A B A B
0 0 1
0 1 0
1 0 0
1 1 1

Because of inversion on the output side, the truth table for a XNOR gate is the complement of the XOR truth
table. The output is 1 when the inputs are same. So the 2-input XNOR gate is immensely useful for bit
comparison, and it recognizes when the two input bits are identical.
The XNOR gate can have any number of inputs.

IT Brainshapers 17 Sanjay -7889862407

You might also like