0% found this document useful (0 votes)
22 views30 pages

CPP ManualV1 0

Uploaded by

Nandu 2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views30 pages

CPP ManualV1 0

Uploaded by

Nandu 2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Free Software Movement Karnataka

www.fsmk.org

} Introduction to C++ Programming Lab (BPLCK105D/205D)

I/II Semester
(common to all branches)
LAB MANUAL
}
Prabodh C P
Asst Professor
Dept of CSE, SIT
Volunteer, FSMK
Visit : https://tinyurl.com/yc5h2mu9

The versioned repository of all the programs can be found here as a GitLab Repository
https://gitlab.com/lab_manuals/22plc15d_intro_to_cpp_programming_lab_manual

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
To veiw a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/4.0/
Contents

Code::Blocks Usage iii

1 Sorting 1

2 Summation 3

3 Shift Operation 5

4 Function Overloading 7

5 Inheritance 9

6 Multilevel Inheritance 11

7 File Operations 13

8 Binary File Operations 15

9 Exception Handling 17

10 Array Bound Exception 19

i
Listings

1.1 01SortElem.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.1 02Summation.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1 03SwapValue.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.1 04FuncOverload.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5.1 05ShapeHeirarchy.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
5.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
6.1 06MultiLevelInheritance.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
6.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7.1 07FileOPerations.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.1 08BinaryFileOperations.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
8.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
9.1 09ExceptionDemo.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
9.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
10.1 10ArrayBoundExceptionDemo.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
10.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

ii
Preface

Usage of Free and Open Source Software


This manual has been developed for the lab component of the newly introduced subject Introduction to C++
Programming Lab (BPLCK105D/205D) for the first year students of VTU. This manual has been prepared
entirely using Free Software. The following Free Software has been used in preparation of this manual.
Operating System Ubuntu 22.04.1 LTS (Jammy Jellyfish)

Linux Kernel 5.15.0-56-generic


Compiler g++ 11.3.0
IDE Code::Blocks 20.03

Version Control git 2.34.1


Typesetting Texmaker 5.0.3 with LaTeX
Image Editing GIMP 2.10.30
I am sharing this manual under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
License. To veiw a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/4.0/.
You are free to share modify this manual with attribution for academic purposes. A repository of all the programs can
be found as GitLab repository in the following link https://gitlab.com/lab_manuals/22plc15d_intro_
to_cpp_programming_lab_manual. Looking for your feedback. If you want to contribute let me know by send-
ing a PR on the git repo mentioned earlier.

Use and spread the word of Free Software. Free Software leads to a Free Society!

Prabodh C P

iii
CODE::BLOCKS

CODE::BLOCKS TUTORIAL
Using Code::Blocks to compile and execute a C++ Program
To launch Code::Blocks IDE, Click on
Applications → Programming → Code::Blocks IDE
You will get a window as shown below

iv
LISTINGS LISTINGS

Code::Blocks creates what is called a Workspace to keep track of the project you are working on. It is possible for
you to be working on multiple projects within your workspace. A project is a collection of one or more source (as
well as header) files. Source files are the files that contain the source code for your program. If you are developing a
C++ program, you are writing C++ source code (.cpp files).

First start a new Project by clicking on Create a new project


OR To create a project, click on the File pull-down menu, open New and then Project.You get this pop-up window

Choose Console application


Then in the next window select the programming language C++ (and not C)

In the next step give the Project Title and specify the folder where you want to save your project.
(Note : Dont use any special characters or whitespaces for project title and folder names)

Dept of CSE, SIT - Prabodh C P v


LISTINGS LISTINGS

Finally you will be prompted to choose the compiler. Just choose the default options here (Dont change the
options). You should be using GNU GCC Compiler. Click Finish to create the new project.

The system will then return to the [MyProgram] window and you are ready to write your program.In the Man-
agement area of the screen (Shift-F2 toggles the Management display), you will see the files that are part of the
project in the Projects tab. To see the source files, click on the triangle symbol to expand the Workspace and its
subdirectories.

Under Sources, there is a file called main.cpp, which is automatically created for you when you build a console
application. Click on main.cpp.

main.cpp contains a simple Hello World program which you can edit later to solve a programming problem. Now
let us see how to compile and execute this main.cpp program. Just to understand the process of debugging we

Dept of CSE, SIT - Prabodh C P vi


LISTINGS LISTINGS

knowingly introduce an error in the program by removing the semicolon after the printf statement. We will now
compile the program (To compile a file means to take the instructions that you have written and translate it into
machine code for the computer to understand).
Compile the project from the Build pull-down menu by clicking on Build option[Ctrl+F9].

The error messages are shown in the Build messages window at the bottom. Let us now try to understand these
error messages. === Build: Debug in MyProgram (compiler: GNU GCC Compiler) ===
main.c In function main:
main.c 7 error: expected ; before return
main.c 8 warning: control reaches end of non-void function [-Wreturn-type]
=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 1 second(s)) ===

The error messages show the errors in syntax (and not the logical errors). It also indicates the line number and
the type of error. Here in this example the error says that before the return statement in line no 7 a semicolon is
missing. The next message is a warning message which has resulted because of the previous error.
Now go to line number 6 and add a semicolon at the end. Now build your project again.

Dept of CSE, SIT - Prabodh C P vii


LISTINGS LISTINGS

Now the build message window shows the following message. 0 error(s), 0 warning(s) (0 minute(s), 0 second(s)
This means that the errors and warnings have been successfully resolved. Now it is time to run the program. You
can Execute the project from the Build pull-down menu by clicking on Run option[Ctrl+F10].

An output window pops displaying the output of the program. A greeting message ”Hello world!” is printed on
to the output console.

Dept of CSE, SIT - Prabodh C P viii


LISTINGS LISTINGS

Installing Code::Blocks IDE


If you want to install Code::Blocks IDE on your system, you can download it from its official webpage.
http://www.codeblocks.org/
It is available for Linux, Mac, Windows platforms.
On Debian/Ubuntu systems Code::Blocks can be installed by using the apt package manner. You have to be
connected to the internet for necessary files to be downloaded. Run the following command.
$sudo apt install codeblocks
For Windows download the binary whose name is like codeblocks-17.12mingw-setup.exe

Dept of CSE, SIT - Prabodh C P ix


Chapter 1

Sorting

Question
Write a C++ program to sort the elements in ascending and descending order.

C++ Code
1 /***************************************************************************
2 *File : 01SortElem.cpp
3 *Description : Program to sort the elements in ascending and descending order.
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 26 December 2022
7 ***************************************************************************/
8

9 #include <iostream>
10 #include <iomanip>
11 #include <vector>
12 using namespace std;
13

14 /***************************************************************************
15 *Function : main
16 *Input parameters : no parameters
17 *RETURNS : 0 on success
18 ***************************************************************************/
19 int main() {
20 vector<int> values;
21 int iNum, iElem;
22

23 cout << "Enter the number of elements : " ;


24 cin >> iNum;
25

26 cout << "Enter " << iNum << " values :";
27 for(int i=0;i<iNum;i++){
28 cin >> iElem;
29 values.push_back(iElem);
30 }
31

32 for(int i=0;i<iNum;i++){
33 cout << values[i] << " ";
34 }
35 cout << endl;
36

37

38 // sort(values.begin(), values.end());
39 //sorting in ascending order
40 cout << "Sorting in descending order" << endl;

1
CHAPTER 1. SORTING

41 for(int i=0;i<iNum;i++){
42 for(int j=0;j<iNum;j++){
43 if(values[i] < values[j]){
44 int temp = values[i];
45 values[i] = values[j];
46 values[j] = temp;
47 }
48 }
49 }
50

51 for(int i=0;i<iNum;i++){
52 cout << values[i] << " ";
53 }
54 cout << endl;
55

56 // sort(values.begin(), values.end(), greater<int>());


57 //sorting in descending order
58 cout << "Sorting in descending order" << endl;
59 for(int i=0;i<iNum;i++){
60 for(int j=0;j<iNum;j++){
61 if(values[i] > values[j]){
62 int temp = values[i];
63 values[i] = values[j];
64 values[j] = temp;
65 }
66 }
67 }
68

69 for(int i=0;i<iNum;i++){
70 cout << values[i] << " ";
71 }
72 cout << endl;
73 return 0;
74 }
Listing 1.1: 01SortElem.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 01SortElem.cpp
2 putta:˜/.../Programs$ ./a.out
3 Enter the number of elements : 5
4 Enter 5 values :5 1 2 4 3
5 5 1 2 4 3
6 Sorting in descending order
7 1 2 3 4 5
8 Sorting in descending order
9 5 4 3 2 1
10

11 putta:˜/.../Programs$ ./a.out
12 Enter the number of elements : 6
13 Enter 6 values :6 1 2 5 4 3
14 6 1 2 5 4 3
15 Sorting in descending order
16 1 2 3 4 5 6
17 Sorting in descending order
18 6 5 4 3 2 1
Listing 1.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 2


Chapter 2

Summation

Question
Write a C++ program to find the sum of all the natural numbers from 1 to n.

C++ Code
1 /***************************************************************************
2 *File : 02Summation.cpp
3 *Description : Program to find the sum of all the natural numbers from 1 to n.
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 26 December 2022
7 ***************************************************************************/
8

9 #include <iostream>
10 #include <iomanip>
11 using namespace std;
12

13 /***************************************************************************
14 *Function : main
15 *Input parameters : no parameters
16 *RETURNS : 0 on success
17 ***************************************************************************/
18

19 int main() {
20 int iNum, iSum = 0;
21

22 cout << "Enter the value of n : " ;


23 cin >> iNum;
24

25 for(int i=1;i<=iNum;i++){
26 iSum += i;
27 }
28 cout << "Sum of 1 to " << iNum << " is : " << iSum << endl;
29 cout << "Sum of 1 to " << iNum << " using formula is : " << iNum*(iNum+1)/2 <<
endl;
30 return 0;
31 }
Listing 2.1: 02Summation.cpp

3
CHAPTER 2. SUMMATION

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 02Summation.cpp
2 putta:˜/.../Programs$ ./a.out
3 Enter the value of n : 5
4 Sum of 1 to 5 is : 15
5 Sum of 1 to 5 using formula is : 15
6

7 putta:˜/.../Programs$ ./a.out
8 Enter the value of n : 7
9 Sum of 1 to 7 is : 28
10 Sum of 1 to 7 using formula is : 28
Listing 2.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 4


Chapter 3

Shift Operation

Question
Write a C++ program to swap 2 values by writing a function that uses call by reference technique.

C++ Code
1 /***************************************************************************
2 *File : 03SwapValue.cpp
3 *Description : Program swap 2 values by writing a function that uses call by
reference technique.
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 January 2023
7 ***************************************************************************/
8 #include <iostream>
9 #include <iomanip>
10 using namespace std;
11

12 void fnSwap(int&, int&);


13 /***************************************************************************
14 *Function : main
15 *Input parameters : no parameters
16 *RETURNS : 0 on success
17 ***************************************************************************/
18 int main() {
19 int iNum1, iNum2;
20 cout << "Enter the value of m and n : " ;
21 cin >> iNum1 >> iNum2;
22 cout << "Values before Swapping m = " << iNum1 << " and n = " << iNum2 << endl;
23 fnSwap(iNum1, iNum2);
24 cout << "Values after Swapping m = " << iNum1 << " and n = " << iNum2 << endl;
25 return 0;
26 }
27 /***************************************************************************
28 *Function : fnSwap
29 *Input parameters : two parameters passed by reference
30 *RETURNS : nothing
31 ***************************************************************************/
32 void fnSwap(int &p, int &q)
33 {
34 p = p ˆ q;
35 q = p ˆ q;
36 p = p ˆ q;
37 }
Listing 3.1: 03SwapValue.cpp

5
CHAPTER 3. SHIFT OPERATION

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 03SwapValue.cpp
2 putta:˜/.../Programs$ ./a.out
3 Enter the value of m and n : 34 76
4 Values before Swapping m = 34 and n = 76
5 Values after Swapping m = 76 and n = 34
6

7 putta:˜/.../Programs$ ./a.out
8 Enter the value of m and n : -12 89
9 Values before Swapping m = -12 and n = 89
10 Values after Swapping m = 89 and n = -12
Listing 3.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 6


Chapter 4

Function Overloading

Question
Write a C++ program to demonstrate function overloading for the following prototypes.

add(int a, int b)
add(double a, double b)

C++ Code
1 /***************************************************************************
2 *File : 04FuncOverload.cpp
3 *Description : Program to demonstrate function overloading
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 26 December 2022
7 ***************************************************************************/
8

9 #include <iostream>
10 #include <iomanip>
11 using namespace std;
12

13 //Function Prototypes
14 void add(int, int);
15 void add(double, double);
16

17 /***************************************************************************
18 *Function : main
19 *Input parameters : no parameters
20 *RETURNS : 0 on success
21 ***************************************************************************/
22

23 int main() {
24 int iNum1, iNum2;
25 double dVal1, dVal2;
26

27

28 cout << "Enter integer values for i1 and i2 : " ;


29 cin >> iNum1 >> iNum2;
30

31 cout << "Enter double values for d1 and d2 : " ;


32 cin >> dVal1 >> dVal2;
33

34 add(iNum1, iNum2);
35 add(dVal1, dVal2);
36

37 return 0;
38 }

7
CHAPTER 4. FUNCTION OVERLOADING

39

40 void add(int p, int q)


41 {
42 cout << "Performing Integer Addition" << endl;
43 cout << "Sum of " << p << " and " << q << " is " << p+q << endl;
44 }
45

46 void add(double p, double q)


47 {
48 cout << "Performing Double Addition" << endl;
49 cout << "Sum of " << p << " and " << q << " is " << p+q << endl;
50 }
Listing 4.1: 04FuncOverload.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 04FuncOverload.cpp
2

3 putta:˜/.../Programs$ ./a.out
4

5 Enter integer values for i1 and i2 : 65 76


6 Enter double values for d1 and d2 : 5.6 7.8
7 Performing Integer Addition
8 Sum of 65 and 76 is 141
9 Performing Double Addition
10 Sum of 5.6 and 7.8 is 13.4
Listing 4.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 8


Chapter 5

Inheritance

Question
Create a class named Shape with a function that prints ”This is a shape”. Create another
class named Polygon inheriting the Shape class with the same function that prints ”Polygon
is a shape”. Create two other classes named Rectangle and Triangle having the same function
which prints ”Rectangle is a polygon” and ”Triangle is a polygon” respectively. Again, make an-
other class named Square having the same function which prints ”Square is a rectangle”.Now,
try calling the function by the object of each of these classes.

C++ Code
1 /***************************************************************************
2 *File : 05ShapeHeirarchy.cpp
3 *Description : Program to illustrate inheritance.
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 26 December 2022
7 ***************************************************************************/
8

9 #include <iostream>
10 #include <iomanip>
11 using namespace std;
12

13 class Shape{
14 public:
15 void show();
16 };
17 void Shape::show(){
18 cout << "This is a Shape" << endl;
19 }
20

21 class Polygon : public Shape{


22 public:
23 void show();
24 };
25 void Polygon::show(){
26 cout << "Polygon is a Shape" << endl;
27 }
28

29 class Triangle : public Polygon{


30 public:
31 void show();
32 };
33 void Triangle::show(){
34 cout << "Triangle is a Polygon" << endl;
35 }

9
CHAPTER 5. INHERITANCE

36

37 class Rectangle : public Polygon{


38 public:
39 void show();
40 };
41 void Rectangle::show(){
42 cout << "Rectangle is a Polygon" << endl;
43 }
44

45 class Square : public Rectangle{


46 public:
47 void show();
48 };
49 void Square::show(){
50 cout << "Square is a Rectangle" << endl;
51 }
52

53 /***************************************************************************
54 *Function : main
55 *Input parameters : no parameters
56 *RETURNS : 0 on success
57 ***************************************************************************/
58

59 int main() {
60 Shape s1;
61 Polygon p1;
62 Rectangle r1;
63 Triangle t1;
64 Square sq1;
65

66 s1.show();
67 p1.show();
68 r1.show();
69 t1.show();
70 sq1.show();
71 return 0;
72 }
Listing 5.1: 05ShapeHeirarchy.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 05ShapeHeirarchy.cpp
2 putta:˜/.../Programs$ ./a.out
3 This is a Shape
4 Polygon is a Shape
5 Rectangle is a Polygon
6 Triangle is a Polygon
7 Square is a Rectangle
Listing 5.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 10


Chapter 6

Multilevel Inheritance

Question
Suppose we have three classes Vehicle, FourWheeler, and Car. The class Vehicle is the base class,
the class FourWheeler is derived from it and the class Car is derived from the class FourWheeler.
Class Vehicle has a method ’vehicle’ that prints ’I am a vehicle’, class FourWheeler has a method
’fourWheeler’ that prints ’I have four wheels’, and class Car has a method ’car’ that prints ’I
am a car’. So, as this is a multi-level inheritance; we can have access to all the other classes
methods from the object of the class Car. We invoke all the methods from a Car object and print
the corresponding outputs of the methods. So, if we invoke the methods in this order, car(), four-
Wheeler(), and vehicle(), then the output will be
I am a car
I have four wheels
I am a vehicle
Write a C++ program to demonstrate multilevel inheritance using this.

C++ Code
1 /***************************************************************************
2 *File : 06MultiLevelInheritance.cpp
3 *Description : Program to illustrate multi level inheritance.
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 12 January 2023
7 ***************************************************************************/
8 #include <iostream>
9 #include <iomanip>
10 using namespace std;
11

12 class Vehicle{
13 public:
14 void vehicle();
15 };
16 void Vehicle::vehicle(){
17 cout << "I am a vehicle" << endl;
18 }
19

20 class FourWheeler : public Vehicle{


21 public:
22 void fourWheeler();
23 };
24 void FourWheeler::fourWheeler(){
25 cout << "I have four wheels" << endl;
26 }
27

28 class Car : public FourWheeler{


29 public:

11
CHAPTER 6. MULTILEVEL INHERITANCE

30 void car();
31 };
32 void Car::car(){
33 cout << "I am a car" << endl;
34 }
35

36 /***************************************************************************
37 *Function : main
38 *Input parameters : no parameters
39 *RETURNS : 0 on success
40 ***************************************************************************/
41 int main() {
42 Car myCar;
43

44 myCar.car();
45 myCar.fourWheeler();
46 myCar.vehicle();
47 return 0;
48 }
Listing 6.1: 06MultiLevelInheritance.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 06MultiLevelInheritance.cpp
2 putta:˜/.../Programs$ ./a.out
3 I am a car
4 I have four wheels
5 I am a vehicle
Listing 6.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 12


Chapter 7

File Operations

Question
Write a C++ program to create a text file, check file created or not, if created it will write some
text into the file and then read the text from the file.

C++ Code
1 /***************************************************************************
2 *File : 07FileOPerations.cpp
3 *Description : Program to perform file operations
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 12 January 2023
7 ***************************************************************************/
8 #include <iostream>
9 #include <fstream>
10 using namespace std;
11 /***************************************************************************
12 *Function : main
13 *Input parameters : no parameters
14 *RETURNS : 0 on success
15 ***************************************************************************/
16 int main() {
17

18 string flName;
19 char mesg[40], ch;
20

21 cout << "Enter the file name you want to create : ";
22 cin >> flName;
23 cin.get(); //read the trailing enter character
24

25 ofstream fout(flName.c_str());
26 // fout.close();
27 if(fout.fail()){
28 cout << "\nFailed to create file." << endl;
29 }
30 else{
31 cout << "\nFile " << flName <<" created successfully" << endl;
32 }
33

34 cout << "Enter a message : ";


35 cin.getline(mesg,40);
36 fout << mesg << endl;
37 cout << "\nMessage written to file successfully\n" << endl;
38 fout.close();
39

13
CHAPTER 7. FILE OPERATIONS

40 ifstream fin(flName.c_str());
41 cout << "Here are the contents of " << flName << ":\n";
42

43 while (fin.get(ch)) // read character from file and


44 cout << ch; // write it to screen
45 cout << "\nDone reading file contents\n" << endl;
46 fin.close();
47 return 0;
48 }
Listing 7.1: 07FileOPerations.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 07FileOPerations.cpp
2 putta:˜/.../Programs$ ./a.out
3 Enter the file name you want to create : random.txt
4

5 File random.txt created successfully


6 Enter a message : The universe is vast and endless
7

8 Message written to file successfully


9

10 Here are the contents of random.txt:


11 The universe is vast and endless
12

13 Done reading file contents


14

15 putta:˜/.../Programs$ cat random.txt


16 The universe is vast and endless
Listing 7.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 14


Chapter 8

Binary File Operations

Question
Write a C++ program to write and read time in/from binary file using fstream

C++ Code
1 /***************************************************************************
2 *File : 08BinaryFileOperations.cpp
3 *Description : Program to illustrate binary file operations
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 12 January 2023
7 ***************************************************************************/
8 #include <iostream>
9 #include <iomanip>
10 #include <fstream>
11 #include <cstring>
12 using namespace std;
13 class timeVal{
14 int hh, mm, ss;
15 char ampm[3];
16 public:
17 void setdata(int h, int m, int s, const char* half)
18 {
19 hh = h;
20 mm = m;
21 ss = s;
22 strcpy(ampm, half);
23 }
24 void showdata()
25 {
26 cout << "\nThe Time is : ";
27 cout << setfill(’0’) << setw(2) << hh << ":";
28 cout << setfill(’0’) << setw(2) << mm << ":";
29 cout << setfill(’0’) << setw(2) << ss << " ";
30 cout << ampm << endl << endl;
31

32 }
33 };
34 /***************************************************************************
35 *Function : main
36 *Input parameters : no parameters
37 *RETURNS : 0 on success
38 ***************************************************************************/
39 int main()
40 {

15
CHAPTER 8. BINARY FILE OPERATIONS

41 timeVal writeObj, readObj;


42 int hh, mm, ss;
43 char ampm[3];
44 cout << "Enter Hours : "; cin >> hh;
45 cout << "Enter Minutes : "; cin >> mm;
46 cout << "Enter Seconds : "; cin >> ss;
47 cout << "Enter am or pm : "; cin >> ampm;
48 writeObj.setdata(hh,mm,ss,ampm);
49 ofstream outFile("TimeFile", ios::out | ios::binary);
50 if(!outFile) {
51 cout << "Cannot open file.\n";
52 return 1;
53 }
54 outFile.write((char *) &writeObj, sizeof(timeVal));
55 cout << "\nWritten the time object successfully to binary file" << endl;
56 outFile.close();
57

58 // now, read back;


59 ifstream inFile("TimeFile", ios::in | ios::binary);
60 if(!inFile) {
61 cout << "Cannot open file.\n";
62 return 1;
63 }
64 inFile.read((char *) &readObj, sizeof(timeVal));
65 cout << "\nRead the time object successfully from binary file" << endl;
66

67 readObj.showdata();
68 inFile.close();
69 return 0;
70 }
Listing 8.1: 08BinaryFileOperations.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 08BinaryFileOPerations.cpp
2 putta:˜/.../Programs$ ./a.out
3 Enter Hours : 6
4 Enter Minutes : 35
5 Enter Seconds : 6
6 Enter am or pm : am
7

8 Written the object successfully to binary file


9

10 Read the object successfully from binary file


11

12 The Time is : 06:35:06 am


13

14 putta:˜/.../Programs$ ./a.out
15 Enter Hours : 8
16 Enter Minutes : 5
17 Enter Seconds : 9
18 Enter am or pm : am
19

20 Written the object successfully to binary file


21

22 Read the object successfully from binary file


23

24 The Time is : 08:05:09 am


Listing 8.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 16


Chapter 9

Exception Handling

Question
Write a function which throws a division by zero exception and catch it in catch block. Write a
C++ program to demonstrate usage of try, catch and throw to handle exception.

C++ Code
1 /***************************************************************************
2 *File : 09ExceptionDemo.cpp
3 *Description : Program to illustrate Exception Handling
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 12 January 2023
7 ***************************************************************************/
8 #include <iostream>
9 #include <iomanip>
10 using namespace std;
11

12 void fnDivide(int, int);


13 /***************************************************************************
14 *Function : main
15 *Input parameters : no parameters
16 *RETURNS : 0 on success
17 ***************************************************************************/
18 int main(void){
19

20 int iNum1, iNum2;


21

22 cout << "Enter the value of m and n : " ;


23 cin >> iNum1 >> iNum2;
24

25 try{
26 fnDivide(iNum1, iNum2);
27 }
28 catch (logic_error& e){
29 cout << "Processing error " << endl << e.what() << " occured.\n";
30 }
31

32 return 0;
33 }
34 /***************************************************************************
35 *Function : fnDivide
36 *Input parameters : two integers
37 *RETURNS : nothing
38 ***************************************************************************/
39

17
CHAPTER 9. EXCEPTION HANDLING

40 void fnDivide(int v1, int v2){


41 double dRes;
42 if(v2 == 0)
43 throw logic_error("Division by Zero Exception");
44 dRes = (double)(v1)/v2;
45

46 cout << v1 << " divided by " << v2 << " is equal to " << dRes << endl << endl;
47 }
Listing 9.1: 09ExceptionDemo.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 09ExceptionDemo.cpp
2 putta:˜/.../Programs$ ./a.out
3 Enter the value of m and n : 9 4
4 9 divided by 4 is equal to 2.25
5

6 putta:˜/.../Programs$ ./a.out
7 Enter the value of m and n : 5 0
8 Processing error
9 Division by Zero Exception occured.
Listing 9.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 18


Chapter 10

Array Bound Exception

Question
Write a C++ program function which handles array of bounds exception using C++.

C++ Code
1 /***************************************************************************
2 *File : 10ArrayBoundExceptionDemo.cpp
3 *Description : Program to illustrate array out of bound Exception
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 12 January 2023
7 ***************************************************************************/
8 #include <iostream>
9 #include <iomanip>
10 #include <cstdlib>
11 #include <vector>
12 using namespace std;
13 /***************************************************************************
14 *Function : main
15 *Input parameters : no parameters
16 *RETURNS : 0 on success
17 ***************************************************************************/
18 int main(void){
19

20 vector<int> values;
21 int iDx, iElem;
22

23 srand(time(NULL));
24 for(int i=0;i<100;i++){
25 iElem = rand() %10000;
26 values.push_back(iElem);
27 }
28

29 try{
30 //generate a random index and test repeatedly 10 times
31 for(int i=0;i<10;i++){
32 iDx = rand() % 200 - 50;
33 if(iDx < 0 || iDx >=100){
34 cout << "Generated index " << iDx << " is invalid" << endl;
35 throw logic_error("Array out of Bounds");
36 }
37 cout << "Generated index is " << iDx << " the value at that index is : "
<< values[i] << endl;
38 }
39

19
CHAPTER 10. ARRAY BOUND EXCEPTION

40 }
41 catch (logic_error& e){
42 cout << "Processing error " << endl << e.what() << " exception occured.\n"
<< endl;
43 }
44

45 return 0;
46 }
Listing 10.1: 10ArrayBoundExceptionDemo.cpp

Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 10ArrayBoundExceptionDemo.cpp
2

3 putta:˜/.../Programs$ ./a.out
4 Generated index is 37 the value at that index is : 8497
5 Generated index is 65 the value at that index is : 1027
6 Generated index is 7 the value at that index is : 8655
7 Generated index is 3 the value at that index is : 994
8 Generated index 105 is invalid
9 Processing error
10 Array out of Bounds exception occured.
11

12 putta:˜/.../Programs$ ./a.out
13 Generated index -31 is invalid
14 Processing error
15 Array out of Bounds exception occured.
16

17

18 putta:˜/.../Programs$ ./a.out
19 Generated index is 43 the value at that index is : 8629
20 Generated index is 95 the value at that index is : 4852
21 Generated index is 45 the value at that index is : 9097
22 Generated index -9 is invalid
23 Processing error
24 Array out of Bounds exception occured.
Listing 10.2: OUTPUT

Dept of CSE, SIT - Prabodh C P 20

You might also like