Unit 5
Unit 5
Unit 5
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++
1 Contents
2 Course Objectives
3 Prerequisites
4 Syllabus
5 Course Outcomes
6 CO-PO Mapping
7 Lecture Plan
9 Lecture Notes
10 Assignments
12 Part-B Questions
16 Assessment Schedule
5.7 Templates
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.
Pointers -Variables – Operators – Expressions – Pointers and Arrays – Functions - Scope Rules –
Function Arguments – return Statement – Recursion – Structures – Unions – Enumerations.
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
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
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
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
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
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++.
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;
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++.
The iomanip.h also contains the following format flags using in formatted IO in C++.
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:
To Close Files
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
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
file_pointer.seekp(number of bytes
2 seekp() fout.seekp(10,ios::beg);
,Reference point);
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
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.
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.
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
int main ()
{
int firstnum = 0;
int secondnum = 0;
double result = 0.0;
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)
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
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)
11. List the functions of ios class used to perform formatted IO in C++. (CO5, K2)
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.
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.
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();
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
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.
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
{
.
.
}
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.
}
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
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
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
❖ 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
try
{
// Check the first character is an alphabet or not
if (!isChar(email[0]))
{
// 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;
}
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);
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
S. Name of the
Start Date End Date Portion
No. Assessment
Text Books:
Reference Books:
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.