Syntax error:
This type of error occurs when the user
violates the languages rule and
regulations.
(e.g) cout>>enter the number; invalid
Cout<<enter the number; valid
Logical error:
this type of error occurs when the
programmer violates the logical concepts
of the language. These errors can be
identified only by the wrong output for the
right input.
3
Asynchronous Exception
The errors that are caused by events beyond the control of
the program are called asynchronous exceptions.
Example: disk failure
keyboard problems etc
All the synchronous exceptions occur within the program
control. But the asynchronous exceptions occur beyond the
program control.
USES:
It avoids abnormal situation during run time.
It help the user by reporting the reason for abnormal
conditions so that the appropriate action will be taken.
5
Try Block:
This block contains ordinary C++ statements and it is related
to throw blocks. The important task of try block is to find out
the abnormal conditions for the given statements. Then the
throw block throws the exception objects.
Throw block:
This block is used to throw the detected exception objects.
you use a throw expression to indicate that your program has
encountered an exception
Catch Block:
A catch block is defined by the keyword catch which cathces
the exceptions thrown by the throw statement in the try block
and handle it appropriately.
Exception
object
Catch block
Catches and handles the exception
try
{
.
// block of statements which detects and
throw exception // throws an exception
.
}
catch ( type arg)
{
}
..
}
When the try block throws an exception, the program control leaves the
try block and enters the catch statement of the catch block.
Exceptions are objects or variables used to transmit information about a
problem.
If the type of object thrown matches the arg type in the catch statement,
then catch block is executed for handling the exception.
If they do not match, the program is aborted with the help of the abort()
function which is invoked automatically.
The catch block may have more than one catch statements, each
corresponding to a particular type of exception.
For example if the throw block is likely to throw two exception, the
catch block will have two catch statements one for each type of
exception. Each catch statement is called is exception handler.
When no exception is detected and thrown, the control goes to the
statement immediately after the catch block. That is catch block is
skipped.
RUN 1:
#include<iostream.h>
void main( )
{
int x, y, z;
cout<<enter the values of x, y, z;
cin>>x>>y>>z;
try
{
if(x= =y)
throw y;
else
int d= z / ( x- y);
cout<<the result of z/ (x-y )is:<< d;
}
catch( int y)
{
cout<<exception caught x-y is << x-y ;
}
}
void main( )
{
int num;
cout<<enter any number;
cin>>num;
try
{
greater ( num);
}
catch( positive)
{
cout<<+ve exception;
}
catch(negative)
{
cout<<-ve exception;
}
catch (zero)
{
cout<<0 exception;
}
}
int main()
{
cout<<testing generic catch \n;
test(-1);
test(0);
test(1);
}
RETHROWING AN EXCEPTION
a handler may decide to throw the exception caught without processing it. it
invokes throw without any argument
int main()
ex: throw;
{
#include<iostream.h>
cout<<inside main;
void divide(double x, double y)
try
{
{
divide(10.5,2.0);
cout<<inside function \n;
divide(20.0,0.0);
try
}
{
catch(double)
if(y==0.0)
{
throw y;
cout<<caught double inside main\n;
else
cout<<division = <<x/y;
}
}
cout<<end of main \n ;
}
catch(double)
{
cout<<caught double inside function \n;
throw;
}
cout<<end of function \n ;
}
EXCEPTION SPECIFICATION
Uncaught exceptions
If a propagating exceptionis not caught by anytrycatch"net", then it propagates all the way out ofmain()
16
TEMPLATES
Templates
Templates are a feature of the C++ programming language
that allow functions and classes to operate with generic types.
This allows a function or class to work on many different data
types without being rewritten for each one.
Generic Programming
Is an approach where generic types are used as parameters
in algorithms
Generic programs work for a variety of suitable data types
and data structures
Template Definition:
template<class T>
The prefix tells the compiler that we are going
to declare a template and use T as a type name
in the declaration
The type T may represent a class name .
A class created from a class template is called a
template class
Syntax for defining an object of a template class
is:
classname<type> objectname(arglist);
This process of creating a specific class from a
class template is called instantiation.
CLASS TEMPLATES
Example program for template using single parameters
# include <iostream.h>
template<class T >
Class sample
{
Private:
T value;
Public:
Void read()
{
Cout<<enter values;
Cin>>value;
}
Void display()
{
Cout<<value=<<value;
}
};
void main()
{
Sample<int>s1;
Sample <float>s2;
S1.read();
S1.display();
S2.read();
S2.display();
}
Output:
Enter values 10
Value=10
Enter values 10.5
Value=10.5
# include <iostream.h>
# include <string.h>
template<class T >
Class sample
{
Private:
T a;
T b;
Public:
Void read()
{
Cout<<enter values;
Cin>>a>>b;
}
Void display()
{
Cout<<value=<<a<<b;
}
};
Example:2
void main()
{
Sample<int,int>s1;
Sample <float,float>s2;
S1.read();
S1.dispaly();
S2.read();
S2.dispaly();
}
Enter values 10 20
Value=10 20
Enter values 10.5 20.5
Value=10.5 20.5
void display()
{
cout<<value=<<z;
}
};
void main()
{
sample<float ,int>s1;
s1.read();
s1.dispaly();
getch();
}
Output:
Enter values 10.3 20
Value=30.3
Function template
Like class templates, we can also define function templates that could be
used to create a family of functions with different argument types.
The function template syntax is similar to that of class template except that
we are defining functions instead of classes.
We must use the template parameter T as and when necessary in the
function body and its argument list. The general format of a function
template is:
Syntax:
template<class T>
return type function name (arguments of type T)
{
//
//body of function //with type T
//wherever appropriate
//..
}
The following example declares a swap() function template that will swap
two values of a given type of data.
template<class T>
void swap(T &x,T &y)
{
T temp=x;
X=Y;
Y=temp;
}
FUNCTION TEMPLATES
# include <iostream.h>
# include <string.h>
template<class T >
void display(T x)
{
cout << x;
}
void main()
{
display(1999);
display(12.34);
display(w);
return 0;
}
OUTPUT:
1999
12.34
w
# include <iostream.h>
# include <string.h>
template<class T >
void display(T x, T y)
{
cout << x<<y;
}
int main()
{
display(1999,2000);
display(12.34,10.5)
display(w,s);
return 0;
}
OUTPUT:
1999 2000
12.34 10.5
ws
cout<<a=<<a<<endl<<
b=<<b<<endl;
swap(a,b);
cout<<After
swapping:<<endl;
cout<<a=<<a<<endl<<
b=<<b<<endl;
char c1=$,c2=&;
cout<<Before
swapping:<<endl;
cout<<c1=<<c1<<endl<
<c2=<<c2<<endl;
swap(c1,c2);
cout<<After
swapping:<<endl;
cout<<c1=<<c1<<end
l<<c2=<<c2<<endl;
float f1=3.45,f2=4.65;
cout<<Before
swapping:<<endl;
cout<<f1=<<f1<<endl
<<f2=<<f2<<endl;
swap(f1,f2);
cout<<After
swapping:<<endl;
cout<<f1=<<f1<<en
dl<<f2=<<f2<<en
dl;
getch();
}
# include <iostream.h>
template<class T >
Class sample
{
Private:
T value;
public:
void read()
void display()
};
template<class T >
void sample <t>:: read()
{
cout<<enter values;
cin>>value;
}
template<class T >
void sample<t>::display()
{
cout<<value=<<value;
}
void main()
{
sample<int>s1;
sample <float>s2;
s1.read();
s1.dispaly();
s2.read();
s2.dispaly();
}
Output:
Enter values 10
Value=10
Enter values 10.5
Value=10.5
FILE HANDLING
FUNCTIONS
{OR}
A file is a collection of related
data stored in a particular area
on the disk.
TEXT MODE
BINARY MODE
fin.getline(line,n);
cout<<line;
}
fin.close();
getch();
}
Output
contents of country file
IndiaPakistanSrilanka
contents of capital file
DelhiKarachiKolumbo
To move a file pointer to a desired location using the seek functions. The argument
to these functions represent the absolute position in the file.
seek functions seekg() and seekp() can also be used with two arguments
Program:
#include<iostream.h>
Output:
Enter a string
#include<fstream.h>
Cobol_programming input
#include<string.h>
Cobol_programming output
int main()
{
char string[80];
cout<<Enter a string\n;
cin>>string;
int len=strlen(string);
fstream file;
\\ input and output stream
file.open(TEXT,ios::in| ios::out);
for(int i=0,i<len;i++)
file.put(string[i]); \\ put a character to file
file.seekg(0);
\\ go to start
char ch;
while(file)
{
file.get(ch); \\ get a character from a file
cout<<ch;
\\ display it on screen
}
return 0;}
Infile.read((char*)&v, sizeof(v));
Outfile.write((char*)&v,sizeof(v));
for(i=0;i<4;i++)
I/O operations on binary files:
{
Program:
cout.setf(ios::showpoint);
#include<iostream.h>
cout<<setw(10)<<setprecision(2)<<hei
#include<conio.h>
ght[i];
#include<iomanip.h>
}
const char * filename= binary;
infile.close();
int main()
return 0;}
{
float height[4] ={175.5,153.0,167.25,160.70}
ofstream outfile;
outfile.open(filename);
outfile.write((char*)&height, sizeof(height));
outfile.close(); \\ close the file for reading
for (int i=0;i<4;i++) \\ clear array from memory
height[i]=0;
ifstream infile;
infile.open(filename);
infile.read((char*)&height, sizeof(height));
Output:
175.50 153.00 167.25
Updating a file:
Updating is a routine task in the maintenance of any data file. The updating
would include one or more of the following tasks:
DETECTING END-OF-FILE
if(fin1.eof() != 0) {exit(1);}
eof() is a member function of ios class. It returns a nonzero value if the end-of-file (EOF) condition is encountered,
and a zero, otherwise.
Example:
ifstream infile;
infile.open(ABC);
while(!infile.fail())
{
. (process when operation fails)
.
}
if (infile.eof())
{
.. (terminate program normally)
}
else
if(infile.bad())
{
.. (report fatal error)
}
else
{
infile.clear(); \\ clear error state
Advantages
to save the time and effort
to reuse the same code
Components of STL
The three key components of STL are
Containers
Algorithms
Iterators
A container is an object that actually stores data in memory, for
example an array of elements.
Algorithms in the STL are procedures that are applied to containers
to process their data, for example search for an element in an array,
or sort an array.
Iterators are a generalization of the concept of pointers, they point
to elements in a container, for example you can increment an
iterator to point to the next element in an array
Containers, Iterators,
Algorithms
Algorithms use iterators to interact with objects
stored in containers
Container
Container
Iterator
Algorithm
Iterator
Objects
Iterator
Algorithm
Algorithm
Iterator
Containers
Containers are objects that hold data, either built-in data
types like int and float, or class objects.
STL containers are implemented by template class.
Each container class defines the set of functions that
can be used to manipulate its contents.
The STL provides several basic kinds of containers
the major 3 categories,
sequence container
<vector> : one-dimensional array
<list> : double linked list
<deque> : double-ended queue
Derived container
<queue> : queue
<stack> : stack
Associative container
<set> : set
<map> : associative array
<priority queue>
Sequence Containers
A sequence container stores a set of elements in sequence, in
other words each element (except for the first and last one) is
preceded by one specific element and followed by another,
<vector>,<list> and <deque> are sequential containers
STL provides three types of sequence containers.
In an ordinary C++ array the size is fixed and can not change
during run-time, it is also tedious to insert or delete elements.
Advantage: quick random access
<vector> is an expandable array that can shrink or grow in size,
but still has the disadvantage of inserting or deleting elements in
the middle . It allows insertion and deletion at back.
Sequence Containers
<list> is a double linked list (each element has points to its
successor and predecessor), it is quick to insert or delete
elements but has slow random access
<deque> is a double-ended queue, that means one can
insert and delete elements from both ends, it is a kind of
combination between a stack (last in first out) and a queue
(first in first out) and constitutes a compromise between a
<vector> and a <list>. the iterator used is bidirectional.
Associative Containers
In an associative container the items are not arranged in
sequence, but usually as a tree structure or a hash table.
The main advantage of associative containers is the speed
of searching (binary search like in a dictionary)
Searching is done using a key which is usually a single
value like a number or string
The value is an attribute of the objects in the container
The STL contains two basic associative containers
sets and multisets
maps and multimaps
Associative Containers
A <set> stores a number of items which contain keys. The keys are
the attributes used to order the items, for example a set might store
objects of the class Person which are ordered alphabetically using
their name
A <map> stores pairs of objects: a key object and an associated
value object. A <map> is somehow similar to an array except
instead of accessing its elements with index numbers, you access
them with indices of an arbitrary type.
<set> and <map> only allow one key of each value, whereas
<multiset> and <multimap> allow multiple identical key values
Derived Containers
STL provides three derived containers namely,
Stack
queue
priority_queue
Algorithms
Algorithms are defined as the step by step process for
mnaipulating functions.
STL algorithms allows us to work with two different
types of containers at the same time.
STL algorithms are not member functions or friends of
containers. they are standalone template functions.
STL algoritms, provides more than sixty algorithms
which are used to support complex operations. They are
retrive or non-mutating algorithms- find(), search()
Iterators
Iterators are pointer-like entities that are used to access individual
elements in a container.
Often they are used to move sequentially from element to element,
a process called iterating through a container.
vector<int>
array_
17
vector<int>::iterator
4
23
12
size_
Iterators
The member functions begin() and end() return an
iterator to the first and past the last element of a container
vector<int> v
array_
17
v.begin()
4
23
12
size_
v.end()
Iterators
One can have multiple iterators pointing to different or identical
elements in the container
vector<int> v
array_
17
4
23
i1
i2
12
size_
i3
Iterator Categories
Not every iterator can be used with every container for
example the list class provides no random access iterator
Iterators are divided into five categories in which a higher
(more specific) category always subsides a lower (more
general) category, e.g. An algorithm that accepts a forward
iterator will also work with a bidirectional iterator and a
random access iterator .
input
forward
output
bidirectional
random
access