CPP ManualV1 0
CPP ManualV1 0
www.fsmk.org
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
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
9 Exception Handling 17
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
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).
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)
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
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.
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.
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
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
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
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
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
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
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
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
34 add(iNum1, iNum2);
35 add(dVal1, dVal2);
36
37 return 0;
38 }
7
CHAPTER 4. FUNCTION OVERLOADING
39
Output
=================================
1 putta:˜/.../Programs$ g++ -Wall 04FuncOverload.cpp
2
3 putta:˜/.../Programs$ ./a.out
4
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
9
CHAPTER 5. INHERITANCE
36
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
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
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
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
13
CHAPTER 7. FILE OPERATIONS
40 ifstream fin(flName.c_str());
41 cout << "Here are the contents of " << flName << ":\n";
42
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
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
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
14 putta:˜/.../Programs$ ./a.out
15 Enter Hours : 8
16 Enter Minutes : 5
17 Enter Seconds : 9
18 Enter am or pm : am
19
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
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
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
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