Guru Gobind Singh Indraprastha University: Institute of Innovation in Technology & Management

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 59

GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY

INSTITUTE OF INNOVATION IN TECHNOLOGY & MANAGEMENT

VII C++ LAB


PRACTICAL FILE
BCA-271

Submitted To: Submitted By:


Mrs. Sushma Sethi Name: Dhruv Sharma
Asst. Professor (IT) Class: BCA3 M1
Enrolment no 00290302023
INDEX
S.NO PROGRAM DATE FACULTY
SIGNATURE
1 WAP to implement ‘Inline function’

2 WAP to implement call by reference and return


by reference using class. [Hint. Assume necessary
functions]

3 WAP to implement friend function by taking


some real life example

4 WAP to implement ‘Function Overloading’

5 WAP to implement Parameterized Constructor,


Copy Constructor and Destructor

6 WAP to show the usage of constructor in base


and derived classes, in multiple inheritance

7 WAP to show the implementation of


‘containership’

8 WAP to show swapping using template function


(Generic)
9 WAP to implement ‘Exception Handling’

10 WAP to read and write values through object


using file handling

11 Create a class employee which have name, age


and address of employee, include functions
getdata() and showdata(), getdata() takes the
input from the user, showdata() display the data
in following format:
Name:
Age:
Address:

12 Write a class called CAccount which contains


two private data elements, an integer
accountNumber and a floating point
accountBalance, and three member functions:
 A constructor that allows the user to set initial
values for accountNumber and accountBalance
and a default constructor that prompts for the
input of the values for the above data numbers.
 A function called inputTransaction, which
reads a character value for transactionType(‘D’
for deposit and ‘W’ for withdrawal), and a
floating point value for transactionAmount,
which updates accountBalance.

A function called printBalance, which


prints on the screen the
accountNumber and
accountBalance.

13 Define a class Counter which contains an int


variable count defined as static and a static
function Display () to display the value of count.
Whenever an object of this class is created count
is incremented by 1. Use this class in main to
create multiple objects of this class and display
value of count each time

14 WAP to add and subtract two complex numbers


using classes

15 Write program to overload Binary + to add two


similar types of objects. (Both with and without
using friend functions)

16 WAP to implement += and = operator

17 Implement the following class hierarchy


considering appropriate data members and
member functions

18 Implement the following hierarchy considering


appropriate data members and member functions
(use Virtual functions).

19 WAP to convert meter to centimeter and vice


versa, using data conversions and operator
overloading

20 WAP to count digits, alphabets and spaces, stored


in a text file, using streams

Q1.WAP to implement friend function by taking some


real life example?
Code:
#include <iostream>
using namespace std;
class A;
class B{
int money = 10;
friend void C(A, B);
};

class D {
int money = 20;
friend void C(A, B);
};

void C(A r1, B r2) {


cout << r1.money + r2.money;
}

int main() {
A obj1;
B obj2;
C(obj1, obj2);
return 0;
}
Output:
Q2. WAP to implement ‘Function Overloading’?
Code:
#include <iostream>
using namespace std;

int sum(int, int);


int sum(int, int, float);
float sum(float, float);

int main() {
int a, b, c, d;
float x, y, z;

a = 10;
b = 20;
x = 5.5;
y = 6.7;

c = sum(a, b);
d = sum(a, b, x);
z = sum(x, y);

cout << "\nSum of 2 integers: " << c;


cout << "\nSum of 3 numbers: " << d;
cout << "\nSum of 2 float numbers: " << z;

return 0;
}

int sum(int a, int b) {


return a + b;
}

int sum(int a, int b, float c) {


return a + b + c;
}

float sum(float a, float b) {


return a + b;
}
Output:
Q3. WAP to implement ‘Inline function’?
Code:
#include <iostream>

inline int add(int a, int b) {


return a + b;
}

int main() {
int result = add(3, 4);
std::cout << "Result: " << result << std::endl;
return 0;
}

Q4. WAP to implement Parameterized Constructor,


Copy Constructor and Destructor?
Code:
#include <iostream>

class MyClass {
public:
MyClass(int x) {
data = x;
std::cout << "Parameterized constructor called\n";
}

MyClass(const MyClass& other) {


data = other.data;
std::cout << "Copy constructor called\n";
}

~MyClass() {
std::cout << "Destructor called\n";
}

private:
int data;
};

int main() {
MyClass obj1(10);
MyClass obj2(obj1); // Copy constructor is called
return 0;
}
Q5. WAP to implement call by reference and return by
reference using class. [Hint. Assume necessary
functions]
Code:
#include <iostream>

using namespace std;


class MyClass {
public:
int value;

// Call by reference
void increment(int& num) {
num++;
}

// Return by reference
int& getValue() {
return value;
}
};

int main() {
MyClass obj;
obj.value = 10;

int x = 5;
cout << "Before call by reference: " << x << endl;
obj.increment(x);
cout << "After call by reference: " << x << endl;

int& ref = obj.getValue();


ref = 20;
cout << "Value after return by reference: " <<
obj.value << endl;

return 0;
}

Q6 WAP to show the usage of constructor in base and


derived classes, in multiple inheritance?
CODE:
#include <iostream>

using namespace std;

class Base1 {
public:
Base1(int x) {
cout << "Base1 constructor called with x = " << x
<< endl;
}
};

class Base2 {
public:
Base2(int y) {
cout << "Base2 constructor called with y = " << y
<< endl;
}
};

class Derived : public Base1, public Base2 {


public:
Derived(int x, int y, int z) : Base1(x), Base2(y) {
cout << "Derived constructor called with z = " <<
z << endl;
}
};

int main() {
Derived obj(10, 20, 30);
return 0;
}
OUTPUT:

Q7 WAP to show the implementation of ‘containership’?


CODE:
#include <iostream>
#include <vector>

using namespace std;

class Book {
public:
string title;
string author;

Book(string t, string a) : title(t), author(a) {}

void display() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
}
};

class Library {
public:
vector<Book> books;

void addBook(Book book) {


books.push_back(book);
}

void displayBooks() {
for (Book book : books) {
book.display();
}
}
};

int main() {
Library library;

library.addBook(Book("The Lord of the Rings", "J.R.R.


Tolkien"));
library.addBook(Book("Pride and Prejudice", "Jane
Austen"));

library.displayBooks();

return 0;
}
Q8 WAP to show swapping using template
function (Generic)

CODE:

#include <iostream>
using namespace std;

// Template function to swap two variables


template <typename T>
void swapValues(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}

int main() {
int x = 5, y = 10;
float f1 = 1.5, f2 = 2.5;
char c1 = 'A', c2 = 'B';

cout << "Before swapping: " << endl;


cout << "x = " << x << ", y = " << y <<
endl;
cout << "f1 = " << f1 << ", f2 = " << f2 <<
endl;
cout << "c1 = " << c1 << ", c2 = " << c2 <<
endl;

// Swapping integers
swapValues(x, y);

// Swapping floats
swapValues(f1, f2);
// Swapping characters
swapValues(c1, c2);

cout << "\nAfter swapping: " << endl;


cout << "x = " << x << ", y = " << y <<
endl;
cout << "f1 = " << f1 << ", f2 = " << f2 <<
endl;
cout << "c1 = " << c1 << ", c2 = " << c2 <<
endl;

return 0;
}

OUTPUT
Q9 WAP to implement ‘Exception Handling’
CODE:
#include <iostream>

using namespace std;

void divide(int a, int b) {


if (b == 0) {
throw "Division by zero error";
}
cout << a / b << endl;
}

int main() {
int x, y;

cout << "Enter two numbers: ";


cin >> x >> y;

try {
divide(x, y);
} catch (const char* msg) {
cerr << "Error: " << msg << endl;
}

return 0;
}
OUTPUT:
Q10 WAP to read and write values through object using
file handling
CODE:
#include <iostream>
#include <fstream>
using namespace std;

class Student {
public:
int roll_no;
string name;
float marks;

void readData() {
cout << "Enter Roll No: ";
cin >> roll_no;
cout << "Enter Name: ";
cin.ignore(); // Ignore the newline character left by
previous input
getline(cin, name);
cout << "Enter Marks: ";
cin >> marks;
}

void writeData(ofstream& fout) {


fout << roll_no << endl;
fout << name << endl;
fout << marks << endl;
}
void readDataFromFile(ifstream& fin) {
fin >> roll_no;
getline(fin, name);
fin >> marks;
}

void displayData() {
cout << "Roll No: " << roll_no << endl;
cout << "Name: " << name << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
Student s;

// Write data to a file


ofstream fout("student_data.txt");
s.readData();
s.writeData(fout);
fout.close();

// Read data from the file


ifstream fin("student_data.txt");
s.readDataFromFile(fin);
fin.close();

// Display the read data


s.displayData();

return 0;
}
OUTPUT:
Q11Create a class employee which have name, age
and address of employee, include functions getdata()
and showdata(), getdata() takes the input from the
user, showdata() display the data in following format:
Name: Age: Address:
CODE:
#include <iostream>
#include <string>

using namespace std;

class Employee {
public:
string name;
int age;
string address;

void getdata() {
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Age: ";
cin >> age;
cin.ignore(); // Ignore the newline character left by
previous input
cout << "Enter Address: ";
getline(cin, address);
}

void showdata() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Address: " << address << endl;
}
};

int main() {
Employee emp;

emp.getdata();
emp.showdata();

return 0;
}
Q12 Write a class called CAccount which contains two
private data elements, an integer accountNumber and
a floating point accountBalance, and three member
functions: • A constructor that allows the user to set
initial values for accountNumber and accountBalance
and a default constructor that prompts for the input of
the values for the above data numbers. • A function
called inputTransaction, which reads a character value
for transactionType(‘D’ for deposit and ‘W’ for
withdrawal), and a floating point value for
transactionAmount, which updates accountBalance. A
function called printBalance, which prints on the screen
the accountNumber and accountBalance.
CODE:
#include <iostream>

using namespace std;

class CAccount {
public:
CAccount(int accountNumber = 0, float
accountBalance = 0.0) {
if (accountNumber == 0 && accountBalance ==
0.0) {
cout << "Enter account number: ";
cin >> accountNumber;
cout << "Enter initial balance: ";
cin >> accountBalance;
}
this->accountNumber = accountNumber;
this->accountBalance = accountBalance;
}

void inputTransaction() {
char transactionType;
float transactionAmount;

cout << "Enter transaction type (D for deposit, W


for withdrawal): ";
cin >> transactionType;

cout << "Enter transaction amount: ";


cin >> transactionAmount;

if (transactionType == 'D') {
accountBalance += transactionAmount;
} else if (transactionType == 'W') {
if (transactionAmount > accountBalance) {
cout << "Insufficient balance!\n";
} else {
accountBalance -= transactionAmount;
}
} else {
cout << "Invalid transaction type!\n";
}
}

void printBalance() {
cout << "Account Number: " << accountNumber
<< endl;
cout << "Account Balance: " << accountBalance
<< endl;
}

private:
int accountNumber;
float accountBalance;
};

int main() {
CAccount account;
account.inputTransaction();
account.printBalance();

return 0;
}
OUTPUT:
Q13 Define a class Counter which contains an int
variable count defined as static and a static function
Display () to display the value of count. Whenever an
object of this class is created count is incremented by
1. Use this class in main to create multiple objects of
this class and display value of count each time
CODE:
#include <iostream>

using namespace std;

class Counter {
public:
static int count;

Counter() {
count++;
}

static void Display() {


cout << "Count: " << count << endl;
}
};

int Counter::count = 0;
int main() {
Counter obj1, obj2, obj3;

Counter::Display();
Counter::Display();
Counter::Display();

return 0;
}
OUTPUT:
Q14 WAP to add and subtract two complex numbers
using classes
CODE:
#include <iostream>

using namespace std;

class Complex {
public:
int real, imag;

Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}

Complex operator+(Complex const &obj) {


Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}

Complex operator-(Complex const &obj) {


Complex res;
res.real = real - obj.real;
res.imag = imag - obj.imag;
return res;
}

void print() {
cout << real << " + i" << imag << endl;
}
};

int main() {
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;

cout << "Sum: ";


c3.print();

cout << "Difference: ";


c4.print();
return 0;
}
OUTPUT:
Q15 Write program to overload Binary + to add two
similar types of objects. (Both with and without using
friend functions)
CODE:
#include <iostream>

using namespace std;

class Complex {
public:
int real, imag;

Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}

// Overloading + operator
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() {
cout << real << " + i" << imag << endl;
}
};

int main() {
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // Operator overloading is
used here

c3.print();
}
OUTPUT:
Q16 WAP to implement += and = operator
CODE:
#include <iostream>

using namespace std;

class Complex {
public:
int real, imag;

Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}

// Overloading += operator
Complex& operator+=(const Complex& obj) {
real += obj.real;
imag += obj.imag;
return *this;
}

// Overloading = operator
Complex& operator=(const Complex& obj) {
real = obj.real;
imag = obj.imag;
return *this;
}

void print() {
cout << real << " + i" << imag << endl;
}
};

int main() {
Complex c1(10, 5), c2(2, 4);

// Using += operator
c1 += c2;
c1.print();

// Using = operator
c1 = c2;
c1.print();

return 0;
}
OUTPUT:
Q17 Implement the following class hierarchy
considering appropriate data members and member
functions

CODE:
#include <iostream>
#include <string>
using namespace std;

// Base class: Student


class Student {
protected:
string name;
int student_id;

public:
Student(string n, int id) : name(n), student_id(id) {}

void displayInfo() {
cout << "Student Name: " << name << endl;
cout << "Student ID: " << student_id << endl;
}
};
// Derived class: Test (inherits from Student)
class Test : virtual public Student {
protected:
int test_score;

public:
Test(string n, int id, int score) : Student(n, id),
test_score(score) {}

void displayTestScore() {
cout << "Test Score: " << test_score << endl;
}
};

// Derived class: Sports (inherits from Student)


class Sports : virtual public Student {
protected:
int sports_score;

public:
Sports(string n, int id, int score) : Student(n, id),
sports_score(score) {}

void displaySportsScore() {
cout << "Sports Score: " << sports_score <<
endl;
}
};

// Derived class: Performance (inherits from both Test


and Sports)
class Performance : public Test, public Sports {
public:
Performance(string n, int id, int testScore, int
sportsScore)
: Student(n, id), Test(n, id, testScore), Sports(n, id,
sportsScore) {}

void displayPerformance() {
displayInfo();
displayTestScore();
displaySportsScore();
int total_score = test_score + sports_score;
cout << "Total Performance Score: " <<
total_score << endl;
}
};

int main() {
Performance student1("Alice", 101, 85, 90);
student1.displayPerformance();

return 0;
}
OUTPUT:
Q18 Implement the following hierarchy considering
appropriate data members and member functions(USE
VIRTUAL FUNCTION)

CODE :
#include <iostream>
#include <cmath>
using namespace std;

// Base class
class Shape {
public:
// Virtual function for calculating area
virtual double area() const = 0; // Pure virtual
function
};

// Derived class for Triangle


class Triangle : public Shape {
private:
double base;
double height;
public:
Triangle(double b, double h) : base(b), height(h) {}

// Override area function


double area() const override {
return 0.5 * base * height;
}
};

// Derived class for Rectangle


class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h)
{}

// Override area function


double area() const override {
return width * height;
}
};

// Derived class for Circle


class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}

// Override area function


double area() const override {
return M_PI * radius * radius;
}
};

int main() {
// Create objects of each shape
Shape* shapes[3];
shapes[0] = new Triangle(5.0, 10.0);
shapes[1] = new Rectangle(4.0, 6.0);
shapes[2] = new Circle(3.0);

// Display the area of each shape


for (int i = 0; i < 3; ++i) {
cout << "Area of shape " << i + 1 << ": " <<
shapes[i]->area() << endl;
delete shapes[i]; // Clean up memory
}

return 0;
}

OUTPUT
Q19 WAP to convert meter to centimeter and vice
versa, using data conversions and operator overloading
CODE:
#include <iostream>
using namespace std;

class Centimeter; // Forward declaration

class Meter {
private:
double meters;
public:
// Constructor to initialize meters
Meter(double m = 0) : meters(m) {}

// Getter function for meters


double getMeters() const {
return meters;
}

// Overloading the assignment operator to convert


Centimeter to Meter
Meter& operator=(const Centimeter& cm);
// Display function
void display() const {
cout << meters << " meters" << endl;
}
};

class Centimeter {
private:
double centimeters;
public:
// Constructor to initialize centimeters
Centimeter(double cm = 0) : centimeters(cm) {}

// Getter function for centimeters


double getCentimeters() const {
return centimeters;
}

// Overloading the assignment operator to convert


Meter to Centimeter
Centimeter& operator=(const Meter& m) {
centimeters = m.getMeters() * 100.0; // 1 meter =
100 cm
return *this;
}
// Display function
void display() const {
cout << centimeters << " centimeters" << endl;
}
};

// Overloading the assignment operator to convert


Centimeter to Meter
Meter& Meter::operator=(const Centimeter& cm) {
meters = cm.getCentimeters() / 100.0; // 100 cm = 1
meter
return *this;
}

int main() {
Meter m1(5); // 5 meters
Centimeter cm1;

// Convert Meter to Centimeter


cm1 = m1;
cout << "Meter to Centimeter conversion: ";
cm1.display();

// Convert Centimeter to Meter


Centimeter cm2(300); // 300 centimeters
Meter m2;
m2 = cm2;
cout << "Centimeter to Meter conversion: ";
m2.display();

return 0;
}

OUTPUT
Q20 WAP to count digits, alphabets and spaces, stored
in a text file using streams
CODE:
#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Open the file for reading
ifstream file("input.txt");

// Check if the file opened successfully


if (!file) {
cerr << "Error opening file!" << endl;
return 1;
}

// Variables to store counts


int digitCount = 0;
int alphabetCount = 0;
int spaceCount = 0;
char ch;

// Read characters from the file one by one


while (file.get(ch)) {
if (isdigit(ch)) {
++digitCount;
} else if (isalpha(ch)) {
++alphabetCount;
} else if (isspace(ch)) {
++spaceCount;
}
}

// Close the file


file.close();

// Display the counts


cout << "Digits: " << digitCount << endl;
cout << "Alphabets: " << alphabetCount << endl;
cout << "Spaces: " << spaceCount << endl;

return 0;
}
OUTPUT
File content

output

You might also like