C++ Lab Manual

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

Introduction to C++ Programming (BPLCK205D)

PROGRAM 1
SORTING

Question
Write a C++ program to sort the elements in ascending and descending order
C++ Code
#include<iostream>
#include <iomanip>
#include<vector>
using namespace std;
int main()
{
vector <int> values;
int iNum, iElem;
cout << "Enter the number of elements : " ;
cin >> iNum;

cout << "Enter " << iNum << " values :";
for(int i=0;i<iNum;i++)
{
Cin>>iElem;
values.push_back(iElem);
}
for(int i=0;i<iNum;i++)
{
cout<< values[i] << " ";
}
cout << endl;
cout << "Sorting in ascending order" << endl;
for(int i=0;i<iNum;i++)
{
for(int j=0;j<iNum;j++)
{
if(values[i]< values[j])
{
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 1


Introduction to C++ Programming (BPLCK205D)

} for(int i=0;i<iNum;i++)
{
cout<< values[i] << " ";
}
cout << endl;
cout << "Sorting in descending order" << endl;
for(int i=0;i<iNum;i++)
{
for(int j=0;j<iNum;j++)
{
if(values[i]> values[j])
{
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
for(int i=0;i<iNum;i++)
{
cout << values[i] << " ";
}
cout << endl;
return 0;
}

OUTPUT

Enter the number of elements : 5


Enter 5 values :5 1 2 4 3
51243
Sorting in ascending order
12345
Sorting in descending order
5 4 3 2 1 10

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 2


Introduction to C++ Programming (BPLCK205D)

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

C++ Code
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
int iNum, iSum = 0;
cout << "Enter the value of n : " ;
cin >> iNum;
for(int i=1;i<=iNum;i++)
{
iSum += i;
}
cout << "Sum of 1 to " << iNum << " is : " << iSum << endl;
cout << "Sum of 1 to " << iNum << " using formula is : " << iNum*(iNum+1)/2 << endl;
return 0;
}

OUTPUT

Enter the value of n : 5


Sum of 1 to 5 is : 15
Sum of 1 to 5 using formula is : 15

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 3


Introduction to C++ Programming (BPLCK205D)

PROGRAM -3
SHIFT OPERATION
Question
Write a C++ program to swap 2 values by writing a function that uses call by reference
technique.

C++ Code

#include<iostream>
using namespace std;
void fnSwap(int&, int&);
int main()
{
int iNum1, iNum2;
cout << "Enter the value of m and n : " ;
cin >> iNum1 >> iNum2;
cout << "Values before Swapping m = " << iNum1 << " and n = " << iNum2 << endl;
fnSwap(iNum1, iNum2);
cout << "Values after Swapping m = " << iNum1 << " and n = " << iNum2 << endl;
return 0;
}
void fnSwap(int &p, int &q)
{
p = p ˆ q;
q = p ˆ q;
p = p ˆ q;
}

OUTPUT

Enter the value of m and n : 34 76


Values before Swapping m = 34 and n = 76
Values after Swapping m = 76 and n = 34

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 4


Introduction to C++ Programming (BPLCK205D)

PROGRAM 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

#include<iostream>
#include <iomanip>
using namespace std;

//Function Prototypes
void add(int, int);
void add(double, double);

int main()
{
int iNum1, iNum2;
double dVal1, dVal2;
cout << "Enter integer values for i1 and i2 : " ;
cin >> iNum1 >> iNum2;
cout << "Enter double values for d1 and d2 : " ;
cin >> dVal1 >> dVal2;
add(iNum1, iNum2);
add(dVal1, dVal2);
return 0;
}

void add(int p, int q)


{
cout << "Performing Integer Addition" << endl;
cout << "Sum of " << p << " and " << q << " is " << p+q << endl;
}
void add(double p, double q)
{
cout << "Performing Double Addition" << endl;
cout << "Sum of " << p << " and " << q << " is " << p+q << endl;
}

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 5


Introduction to C++ Programming (BPLCK205D)

OUTPUT
Enter integer values for i1 and i2 : 65 76
Enter double values for d1 and d2 : 5.6 7.8
Performing Integer Addition
Sum of 65 and 76 is 141
Performing Double Addition
Sum of 5.6 and 7.8 is 13.4

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 6


Introduction to C++ Programming (BPLCK205D)

PROGRAM 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 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.

C++ Code
#include<iostream>
#include <iomanip>
using namespace std;
class Shape
{
public:
void show();
};
void Shape::show()
{
cout << "This is a Shape" << endl;
}
class Polygon : public Shape
{
public:
void show();
};
void Polygon::show()
{
cout << "Polygon is a Shape" << endl;
}
class Triangle : public Polygon
{
public:
void show();
};
void Triangle::show()
{
cout << "Triangle is a Polygon" << endl;

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 7


Introduction to C++ Programming (BPLCK205D)

}
class Rectangle : public Polygon
{
public: void show();
};
void Rectangle::show()
{
cout << "Rectangle is a Polygon" << endl;
}
class Square : public Rectangle
{
public: void show();
};
void Square::show()
{
cout << "Square is a Rectangle" << endl;
}
int main()
{
Shape s1;
Polygon p1;
Rectangle r1;
Triangle t1;
Square sq1;
s1.show();
p1.show();
r1.show();
t1.show();
sq1.show();
return 0;
}

OUTPUT
This is a Shape
Polygon is a Shape
Rectangle is a Polygon
Triangle is a Polygon
Square is a Rectangle

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 8


Introduction to C++ Programming (BPLCK205D)

PROGRAM 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(),
fourWheeler(), 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
#include<iostream>
#include <iomanip>
using namespace std;
class Vehicle
{
public:
void vehicle();
};
void Vehicle::vehicle()
{
cout << "I am a vehicle" << endl;
}
class FourWheeler : public Vehicle
{ public:
void fourWheeler();
};
void FourWheeler::fourWheeler()
{
cout << "I have four wheels" << endl;
}
class Car : public FourWheeler
{
public:
void car();
};
void Car::car()

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 9


Introduction to C++ Programming (BPLCK205D)

{ cout << "I am a car" << endl;


}
int main()
{
Car myCar;
myCar.car();
myCar.fourWheeler();
myCar.vehicle();
return 0;
}

OUTPUT

I am a car
I have four wheels
I am a vehicle

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 10


Introduction to C++ Programming (BPLCK205D)

PROGRAM 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
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
string flName;
char mesg[40], ch;
cout << "Enter the file name you want to create : ";
cin >> flName;
cin.get(); //read the trailing enter character
ofstream fout(flName.c_str());
if(fout.fail())
{
cout << "\nFailed to create file." << endl;
}
else
{
cout << "\nFile " << flName <<" created successfully" << endl;
}
cout << "Enter a message : ";
cin.getline(mesg,40);
fout << mesg << endl;
cout << "\nMessage written to file successfully\n" << endl;
fout.close();
ifstream fin(flName.c_str());
cout << "Here are the contents of " << flName << ":\n";
while (fin.get(ch)) // read character from file and
cout << ch; // write it to screen
cout << "\nDone reading file contents\n" << endl;
fin.close();
return 0;
}

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 11


Introduction to C++ Programming (BPLCK205D)

OUTPUT

Enter the file name you want to create : random.txt


File random.txt created successfully
Enter a message : The universe is vast and endless
Message written to file successfully
Here are the contents of random.txt:
The universe is vast and endless
Done reading file contents 14 15

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 12


Introduction to C++ Programming (BPLCK205D)

PROGRAM 8
BINARY FILE OPERATIONS
Question
Write a C++ program to write and read time in/from binary file using fstream

C++ Code
#include<iostream>
#include <fstream>
#include<iomanip>
#include <cstring>
using namespace std;
class timeVal
{
int hh, mm, ss;
char ampm[3];
public:
void setdata(int h, int m, int s, const char* half)
{
hh = h;
mm = m;
ss = s;
strcpy(ampm, half);
}
void showdata()
{
cout << "\nThe Time is : ";
cout << setfill(’0’) << setw(2) << hh << ":";
cout << setfill(’0’) << setw(2) << mm << ":";
cout << setfill(’0’) << setw(2) << ss << " ";
cout << ampm << endl << endl;
}
};
int main()
{
timeVal writeObj, readObj;
int hh, mm, ss;
char ampm[3];
cout << "Enter Hours : ";
cin >> hh;
cout << "Enter Minutes : ";

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 13


Introduction to C++ Programming (BPLCK205D)

cin >> mm;


cout << "Enter Seconds : ";
cin >> ss;
cout << "Enter am or pm : ";
cin >> ampm;
writeObj.setdata(hh,mm,ss,ampm);
ofstream outFile("TimeFile", ios::out | ios::binary);
if(!outFile)
{
cout << "Cannot open file.\n";
return 1;
}
outFile.write((char *) &writeObj, sizeof(timeVal));
cout << "\nWritten the time object successfully to binary file" << endl;
outFile.close();
// now, read back;
ifstream inFile("TimeFile", ios::in | ios::binary);
if(!inFile)
{
cout << "Cannot open file.\n";
return 1;
}
inFile.read((char *) &readObj, sizeof(timeVal));
cout << "\nRead the time object successfully from binary file" << endl;
readObj.showdata();
inFile.close();
return 0;
}

OUTPUT
Enter Hours : 6
Enter Minutes : 35
Enter Seconds : 6
Enter am or pm : am
Written the object successfully to binary file
Read the object successfully from binary file
The Time is : 06:35:06 am

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 14


Introduction to C++ Programming (BPLCK205D)

PROGRAM 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
#include<iostream>
#include |<iomanip>
# using namespace std;
void fnDivide(int, int);
int main(void)
{
int iNum1, iNum2;
cout << "Enter the value of m and n : " ;
cin >> iNum1 >> iNum2;
try{
fnDivide(iNum1, iNum2);
}
catch (logic_error& e)
{
cout << "Processing error " << endl << e.what() << " occured.\n";

}
return 0;
}

OUTPUT
Enter the value of m and n : 9 4
9 divided by 4 is equal to 2.25

Enter the value of m and n : 5 0


Processing error
Division by Zero Exception occured.

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 15


Introduction to C++ Programming (BPLCK205D)

Chapter 10
ARRAY BOUND EXCEPTION
Question
Write a C++ program function which handles array of bounds exception using C++
C++ Code
#include<iostream>
#include <iomanip>
#include <cstdlib>
#include<vector>
using namespace std;
int main(void)
{
Vector<int> values;
int iDx, iElem;
srand(time(NULL));
for(int i=0;i< 100;i++)
{
iElem = rand() %10000;
values.push_back(iElem);
}
try{
//generate a random index and test repeatedly 10 times
for(int i=0;i< 0 || iDx >=100)
{
cout << "Generated index " << iDx << " is invalid" << endl;
throw logic_error("Array out of Bounds");
}
cout << "Generated index is " << iDx << " the value at that index is : " << values[i] << endl;
}
} catch (logic_error& e)
{ cout << "Processing error " << endl << e.what() << " exception occured.\n" << endl;
}
return 0;
}

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 16


Introduction to C++ Programming (BPLCK205D)

OUTPUT
Generated index is 37 the value at that index is : 8497
Generated index is 65 the value at that index is : 1027

Generated index is 7 the value at that index is : 8655


Generated index is 3 the value at that index is : 994
Generated index 105 is invalid
Processing error
Array out of Bounds exception occured.

Shylaja D N , Assistant professor, Department of CSE,BTI 2022-23Page 17

You might also like