Unit 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

Please read this disclaimer before proceeding:

This document is confidential and intended solely for the educational purpose of RMK
Group of Educational Institutions. If you have received this document through email in
error, please notify the system manager. This document contains proprietary information
and is intended only to the respective group / learning community as intended. If you
are not the addressee you should not disseminate, distribute or copy through e-mail.
Please notify the sender immediately by e-mail if you have received this document by
mistake and delete this document from your system. If you are not the intended
recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
22CS101
Problem Solving using C++

Department : CSE , IT , AIML , CSBS


Batch / Year : 2023 – 2027 / I
Created by : Subject Handling Faculties
Date : 27.11.2023
1. Contents
S. No. Contents

1 Contents

2 Course Objectives

3 Prerequisites

4 Syllabus

5 Course Outcomes

6 CO-PO Mapping

7 Lecture Plan

8 Activity Based Learning

9 Lecture Notes

10 Assignments

11 Part- A Questions & Answers

12 Part-B Questions

13 Supportive Online Courses

14 Real Time Applications

15 Content beyond the Syllabus

16 Assessment Schedule

17 Prescribed Text books & Reference Books

18 Mini Project Suggestions


Unit - 5 Content

Chapter No. Contents

5.1 C++ Streams

5.2 Unformatted I/O

5.3 Formatted Console I/O

5.4 Opening and Closing File

5.5 File Modes

5.6 File Pointers and their Manipulations

5.7 Templates

5.8 Class Templates

5.9 Function Templates

5.10 Exception handling

5.11 Usage of try Keyword

5.12 Usage of catch Keyword

5.13 Usage of throw Keyword

5.14 Usage of catch (...)

Programming Illustration - Exception


5.15
handling
2. Course Objectives
 To learn problem solving and programming fundamentals.
 To gain knowledge on pointers and functions.
 To apply the principles of object orientated programming.
 To understand operator overloading, inheritance and polymorphism.
 To use the functionalities of I/O operations, files build C++ programs
using exceptions.
3. Prerequisites

22CS101
Problem Solving Using C++

Fundamentals of
Programming

Logical Thinking

Fundamentals of
Mathematics
4. Syllabus
PROBLEM SOLVING USING C++ L T P C
22CS101 (Lab Integrated) 3 0 2 4
OBJECTIVES:
 To learn programming fundamentals in C.
 To gain knowledge on pointers and functions.
 To apply the principles of classes and objects
 To develop a C++ application with object oriented concepts.
 To use the functionalities of I/O operations, files build C++ programs using exceptions.
UNIT I PROGRAMMING FUNDAMENTALS 15

Computational thinking for Problem solving – Algorithmic thinking for problem Solving- Building
Blocks - Problem Solving and Decomposition –Dealing with Error – Evaluation. Overview of C –
Data types – Identifiers – Variables – Storage Class Specifiers – Constants – Operators -
Expressions – Statements – Arrays and Strings – Single-Dimensional – Two-
Dimensional Arrays – Arrays of Strings – Multidimensional Arrays.

UNIT II POINTERS AND FUNCTIONS 15

Pointers -Variables – Operators – Expressions – Pointers and Arrays – Functions - Scope Rules –
Function Arguments – return Statement – Recursion – Structures – Unions – Enumerations.

UNIT III CLASSES AND OBJECTS 15

Concepts of Object Oriented Programming – Benefits of OOP – Simple C++ program - Classes and
Objects - Member functions - Nesting of member functions - Private member functions - Memory
Allocation for Objects - Static Data Members - Static Member functions - Array of Objects - Objects
as function arguments - Returning objects - friend functions – Const Member functions -
Constructors – Destructors

UNIT IV OPERATOR OVERLOADING , INHERITANCE AND POLYMORPHISM 15

Operator Overloading - Overloading Using Friend functions – Inheritance – Types of inheritance –


Virtual Base Class - Abstract Class – Constructors in Derived Classes - member class: nesting of
classes. Pointer to objects – this pointer- Pointer to derived Class - Virtual functions – Pure Virtual
Functions – Polymorphism

UNIT V I/O, FILES AND EXCEPTIONS 15

C++ Streams – Unformatted I/O - Formatted Console I/O – Opening and Closing File – File
modes - File pointers and their manipulations – Templates – Class Templates – Function Templates
- Exception handling.
Lab Exercises

1. Write C/C++ programs for the following:


a. Find the sum of individual digits of a positive integer.
b. Compute the GCD of two numbers.
c. Find the roots of a number (Newton‘s method)
2. Write C/C++ programs using arrays:
a. Find the maximum of an array of numbers.
b. Remove duplicates from an array of numbers.
c. Print the numbers in an array after removing even numbers .
4. Syllabus Contd...
3. Write C/C++ programs using strings:
a. Checking for palindrome.
b. Count the occurrences of each character in a given word.
4. Generate salary slip of employees using structures and pointers. Create a structure
Employee with the following members:
EID, Ename, Designation, DOB, DOJ, Basicpay
Note that DOB and DOJ should be implemented using structure within structure.
5. Compute internal marks of students for five different subjects using structures and
functions.
6. Write a program Illustrating Class Declarations, Definition, and Accessing Class
Members.
7. Program to illustrate default constructor, parameterized constructor and copy
constructors
8. Write a Program to Demonstrate the i) Operator Overloading. ii) Function
Overloading.
9. Write a Program to Demonstrate Friend Function and Friend Class.
10. Program to demonstrate inline functions.
11. Program for Overriding of member functions.
12. Write C++ programs that illustrate how the following forms of inheritance are
supported:
a) Single inheritance b)Multiple inheritance c)Multi level inheritance d)Hierarchical
inheritance
13. Program to demonstrate pure virtual function implementation.
14. Count the number of account holders whose balance is less than the minimum
balance using sequential access file.
15. Write a Program to Demonstrate the Catching of all Exceptions.
16. Mini project.
TOTAL: 45+30 = 75 PERIODS
TEXT BOOKS:
1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015. (Unit 1 & 2)
2. E Balagurusamy,”Object Oriented Programming with C++”, 4th Edition, Tata McGraw-
Hill Education, 2008. (Unit 3, 4 & 5)

REFERENCES:
1. Nell Dale, Chip Weems, “Programming and Problem Solving with C++”, 5th Edition,
Jones and Barklett Publishers, 2010.
2. John Hubbard, “Schaum's Outline of Programming with C++”, MH, 2016.
3. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
4. ISRD Group, “Introduction to Object-oriented Programming and C++”, Tata McGraw-
Hill Publishing Company Ltd., 2007.
5. D. S. Malik, “C++ Programming: From Problem Analysis to Program Design”, Third
Edition, Thomson Course Technology, 2007.
6. https://infyspringboard.onwingspan.com/web/en/aptoclex_auth_01297200240671948
837_shared/overview
5. Course Outcomes

CO1: Solve problems using basic constructs in C.

CO2: Implement C programs using pointers and functions.

CO3: Apply object-oriented concepts and solve real world problems.

CO4: Develop C++ programs using operator overloading and polymorphism.

CO5: Implement C++ programs using Files and Exceptions.


6. CO - PO Mapping
POs and PSOs

PO10

PO11

PO12

PSO1

PSO2

PSO3
PO2

PO3

PO4

PO5

PO6
PO1

PO7

PO8

PO9
COs

CO1 3 3 3 3 3 2 1

CO2 3 3 3 3 3 3 3 1

CO3 3 3 3 3 3 3 3 3 3 3 3 3 1

CO4 3 3 3 3 3 3 3 1

CO5 3 3 3 3 3 3 3 1
7. Lecture Plan- Unit IV
No.
S. of Proposed Actual Pertaining Taxonomy Mode of
Topic
No. Period Date Lecture CO Level Delivery
s Date
27-11-
27-11-
1 C++ Streams 2023 Chalk &
1 2023 CO5 K2
Talk
27-11- 27-11-
2 Unformatted I/O 1 2023 2023 CO5 Chalk &
K3
Talk
28-11- 28-11-
Formatted Console I/O 1 2023 2023 CO5 Chalk &
3 K2
Talk
28-11- 28-11-
4 Opening and Closing File 1 2023 2023 CO5 Chalk &
K2
Talk
29-11- 29-11-
5 File Modes 1 2023 2023 CO5 Chalk &
K2
Talk
29-11- 29-11-
File pointers and their
6 1 2023 2023 CO5 Chalk &
manipulations K2
Talk
30-11- 30-11-
7 Templates 1 2023 2023 CO5 Chalk &
K3
Talk
30-11- 30-11-
8 Class Templates 1 2023 2023 CO5
K2
Chalk &
Talk
1-12-
1-12-
9 Function Templates 1 2023 CO5 Chalk &
2023 K2
Talk
2-12- 2-12-
10 Exception handling 1 CO5 Chalk &
2023 2023 K3
Talk
5-12- 5-12-
11 Usage of try Keyword 1 2023 2023 CO5 Chalk &
K2
Talk
6-12- 6-12-
12 Usage of catch Keyword 1 2023 2023 CO5 Chalk &
K2
Talk
6-12- 6-12-
13 Usage of throw Keyword 1 2023 2023 CO5 Chalk &
K2
Talk
7-12- 7-12-
14 Usage of catch (...) 1 2023 2023 CO5 Chalk &
K2
Talk
Programming 8-12-
8-12-
15 Illustration - Exception 1 2023 CO5 Chalk &
2023 K2
handling Talk
8. Activity Based Learning
Learning Method Activity

Tutorial Sessions available


Learn by Solving Problems
in Skill-rack for Practice

Quiz / MCQ Using RMK Next


Learn by Questioning
gen App

Learn by doing Hands-on Practice in Lab


9. Lecture Notes

UNIT V I/O, FILES AND EXCEPTIONS 15

C++ Streams – Unformatted I/O - Formatted Console I/O – Opening and


Closing File – File Modes - File pointers and their manipulations – Templates
– Class Templates – Function Templates - Exception handling.
5.1 C++ Streams
Introduction
C/C++ IO are based on streams, which are sequence of bytes flowing in and
out of the programs, just like water and oil flowing through a pipe.
In input operations, data bytes flow from an input source (such as keyboard, file, network
or another program) into the program.
In output operations, data bytes flow from the program to an output sink (such as
console, file, network or another program). Streams acts as an intermediaries between
the programs and the actual IO devices, in such the way that frees the programmers from
handling the actual devices, so as to archive device independent IO operations.

C++ provides both the formatted and unformatted IO functions.


In formatted or high-level IO, bytes are grouped and converted to types such as int,
double, string or user-defined types. Formatted IO operations are supported via
overloading the stream insertion (<<) and stream extraction (>>) operators, which
presents a consistent public IO interface.
In unformatted or low-level IO, bytes are treated as raw bytes and unconverted.
To perform input and output, a C++ program:
Construct a stream object.
 Connect the stream object to an actual IO device (e.g., keyboard, console, file,
network, another program).
 Perform input/output operations on the stream, via the functions defined in the
stream's public interface in a device independent manner
 Disconnect the stream to the actual IO device (e.g., close the file).
 Free the stream object.
5.1 C++ Streams
Input / Output Streams
In C++ stream refers to the stream of characters that are transferred
between the program thread and Input / Output. Stream classes in C++ are used to input
and output operations on files and Input/Output devices.
These classes have specific features and to handle input and output of the
program. The iostream.h library holds all the stream classes in the C++ programming
language.

ios class
This class is the base class for all stream classes. The streams can be input or output
streams. This class defines members that are independent of how the templates of the
class are defined.
istream Class
The istream class handles the input stream in c++ programming language. These input
stream objects are used to read and interpret the input as a sequence of characters. The
cin handles the input.
ostream class
The ostream class handles the output stream in c++ programming language. These
output stream objects are used to write data as a sequence of characters on the screen.
cout and puts handle the out streams in c++ programming language.
5.1 C++ Streams
Example Programs
Out Stream – cout
#include <iostream>
using namespace std;
int main()
{
cout<<"This output is printed on screen";
}
Output
This output is printed on screen
Out Stream – puts
#include <iostream>
using namespace std;
int main()
{
puts("This output is printed using puts");
}
Output
This output is printed using puts
In Stream – cin
#include <iostream>
using namespace std;
int main()
{
int no;
cout<<"Enter a number ";
cin>>no;
cout<<"Number entered using cin is “ << no;
Output
Enter a number 3453
Number entered using cin is 3453
5.1 C++ Streams
In Stream – gets
#include <iostream>
using namespace std;
int main()
{
char ch[15];
puts("Enter a character array");
gets(ch);
puts("The character array entered using gets is : ");
puts(ch);
}
Output
Enter a character array
Vijayakumar
The character array entered using gets is :
Vijayakumar

C++ IO Headers, Templates and Classes


C++ IO is provided in headers <iostream> (which included <ios>,
<istream>, <ostream> and <streambuf>), <fstream> (for file IO), and <sstream> (for
string IO). Furthermore, the header <iomanip> provided manipulators such as setw(),
setprecision()setfill() and setbase() for formatting.
UNFORMATTED I/O OPERATIONS
put() and get()
put() and get() are member functions of istream and ostream classes
For single character input/output operations
Example: char c;
cin.get(c)
c=cin.get();
put()-> used to output a line of text, character by character
Example: char c;
cout.put(‘x’);
cout.put(c);

getline() and write() take a line or sentence or a group of characters


getline(var, size)
Example
char name[10];
cin.getline(name,10);
cin>>name;
cout.write(name,10);

write()=> Displays the string of given size, if the size is greater than the
length of line, then it displays the bounds of line.
5.3 Formatted Input / Output
Introduction
Formatted output is carried out on streams via the stream insertion << and stream
extraction >> operators. For example,
cout << value;
cin >> variable;
Take note that cin/cout shall be the left operand and the data flow in the
direction of the arrows. The << and >> operators are overloaded to handle fundamental
types (such as int and double), and classes (such as string). We can also overload these
operators for our own user-defined types.
The cin << and cout >> return a reference to cin and cout, and thus,
support cascading operations. For example,
cout << value1 << value2 << .... ;
cin >> variable1 << variable2 << .... ;
The iomanip.h and iostream.h header files are used to perform the formatted IO
operations in C++.
The C++ programming language provides the several built-in functions to
display the output in formatted form. These built-in functions are available in the header
file iomanip.h and ios class of header file iostream.h.
In C++, there are two ways to perform the formatted IO operations.
 Using the member functions of ios class.
 Using the special functions called manipulators defined in iomanip.h.
Formatted IO using ios class members
The ios class contains several member functions that are used to perform formatted IO
operations. The ios class also contains few format flags used to format the output. It has
format flags like showpos, showbase, oct, hex, etc. The format flags are used by the
function setf( ).
The following table provides the details of the functions of ios class used to
perform formatted IO in C++.
5.3 Formatted Input / Output
The following table provides the details of the functions of ios class used to perform
formatted IO in C++.

S.No. Function Description


Used to set the width in number of character
1 width(int)
spaces for the immediate output data.
Used to fill the blank spaces in output with
2 fill(char)
given character.
Used to set the number of the decimal point
3 precision(int)
to a float value.
Used to set various flags for formatting output
4 setf(format flags)
like showbase, showpos, oct, hex, etc.

5 unsetf(format flags) Used to clear the format flag setting.

All the above functions are called using the built-in object cout.
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << "Example for formatted IO" << endl;
cout << "Default: " << endl;
cout << 123 << endl;
cout << "width(5): " << endl;
cout.width(5);
cout << 123 << endl;
cout << "width(5) and fill('*'): " << endl;
cout.width(5);
cout.fill('*');
cout << 123 << endl;
5.3 Formatted Input / Output
cout.precision(5);
cout << "precision(5) ---> " << 123.4567890 << endl;
cout << "precision(5) ---> " << 9.876543210 << endl;

cout << "setf(showpos): " << endl;


cout.setf(ios::showpos);
cout << 123 << endl;

cout << "unsetf(showpos): " << endl;


cout.unsetf(ios::showpos);
cout << 123 << endl;

return 0;
}
Output
Example for formatted IO
Default:
123
width(5):
123
width(5) and fill('*'):
**123
precision(5) ---> 123.46
precision(5) ---> 9.8765
setf(showpos):
+123
unsetf(showpos):
123
5.3 Formatted Input / Output
Formatted IO using manipulators
The iomanip.h header file contains several special functions that are used to
perform formatted IO operations. The following table provides the details of the special
manipulator functions used to perform formatted IO in C++.

S.No. Function Description


Used to set the width in number of characters
1 setw(int)
for the immediate output data.
Used to fill the blank spaces in output with
2 setfill(char)
given character.

3 setprecision(int) Used to set the number of digits of precision.

4 setbase(int) Used to set the number base.

5 setiosflags(format flags) Used to set the format flag.


resetiosflags(format
6 flags)
Used to clear the format flag.

The iomanip.h also contains the following format flags using in formatted IO in C++.

S.No. Function Description

1 endl Used to move the cursor position to a newline.

2 ends Used to print a blank space (null character).

3 dec Used to set the decimal flag.

4 oct Used to set the octal flag.

5 hex Used to set the hexadecimal flag.

6 left Used to set the left alignment flag.

7 right Used to set the right alignment flag.

8 showbase Used to set the showbase flag.

9 noshowbase Used to set the noshowbase flag.

10 showpos Used to set the showpos flag.

11 noshowpos Used to set the noshowpos flag.

12 showpoit Used to set the showpoit flag.

13 noshowpoint Used to set the noshowpoint flag.


5.3 Formatted Input / Output
Program
#include <iostream>
#include<iomanip>
#include <fstream>
using namespace std;

void line() {
cout << "-------------------------------" << endl;
}
int main()
{
cout << "Example for Formatted IO Using Manipulators" << endl;
line();
cout << "setw(10): " << endl;
cout << setw(10) << 99 << endl;
line();
cout << "setw(10) and setfill('*'): " << endl;
cout << setw(10) << setfill('*') << 99 << endl;
line();
cout << "setprecision(5): " << endl;
cout << setprecision(5) << 123.4567890 << endl;
line();
cout << "showpos: " << endl;
cout << showpos << 999 << endl;
line();
cout << "hex: " << endl;
cout << hex << 100 << endl;
line();
cout << "hex and showbase: " << endl;
cout << showbase << hex << 100 << endl;
line();
return 0;
}
5.3 Formatted Input / Output
Output
Example for Formatted IO Using Manipulators
-------------------------------
setw(10):
99
-------------------------------
setw(10) and setfill('*'):
********99
-------------------------------
setprecision(5):
123.46
-------------------------------
showpos:
+999
-------------------------------
hex:
64
-------------------------------
hex and showbase:
0x64
-------------------------------
5.4 Opening and Closing File and 5.5 File Modes
Introduction
Files store data permanently in a storage device. With file handling, the
output from a program can be stored in a file. Various operations can be performed on
the data while in the file.
Achieve the File Handling
For achieving file handling we need to follow the following steps:-
Step 1 : Create a File.
Step 2 : Opening a file.
Step 3 : Writing data into the file
Step 4 : Reading data from the file
Step 5 : Closing a file.
The fstream Library
The fstream library provides C++ programmers with three classes for working with files.
These classes include:
Ofstream : This class represents an output stream. It’s used for creating files and writing
information to files.
Ifstream : This class represents an input stream. It’s used for reading information from
data files.
Fstream : This class generally represents a file stream. It comes with ofstream/ifstream
capabilities. This means it’s capable of creating files, writing to files, reading from data
files. The following image makes it simple to understand:
5.4 Opening and Closing File and 5.5 File Modes
To Open a Files
Before performing any operation on a file, it must be opened first.
If you need to write to the file, open it using fstream or ofstream objects.
If you only need to read from the file, open it using the ifstream object.
The three objects, that is, fstream, ofstream, and ifstream, have the open() function
defined in them. The function takes this syntax:
open (file_name, mode);
The file_name parameter denotes the name of the file to open.
The mode parameter is optional. It can take any of the following values:

S.No. Value Description


The Append mode. The output sent to the file is appended to
1 ios:: app
it.
It opens the file for the output then moves the read and write
2 ios::ate
control to file’s end.
3 ios::in It opens the file for a read.

4 ios::out It opens the file for a write.


If a file exists, the file elements should be truncated prior to its
5 ios::trunc
opening.
It is possible to use two modes at the same time. You combine them using the | (OR)
operator.
Program Output
#include <iostream> File created successfully!
#include <fstream>
using namespace std;
int main()
{
fstream my_file;
my_file.open("my_file", ios::out);
if (!my_file)
{
cout << "File not created!";
}
else
{
cout << "File created successfully!";
my_file.close();
}
return 0;
}
5.4 Opening and Closing File and 5.5 File Modes
5.4 Opening and Closing File and 5.5 File Modes
Explanation:
1. Include the iostream header file in the program to use its functions.
2. Include the fstream header file in the program to use its classes.
3. Include the std namespace in our code to use its classes without calling it.
4. Call the main() function. The program logic should go within its body.
5. Create an object of the fstream class and give it the name my_file.
6. Apply the open() function on the above object to create a new file. The out mode
allows us to write into the file.
7. Use if statement to check whether file creation failed.
8. Message to print on the console if the file was not created.
9. End of the body of if statement.
10. Use an else statement to state what to do if the file was created.
11. Message to print on the console if the file was created.
12. Apply the close() function on the object to close the file.
13. End of the body of the else statement.
14. The program must return value if it completes successfully.
15. End of the main() function body.

To Close Files

Once a C++ program terminates, it automatically


flushes the streams
releases the allocated memory
closes opened files.
However, as a programmer, you should learn to close open files before the program
terminates. The fstream, ofstream, and ifstream objects have the close() function for
closing files. The function takes this syntax:

void close();
5.4 Opening and Closing File and 5.5 File Modes
To Write to Files
We can write to file right from your C++ program. We can use stream
insertion operator (<<) for this. The text to be written to the file should be enclosed
within double-quotes.
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream my_file;
my_file.open("my_file.txt", ios::out);
if (!my_file)
{
cout << "File not created!";
}
else
{
cout << "File created successfully!";
my_file << "Welcome to Files in C++";
my_file.close();
}
return 0;
}
Code Explanation:
1. Include the iostream header file in the program to use its functions.
2. Include the fstream header file in the program to use its classes.
3. Include the std namespace in the program to use its classes without calling it.
5.4 Opening and Closing File and 5.5 File Modes

Code Explanation: contd…


4. Call the main() function. The program logic should be added within the body of this
function.
5. Create an instance of the fstream class and give it the name my_file.
6. Use the open() function to create a new file named my_file.txt. The file will be opened
in the out mode for writing into it.
7. Use an if statement to check whether the file has not been opened.
8. Text to print on the console if the file is not opened.
9. End of the body of the if statement.
10. Use an else statement to state what to do if the file was created.
11. Text to print on the console if the file was created.
12. Write some text to the created file.
13. Use the close() function to close the file.
14. End of the body of the else statement.
15. The program must return value upon successful completion.
16. End of the body of the main() function.

To Read from Files


We can read information from files into your C++ program. This is possible
using stream extraction operator (>>). We use the operator in the same way We use it to
read user input from the keyboard. However, instead of using the cin object, We use the
ifstream/ fstream object.
Program Example
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream my_file;
my_file.open("my_file.txt", ios::in);
if (!my_file) {
cout << "No such file";
}
5.4 Opening and Closing File and 5.5 File Modes

else {
char ch;
while (1) {
my_file >> ch;
if (my_file.eof())
break;
cout << ch;
}
}
my_file.close();
return 0;
}
Output
Welcome to Files in C++
Code Explanation:
1. Include the iostream header file in the program to use its functions.
2. Include the fstream header file in the program to use its classes.
3. Include the std namespace in the program to use its classes without calling it.
4. Call the main() function. The program logic should be added within the body of this
function.
5. Create an instance of the fstream class and give it the name my_file.
6. Use the open() function to create a new file named my_file.txt. The file will be opened
in the in mode for reading from it.
7. Use an if statement to check whether the file does not exist.
8. Text to print on the console if the file is not found.
9. End of the body of the if statement.
10. Use an else statement to state what to do if the file is found.
11. Create a char variable named ch.
12. Create a while loop for iterating over the file contents.
13. Write/store contents of the file in the variable ch.
5.4 Opening and Closing File and 5.5 File Modes

14. Use an if condition and eof() function that is, end of the file, to ensure the compiler
keeps on reading from the file if the end is not reached.
15. Use a break statement to stop reading from the file once the end is reached.
16. Print the contents of variable ch on the console.
17. End of the while body.
18. End of the body of the else statement.
19. Call the close() function to close the file.
20. The program must return value upon successful completion.
21. End of the body of the main() function.
5.6 File Pointers and Manipulations
Introduction
A pointer is used to handle and keep track of the files being accessed. Every
file maintains two pointers called get_pointer (in input mode file) and put_pointer (in
output mode file), which tells the current position where reading or writing will take place
with the use of opening modes and their respective manipulators.
These pointers help attain random access to the file. Like Moving at once to
any area with inside the record rather than shifting through it sequentially.
Function for manipulation of file pointer
The C++ I/O system support for function for setting a file pointer to any desired position
inside the file or to get the file pointer. These allow the programmer to have control over
a pointer in the file where read or write operation text place. These for function are listed
below.

S.No Member
Function Action Performed
. of Class

seekg() is used to move the get


1 seekg() ifstream pointer to the desired location
concerning a reference point.

seekp() is used to move the put


2 seekp() ofstream pointer to the desired location
concerning a reference point.

Returns the current position of the


3 tellg() ifstream
get pointer

Returns the current position of the


4 tellp() ofstream
put pointer

The reference points are:


ios::beg - These are used from the beginning of the file
ios::end - These are used from the end of the file
ios::cur -– These are used from the current position in the file.
5.6 File Pointers and Manipulations
Introduction

S.No. Function Syntax Example

file_pointer.seekg (number of bytes


1 seekg() ,Reference point);
fin.seekg(10,ios::beg);

file_pointer.seekp(number of bytes
2 seekp() fout.seekp(10,ios::beg);
,Reference point);

3 tellg() file_pointer.tellg(); int posn = fin.tellg();

4 tellp() file_pointer.tellp(); int posn=fout.tellp();

Files Usage
1. Data Preservation: Storing files in documents allows to hold records even though
this system terminates.
2. Easy Data Access: Accessing records will become easy whilst there may be a large
number of records and it’s far saved with inside the record, then these files may be
accessed the use of the C++ commands.
3. Portability: It will become less difficult to switch records from one PC to any other
with no changes.
Seekg() and tellg()
5.7 Templates
Introduction
Templates are powerful features of C++ which allows us to write generic
programs. Generic Programming is an approach to programming where generic types are
used as parameters in algorithms to work for a variety of data types. To avoid having to
write the same code for many data types, the simple concept is to pass the data type as a
parameter.
There are two ways we can implement templates:
 Function Templates
 Class Templates
Templates in C++ is an interesting feature that is used for generic
programming and templates in c++ is defined as a blueprint or formula for creating a
generic class or a function. Simply put, we can create a single function or single class to
work with different data types using templates.
Function Template
Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
 The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
 For example, Quick sorting algorithm is implemented using a generic function, it can
be implemented to an array of integers or array of floats.
 A Generic function is created by using the keyword template. The template defines
what function will do.

Class Template
Class Template can also be defined similarly to the Function Template. When a class
uses the concept of Template, then the class is known as generic class.
5.8 Class Templates
Introduction
Class Template can also be defined similarly to the Function Template. When a class uses
the concept of Template, then the class is known as generic class.
Syntax
template<class Ttype>
class class_name
{
.
.
}
Ttype is a placeholder name which will be determined when the class is instantiated. We
can define more than one generic data type using a comma-separated list. The Ttype can
be used inside the class body.
Now, we create an instance of a class
class_name<type> ob;
Where
class_name: It is the name of the class.
type: It is the type of the data that the class is operating on.
ob: It is the name of the object.
Example Program
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<
std::endl;
}
5.8 Class Templates
};

int main()
{
A<int> d;
d.add();
return 0;
}
Output
Addition of num1 and num2 : 11

Class Template With Multiple Parameters


We can use more than one generic data type in a class template, and each generic data
type is separated by the comma.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
Example Program
#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
5.8 Class Templates
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
std::cout << "Values of a and b are : " << a<<" ,
"<<b<<std::endl;
}
};

int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
Output:
Values of a and b are : 5,6.5
5.9 Function Templates
Introduction
Function Template
Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
 The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
 For example, Quick sorting algorithm is implemented using a generic function, it can
be implemented to an array of integers or array of floats.
 A Generic function is created by using the keyword template. The template defines
what function will do.

Syntax of Function Template

template < class Ttype> ret_type func_name(parameter_list)


{
// body of function.
}

Where Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will automatically
replace this placeholder with the actual data type.
class: A class keyword is used to specify a generic type in a
template declaration.
5.9 Function Templates
Program

#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b) {
return a < b ? b:a;
}
int main () {
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
Output
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
5.9 Function Templates
Advantages of Using Templates in C++
 Templates are type-safe. (Type safety means that the compiler will validate types
while compiling, and throw an error if we try to assign the wrong type to a variable)
 They are generally considered as an improvement over macros for these purposes.
 Templates avoid some common errors found in code that make heavy use of
function-like macros.
 Both templates and macros are expanded at compile time.
 They are a good way of making generalizations for APIs.
Disadvantages of Using Templates in C++
 Many compilers do not support nesting of templates.
 When templates are used, all codes exposed.
 Some compilers have poor support of templates.
 All compilers produce unhelpful, confusing error messages when errors are
detected in the template code.
 It can make it challenging to develop the template.
5.10 Exception Handling
Introduction
Errors are the problems that occur in the program due to an illegal operation
performed by the user or by the fault of a programmer. When executing C++ code,
different errors can occur: coding errors made by the programmer, errors due to wrong
input, or other unforeseeable things.
Exception
An exception is a problem that arises during the execution of a program. A
C++ exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
Exception Handling
Exception Handling in C++ is a process to handle runtime errors. We
perform exception handling so that normal flow of the application can be maintained even
after runtime errors.
In C++, exception is an event or object which is thrown at runtime. All
exceptions are derived from std::exception class. It is a runtime error which can be
handled. If we don't handle the exception, it prints exception message and terminates the
program.
C++ exception handling is built upon three keywords: try, catch, and throw.
Syntax

try
{
// Block of code to try

throw exception;
}

catch ()
{
// Block of code to handle errors
}
Code within a try/catch block is referred to as protected code
5.10 Exception Handling
Main advantages of exception handling over traditional error handling:
1. Separation of Error Handling code from Normal Code: In traditional error
handling codes, there are always if-else conditions to handle errors. These conditions
and the code to handle errors get mixed up with the normal flow. This makes the code
less readable and maintainable. With try/catch blocks, the code for error handling
becomes separate from the normal flow.
2. Functions/Methods can handle only the exceptions they choose: A function
can throw many exceptions, but may choose to handle some of them. The other
exceptions, which are thrown but not caught, can be handled by the caller. If the caller
chooses not to catch them, then the exceptions are handled by the caller of the caller.
3. Grouping of Error Types: In C++, both basic types and objects can be thrown as
exceptions. We can create a hierarchy of exception objects, group exceptions in
namespaces or classes and categorize them according to their types.
In C++, a function can pecify the exceptions that it throws using the throw
keyword. The caller of this function must handle the exception in some way (either by
specifying it again or catching it).
All the exception classes in C++ are derived from std::exception class. Let's see
the list of C++ common exception classes.

S.No. Exception Description

It is an exception and parent class of all standard C++


1 std::exception
exceptions.
It is an exception that can be detected by reading a
2 std::logic_failure
code.
It is an exception that cannot be detected by reading
3 std::runtime_error
a code.
It is used to handle the unexpected exceptions in a
4 std::bad_exception
c++ program.
This exception is generally be thrown by
5 std::bad_cast
dynamic_cast.
6 std::bad_typeid This exception is generally be thrown by typeid.

7 std::bad_alloc This exception is generally be thrown by new.


5.11 Usage of try keyword
The try statement allows you to define a block of code to be tested for
errors while it is being executed.
We use a try block to indicate which areas in our program that might throw
exceptions we want to handle immediately. We use a function try block to indicate that we
want to detect exceptions in the entire body of a function.

Syntax:
try
{
// the protected code
}
catch( Exception_Name exception1 )
{
// catch block
}
catch( Exception_Name exception2 )
{
// catch block
}
catch( Exception_Name exceptionN )
{
// catch block
}
5.12 Usage of throw Keyword
The throw keyword throws an exception when a problem is detected, which lets us create
a custom error.
Exceptions can be thrown anywhere within a code block using throw
statement. The operand of the throw statement determines a type for the exception and
can be any expression and the type of the result of the expression determines the type of
exception thrown.
In C++, we may use throw keyword when we explicitly want to throw an
exception. The keyword throw is followed by a variable of a primitive data-type or an
object of a type that we want to throw. Using throw keyword, an exception can be
explicitly thrown from within the two places in a program
 try-block or
 catch-block.

Syntax
try
{
// Block of code to try
throw exception;
}
catch ()
{
// Block of code to handle errors
}
5.13 Usage of catch keyword
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
The catch block following the try block catches any exception. we can
specify what type of exception we want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.

try
{
// protected code
} catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type

we have only seen one catch block associated with a try block. But it is also
possible to have multiple catch blocks associated with one try block.
Multiple catch blocks are used when we have to catch a specific type of
exception out of many possible type of exceptions i.e. an exception of type char or int or
short or long etc. Let's see the use of multiple catch blocks with an example
try
{
}
catch(ExceptionType e) //catch block to handle/catch
exception
{
}
catch(ExceptionType e) //catch block to handle/catch
exception
{
}
catch(ExceptionType e) //catch block to handle/catch
exception
{
}
5.14 Usage of catch(…)
If we want to specify that a catch block should handle any type of exception that is

thrown in a try block, we must put an ellipsis, ... between the parentheses enclosing the
exception declaration as follows

try
{
// protected code
} catch(...)
{
// code to handle any exception
}
5.15 Programming Illustration -
Exception handling
Program 1
#include<iostream>
using namespace std;
int main()
{
int num1, num2, num3;
float result;
cout << "Enter the value of first integer: ";
cin>>num1;
cout << "Enter the value of second integer :";
cin>>num2;
cout << "Enter the value of third integer :";
cin>>num3;

try
{
if ((num1 - num2) != 0)
{
result = num3 / (num1 - num2);
cout << "Result is : " << result;
} else
{
throw (num1 - num2);
}
}
catch (int i)
{
cout << "Answer is infinite because number 1 - number 2 is : " << i;
}
return 0;
}
Output 1
Enter the value of first integer: 20
Enter the value of second integer :20
Enter the value of third integer :25
Answer is infinite because number 1 - number 2 is : 0
Output 2
Enter the value of first integer: 30
Enter the value of second integer :20
Enter the value of third integer :10
Result is : 1
5.15 Programming Illustration -
Exception handling
Program 2
#include <iostream>
using namespace std;

int main()
{
// checking if the age is more than 18 in tr block.
try
{
int age = 15;
if (age >= 18)
{
cout << "Access granted.";
}
// Throwing custom exception if the age is less than 18.
else
{
throw(age);
}
}
// catching the thrown exception and displaying the desired output
(access denied!)
catch (int x)
{
cout << "Access denied!, Age is: " << x << endl;
}
return 0;
}

Output
Access denied!, Age is: 15
5.15 Programming Illustration -
Exception handling
Program 3
#include <iostream>
using namespace std;

int main()
{
int x = 99;
cout << "Before the try block." << endl;
try
{
cout << "Inside the try block." << endl;
// Throwing an exception if the
// value of x is smaller than 100.
if (x < 100)
{
// Throwing the value of x as exception as x is now less than 100.
throw x;
cout << "After throw the throw block." << endl;
}
}
// Catching the value of x thrown by the throw keyword
from the try block.
catch (int x)
{
cout << "Exception caught in the catch block." << endl;
}
return 0;
}

Output

Before the try block.


Inside the try block.
Exception caught in the catch block.
5.15 Programming Illustration -
Exception handling
Program 4
#include <iostream>
using namespace std;

double division(int num1, int num2);


const char* msg = "Error... Division by Zero condition
!!!";

int main ()
{
int firstnum = 0;
int secondnum = 0;
double result = 0.0;

cout << "Enter the First Number : ";


cin >>firstnum;
cout << "Enter the Second Number : ";
cin >>secondnum;
try
{
result = division(firstnum, secondnum);
cout << "The result of division operation is : " <<
result << endl;
}

catch (const char* msg)


{
cout << msg << endl;
}

catch (int e)
{
cout << "Error... Result of Division is Undefined
!!!" << endl;
}
catch (...)
{
cout << "Error... Inputs are not Valid !!! for
division operation" << endl;
}
return 0;
}
5.15 Programming Illustration -
Exception handling
Program 4 contd...
double division(int num1, int num2)
{
if (num1==0 && num2 ==0)
{
throw 0;
}
if( num2 == 0 )
{
throw msg;;
}
if( num2 == 1 )
{
throw 1.1;
}
return (num1/num2);
}

Output 1 No Exception
Enter the First Number : 25
Enter the Second Number : 5
The result of division operation is : 5
Output 2 throw msg – Char Type - Handled by catch (const char* msg)
Enter the First Number : 25
Enter the Second Number : 0
Error... Division by Zero condition !!!
Output 3 throw 0 – Integer Type - Handled by catch (int e)
Enter the First Number : 0
Enter the Second Number : 0
Error... Result of Division is Undefined !!!
Output 4 throw 1.1 Any Type - Handled by catch (...)
Enter the First Number : 25
Enter the Second Number : 1
Error... Inputs are not Valid !!! for division operation
10. Assignment Questions
K-
S.No. Write Programs for the following COs
Level
Library Management using File and Exception
Handling
Features
 Add books
 Admin login
 User name and password
1  Delete books K3 CO4
 Update books
 List of complete books store the file and delete
the books in file
 Borrow the books of students 5 days for free
otherwise per day 500 fine charge
11. Part A
Question & Answer
11. Part A Question & Answer
1. Illustrate C++ IO Streams with Neat Diagram (CO5, K1)

2. Illustrate IOS Class Hierarchy (CO5, K1)

3. Give brief note on ios class (CO5, K1)

This class is the base class for all stream classes. The streams can be
input or output streams. This class defines members that are independent of how the
templates of the class are defined

4. Discuss istream and ostream class (CO5, K2)

istream class : The istream class handles the input stream in c++ programming
language. These input stream objects are used to read and interpret the input as a
sequence of characters. The cin handles the input.

ostream class: The ostream class handles the output stream in c++ programming
language. These output stream objects are used to write data as a sequence of
characters on the screen. cout and puts handle the out streams in c++ programming
language
11. Part A Question & Answer
5. Illustrate out stream cout with simple C++ Program (CO5, K2)
#include <iostream>
using namespace std;
int main()
{
cout << "This output is printed on screen";
}
Output
This output is printed on screen
6. Illustrate out stream puts with simple C++ Program (CO5, K2)

#include <iostream>
using namespace std;
int main()
{
puts("This output is printed using puts");
}
Output
This output is printed using puts
7. Illustrate in stream cin with simple C++ Program (CO5, K2)
#include <iostream>
using namespace std;
int main()
{
int no;
cout<<"Enter a number ";
cin>>no;
cout<<"Number entered using cin is “ << no;

Output
Enter a number 3453
Number entered using cin is 3453
8. Illustrate instream gets with simple C++ Program (CO5, K2)
#include <iostream>
using namespace std;
int main()
{
char ch[15];
puts("Enter a character array");
gets(ch);
puts("The character array entered using gets is : ");
puts(ch);
}
Output
Enter a character array
Vijayakumar
The character array entered using gets is :
Vijayakumar
11. Part A Question & Answer
9. How Formatted out put is done in C++? (CO5, K2)
Formatted output is carried out on streams via the stream insertion << and stream
extraction >> operators. For example,
cout << value;
cin >> variable;
The iomanip.h and iostream.h header files are used to perform the formatted IO
operations in C++.

10. Mention the ways to perform the formatted IO operations. In C++. (CO5, K1)

In C++, there are two ways to perform the formatted IO operations.

 Using the member functions of ios class.

 Using the special functions called manipulators defined in iomanip.h.

11. List the functions of ios class used to perform formatted IO in C++. (CO5, K2)

List of ios Functions are


width(int)
fill(char)
precision(int)
setf(format flags)
unsetf(format flags)

12. List and state the purpose of any two functions of ios class used to
perform formatted IO in C++. (CO5, K1)

 width(int) - Used to set the width in number of character spaces for the immediate
output data.
 precision(int) - Used to set the number of the decimal point to a float value.
13. Discuss about Formatted IO using manipulators (CO5, K1)
setw(int) - Used to set the width in number of characters for the immediate output
data.
setfill(char) - Used to fill the blank spaces in output with given character.
setprecision(int) - Used to set the number of digits of precision.
setbase(int) - Used to set the number base.
setiosflags(format flags) - Used to set the format flag.
resetiosflags(format flags) - Used to clear the format flag.
11. Part A Question & Answer
14. List the iomanip.h format flags used in formatted IO in C++. (CO5, K1)
endl - Used to move the cursor position to a newline.
left - Used to set the left alignment flag.
right - Used to set the right alignment flag.
showbase - Used to set the showbase flag.
showpos - Used to set the showpos flag.
15. What are the steps to be followed for File Handling? (CO5, K2)
For achieving file handling we need to follow the following steps:-
Step 1 : Create a File.
Step 2 : Opening a file.
Step 3 : Writing data into the file
Step 4 : Reading data from the file
Step 5 : Closing a file.

16. Give the syntax to open a file (CO5, K2)

The function takes this syntax:


open (file_name, mode);

17. List the various file modes (CO5, K1)

ios::app - The Append mode. The output sent to the file is appended to it.
ios::ate - It opens the file for the output then moves the read and write control to file’s end .
ios::in - It opens the file for a read.
ios::out - It opens the file for a write.
ios::trunc - If a file exists, the file elements should be truncated prior to its opening.

18. Write a function to show file writing. (CO5, K2)


int main()
{
fstream my_file;
my_file.open("my_file.txt", ios::out);
if (!my_file) {
cout << "File not created!";
}
else {
cout << "File created successfully!";
my_file << "Welcome to Files in C++";
my_file.close();
}
return 0;
}
11. Part A Question & Answer
19. Write note on Function for manipulation of file pointer (CO5, K2)
1 seekg() - is used to move the get pointer to the desired location concerning a
reference point.
2 seekp() - is used to move the put pointer to the desired location concerning a
reference point.
3 tellg() - Returns the current position of the get pointer
4 tellp() - Returns the current position of the put pointer

20. Write Function and Syntax for manipulation of file pointer (CO5, K2)
seekg() - file_pointer.seekg (number of bytes,Reference point);
seekp() - file_pointer.seekp(number of bytes,Reference point);
tellg() - file_pointer.tellg();
tellp() - file_pointer.tellp();

21. What are the usages of File (CO5, K2)

Data Preservation: Storing files in documents allows to hold records even though
this system terminates.

Easy Data Access: Accessing records will become easy whilst there may be a large
number of records and it’s far saved with inside the record, then these files may be
accessed the use of the C++ commands.

Portability: It will become less difficult to switch records from one PC to any other
with no changes

22. Define Templates (CO5, K2)

Templates in C++ is an interesting feature that is used for generic programming and
templates in C++ is defined as a blueprint or formula for creating a generic class or a
function.

23. How can we implement Templates (CO5, K2)

There are two ways we can implement templates:

 Function Templates

 Class Templates
11. Part A Question & Answer
24 Illustrate the syntax for class template (CO5, K2)
Class Template can also be defined similarly to the Function Template. When a class
uses the concept of Template, then the class is known as generic class.
Syntax
template<class Ttype>
class class_name
{
.
.
}

25. How an object for a class template is created? (CO5, K2)


we create an instance of a class
class_name<type> ob;
Where
class_name: It is the name of the class.
type: It is the type of the data that the class is operating on.
ob: It is the name of the object.

26. Is it possible to create Class Template With Multiple Parameters ? (CO5, K2)
Yes, it possible to create Class Template With Multiple Parameters
We can use more than one generic data type in a class template, and each generic
data type is separated by the comma.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}

27. Define Function Template (CO5, K2)


Generic functions use the concept of a function template. Generic functions define a
set of operations that can be applied to the various types of data. The type of the data
that the function will operate on depends on the type of the data passed as a
parameter

28. Write the Syntax for Function Template (CO5, K2)


template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
11. Part A Question & Answer
29. List out the Advantages of Using Templates in C++ (CO5, K1)
 Templates are type-safe. (Type safety means that the compiler will validate types
 while compiling, and throw an error if we try to assign the wrong type to a
variable)
 They are generally considered as an improvement over macros for these
purposes.
 Templates avoid some common errors found in code that make heavy use of
function-like macros.

30. List out the Disadvantages of Using Templates in C++ (CO5, K2)
 Many compilers do not support nesting of templates.
 When templates are used, all codes exposed.
 Some compilers have poor support of templates

31. Define Exception Handling (CO5, K2)


Exception Handling in C++ is a process to handle runtime errors. We perform
exception handling so that normal flow of the application can be maintained even
after runtime errors.

32. How Exception Handling is done in C++. (CO5, K2)


C++ exception handling is built upon three keywords: try, catch, and throw.

33. Illustrate the syntax for Exception Handling in C++. (CO5, K2)
try
{
// Block of code to try
throw exception;
}
catch ()
{
// Block of code to handle errors
}
Code within a try/catch block is referred to as protected
code

34. List Main advantages of exception handling over traditional error


handling. (CO5, K2)
 Separation of Error Handling code from Normal Code
 Functions/Methods can handle only the exceptions they choose
 Grouping of Error Types
11. Part A Question & Answer
35. Illustrate the multiple catch in exception handling (CO5, K2)
Syntax:
try
{
// the protected code
}
catch( Exception_Name exception1 )
{
// catch block
}
catch( Exception_Name exception2 )
{
// catch block
}
catch( Exception_Name exceptionN )
{
// catch block
}

36.Illustrate the multiple exception of any type in single catch. (CO5, K2)
If we want to specify that a catch block should handle any type of exception that is
thrown in a try block, we must put an ellipsis, ... between the parentheses enclosing
the exception declaration as follows
try
{
// protected code
} catch(...)
{
// code to handle any exception
12. Part B Questions
12.PART – B Questions
1. Explain C++ IO Streams (CO5, K2)
2. Write a program to illustrate C++ IO Streams (CO5, K3)
3. Explain C++ Unformatted I/O Streams (CO5, K2)
4. Write a program to illustrate C++ Unformatted I/O (CO5, K3)
5. Explain C++ Formatted Console I/O (CO5, K2)
6. Write a program to illustrate C++ Formatted Console I/O (CO5, K3)
7. Explain C++ features to Open and Close File in C++. (CO5, K2)
8. Write a program to illustrate to Open and Close File in C++. (CO5, K3)
9. Explain C++ File modes. (CO5, K2)
10. Write a program to illustrate C++ File modes. (CO5, K3)
11. Explain and write a C++ program to demonstrate File pointers and their
manipulations (CO5, K3)
12. Explain and write a C++ program to demonstrate Templates (CO5, K3)
13. Explain and write a C++ program to demonstrate Class Templates (CO5, K3)
14. Explain and write a C++ program to demonstrate Function Templates. (CO5, K3)
15. Explain and write a C++ program to demonstrate Exception handling. (CO5, K3)
13. Supportive online courses

❖ https://nptel.ac.in/courses/106105151
❖ https://nptel.ac.in/courses/106101208
❖ https://www.codecademy.com/learn/learn-c-plus-plus
❖ https://www.udemy.com/topic/c-plus-plus/
❖ https://www.edx.org/learn/c-plus-plus
❖ https://in.coursera.org/specializations/hands-on-cpp
❖ https://www.simplilearn.com/free-course-to-learn-cpp-basics-skillup
❖ https://www.codespaces.com/best-c-plus-plus-courses-tutorials-
certifications.html
❖ https://hackr.io/blog/cpp-course
❖ https://www.udacity.com/course/c-for-programmers--ud210

External Links for Additional Resources

❖ https://swayam.gov.in
❖ https://www.coursera.org
❖ https://www.udemy.com
❖ https://unacademy.com
❖ https://www.sololearn.com
❖ https://www.tutorialspoint.com
❖ https://www.w3schools.in
❖ https://www.geeksforgeeks.org
❖ https://www.programiz.com
14. Real Time Applications

Exception handling is used when the frequency of occurrence of any


exception cannot be predicted.
Real World Examples:
When providing a web form to the users to fill in and submit. In case
there are a lot of conditions to be satisfied and the conditions keeps
changing periodically, Using exception handling will simplify the process.

Database connectivity uses exception handling because the reason for


database connectivity failure cannot be predicted, Because failure can be
caused by various factors like power failure, unreachable server, failure at
client front/back end and so on.

Arithmetic exceptions such as division by zero and so on.

Operating systems use exception handling to resolve deadlocks, recover


from crash and so on
15. Content Beyond Syllabus (CO5, K6)
E-mail Validation:
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
// Function to check the character is an alphabet or not
bool isChar(char c)
{
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}

// Function to check the character is an digit or not


bool isDigit(const char c)
{
return (c >= '0' && c <= '9');
}

// Function to check email id is valid or not


bool is_valid(string email)
{

try
{
// Check the first character is an alphabet or not
if (!isChar(email[0]))
{

// If it's not an alphabet email id is not valid


throw 1.1f;
}
// Variable to store position of At and Dot
int At = -1, Dot = -1;
// Traverse over the email id string to find position of Dot and At
for (int i = 0;i < email.length(); i++)
{

// If the character is '@'


if (email[i] == '@')
{
At = i;
}

// If character is '.'
else if (email[i] == '.')
{
Dot = i;
}
}
15. Content Beyond Syllabus
// If At or Dot is not present
if (At == -1 || Dot == -1)
throw 1;

// If Dot is present before At


if (At > Dot)
throw 1.1;

// If Dot is present at the end


return !(Dot >= (email.length() - 1));

}
catch( int e)
{
cout << "Dot . or At @ is not Present... Invalid Email
ID !!!" << endl;
return 0;
}
catch( double e)
{
cout << "Dot . Position is not Correct... Invalid Email
ID !!!" << endl;
return 0;
}
catch( float e)
{
cout << "Starts with Number ... Invalid Email ID !!!"
<< endl;
return 0;
}

return 0;
}
15. Content Beyond Syllabus
// Driver Code
int main()
{
// Given string email
string email;
cout << endl << "Enter Email Id : ";
cin >> email;
// Function Call
bool valid = is_valid(email);

// Print the result


if (valid)
{
cout << email << " : " << "Valid" << endl;
}
else
{
cout << email << " : " << "Invalid" << endl;
}
return 0;
}
15. Content Beyond Syllabus

Output 1
Enter Email Id : [email protected]
[email protected] : Valid

Output 2
Enter Email Id : [email protected]
Starts with Number ... Invalid Email ID !!!
[email protected] : Invalid

Output 3
Enter Email Id : vijayakumar.gmail@com
Dot . Position is not Correct... Invalid Email ID !!!
vijayakumar.gmail@com : Invalid

Output 4
Enter Email Id : vijayakumar@gmailcom
Dot . or At @ is not Present... Invalid Email ID !!!
vijayakumar@gmailcom : Invalid

Output 5
Enter Email Id : vijayakumargmail.com
Dot . or At @ is not Present... Invalid Email ID !!!
vijayakumar@gmailcom : Invalid
16. Assessment Schedule

Tentative schedule for the Assessment During 2022-2023 Odd semester

S. Name of the
Start Date End Date Portion
No. Assessment

1 Unit Test 1 24.11.2022 29.11.2022 Unit 1

2 IAT 1 07.12.2022 14.12.2022 Unit 1 & 2

3 Unit Test 2 Unit 3

4 IAT 2 23.01.2023 30.01.2023 Unit 3 & 4

5 Revision 1 11.02.2023 Unit 5, 1 & 2

6 Revision 2 13.02.2023 Unit 3 & 4

7 Model 15.02.2023 24.02.2023 All 5 Units


17. Text Books & References

Text Books:

1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH,


2015. (Unit 1 & 2)
2. E Balagurusamy,”Object Oriented Programming with C++”, 4th
Edition, Tata McGraw-Hill Education, 2008. (Unit 3, 4 & 5)

Reference Books:

1. Nell Dale, Chip Weems, “Programming and Problem Solving with


C++”, 5th Edition, Jones and Barklett Publishers, 2010.
2. John Hubbard, “Schaum's Outline of Programming with C++”, MH,
2016.
3. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
4. ISRD Group, “Introduction to Object-oriented Programming and
C++”, Tata McGraw-Hill Publishing Company Ltd., 2007.
5. D. S. Malik, “C++ Programming: From Problem Analysis to Program
Design”, Third Edition, Thomson Course Technology, 2007.
6. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_01
297200240671948837_shared/overview
18. Mini Project Suggestions

1. Employee Management System with Object Oriented


Features and Exception Handling. (CO1-CO5, K6)
2. Student Management System with Object Oriented
Features and Exception Handling. (CO1-CO5, K6)
3. Calculator with Object Oriented Features and Exception
Handling. (CO1-CO5, K6)
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.

You might also like