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

S.D.M.

Institute of Technology,
Ujire- 574 240
(Affiliated to VTU, Belagavi, Accredited by AICTE, New Delhi)

Department of Artificial Intelligence & Data


Science Engineering

A Laboratory Manual of
Introduction to C++ Programming (BPLCK205D)
Semester 2

Prepared by:
Dr. Antheesh. R
Assistant Professor
Department of ADE
SDMIT, Ujire
Introduction to C++ Programming (BPLCK205D)

INTRODUCTION TO C++ PROGRAMMING LABORATORY


(Effective from the academic year 2023-2024)

SEMESTER – II

Course Code BPLCK205D CIE Marks 50


Number of Contact Hours/Week 0:0:2 SEE Marks 50
Theory Exam Hours 03

Course objectives:

 Understanding about object-oriented programming and Gain knowledge about the capability
to store information together in an object.
 Understand the capability of a class to rely upon another class and functions.
 Understand about constructors which are special type of functions.
 Create and process data in files using file I/O functions
 Use the generic programming features of C++ including Exception handling

Laboratory Component:

1. Write a C++ program to sort the elements in ascending and descending order.
2. Write a C++ program to find the sum of all the natural numbers from 1 to n.
3. Write a C++ program to swap 2 values by writing a function that uses call by reference
technique.
4. Write a C++ program to demonstrate function overloading for the following prototypes.
add(int a, int b)
add(double a, double b)
5. 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
another 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.
6. 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(), fourWheeler(), and vehicle(), then the output will be

Dept. of Artificial Intelligence & Data Science Engineering Page 2


Introduction to C++ Programming (BPLCK205D)

I am a car
I have four wheels
I am a vehicle
Write a C++ program to demonstrate multilevel inheritance using this.

7. 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.
8. Write a C++ program to write and read time in/from binary file using fstream.
9. 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.
10. Write a C++ program function which handles array of bounds exception using C++.

1. Write a C++ program to sort the elements in ascending and descending order.
#include <iostream>
#include <algorithm>
using namespace std;
void sortAscending(int arr[], int n) {
sort(arr, arr + n);
}
void sortDescending(int arr[], int n) {
sort(arr, arr + n, greater<int>());
}
int main() {
int arr[] = {5, 2, 9, 1, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
sortAscending(arr, n);
cout << "Sorted array in ascending order: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
sortDescending(arr, n);
cout << "Sorted array in descending order: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 3


Introduction to C++ Programming (BPLCK205D)

2. C++ program to find the sum of all natural numbers from 1 to n


#include <iostream>
using namespace std;
int sumOfNaturalNumbers(int n) {
return n * (n + 1) / 2;
}
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
cout << "Sum of natural numbers from 1 to " << n << " is: " << sumOfNaturalNumbers(n)
<< endl;
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 4


Introduction to C++ Programming (BPLCK205D)

3. C++ program to swap 2 values using call by reference


#include <iostream>
using namespace std;
void swapValues(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
cout << "Before swapping: x = " << x << ", y = " << y << endl;
swapValues(x, y);
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 5


Introduction to C++ Programming (BPLCK205D)

4. C++ program to demonstrate function overloading


#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
cout << "Sum of integers: " << add(5, 3) << endl;
cout << "Sum of doubles: " << add(3.5, 2.5) << endl;
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 6


Introduction to C++ Programming (BPLCK205D)

5. C++ program to demonstrate inheritance


#include <iostream>
using namespace std;
class Shape {
public:
void print() {
cout << "This is a shape" << endl;
}
};
class Polygon : public Shape {
public:
void print() {
cout << "Polygon is a shape" << endl;
}
};
class Rectangle : public Polygon {
public:
void print() {
cout << "Rectangle is a polygon" << endl;
}
};
class Triangle : public Polygon {
public:
void print() {
cout << "Triangle is a polygon" << endl;
}
};
class Square : public Rectangle {
public:
void print() {
cout << "Square is a rectangle" << endl;
}
};
int main ( )
{
Shape s;
Polygon p;
Rectangle r;
Triangle t;
Square sq;
s.print();
p.print();
r.print();
t.print();
sq.print();
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 7


Introduction to C++ Programming (BPLCK205D)

6. C++ program to demonstrate multilevel inheritance


#include <iostream>
using namespace std;
// Base class
class Vehicle {
public:
void vehicle() {
cout << "I am a vehicle" << endl;
}
};

// Derived class
class FourWheeler : public Vehicle {
public:
void fourWheeler() {
cout << "I have four wheels" << endl;
}
};
// Derived class
class Car : public FourWheeler {
public:
void car() {
cout << "I am a car" << endl;
}
};
int main() {
Car myCar;
myCar.car();
myCar.fourWheeler();
myCar.vehicle();
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 8


Introduction to C++ Programming (BPLCK205D)

7. C++ program to create, write, and read a text file


#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("example.txt");
if (outputFile.is_open()) {
outputFile << "Hello, this is a text file!";
outputFile.close();
cout << "File created and text written successfully." << endl;
} else {
cout << "Error creating file." << endl;
}
ifstream inputFile("example.txt");
if (inputFile.is_open()) {
string line;
while (getline(inputFile, line)) {
cout << "Text from file: " << line << endl;
}
inputFile.close();
} else {
cout << "Error reading file." << endl;
}
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 9


Introduction to C++ Programming (BPLCK205D)

8. C++ program to write and read time in/from binary file using fstream
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
int main( )
{
time_t now = time(0);
tm* timeStruct = localtime(&now);
ofstream binaryFile("time.bin", ios::binary | ios::out);
if (binaryFile.is_open()) {
binaryFile.write(reinterpret_cast<char*>(timeStruct), sizeof(tm));
binaryFile.close();
cout << "Time written to binary file successfully." << endl;
}
else
{
cout << "Error writing to binary file." << endl;
}
ifstream readBinaryFile("time.bin", ios::binary | ios::in);
if (readBinaryFile.is_open()) {
tm readTime;
readBinaryFile.read(reinterpret_cast<char*>(&readTime), sizeof(tm));
cout << "Time read from binary file: " << asctime(&readTime);
readBinaryFile.close();
} else {
cout << "Error reading binary file." << endl;
}

return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 10


Introduction to C++ Programming (BPLCK205D)

9. C++ program to demonstrate exception handling


#include <iostream>
using namespace std;
void divisionByZero() {
int numerator = 10;
int denominator = 0;
try {
if (denominator == 0) {
throw "Division by zero!";
}
cout << "Result of division: " << numerator / denominator << endl;
} catch (const char* error) {
cerr << "Error: " << error << endl;
}
}
int main() {
divisionByZero();
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 11


Introduction to C++ Programming (BPLCK205D)

10. C++ program to handle array out-of-bounds exception


#include <iostream>
#include <stdexcept>
using namespace std;
void arrayOutOfBounds() {
int arr[5] = {1, 2, 3, 4, 5};
try {
for (int i = 0; i <= 5; ++i) {
if (i >= 5) {
throw out_of_range("Array index out of bounds!");
}
cout << arr[i] << endl;
}
} catch (const out_of_range& e) {
cerr << "Error: " << e.what() << endl;
}
}
int main() {
arrayOutOfBounds();
return 0;
}

OUTPUT:

Dept. of Artificial Intelligence & Data Science Engineering Page 12

You might also like