0% found this document useful (0 votes)
10 views57 pages

I BCA - CPP Lab

The document outlines various C++ programming exercises demonstrating key concepts such as classes, objects, constructors, function overloading, operator overloading, inheritance, and dynamic memory allocation. Each exercise includes an aim, algorithm, program code, output, and a result indicating successful execution. The document serves as a comprehensive guide for understanding and applying fundamental C++ programming principles.

Uploaded by

22uca12
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)
10 views57 pages

I BCA - CPP Lab

The document outlines various C++ programming exercises demonstrating key concepts such as classes, objects, constructors, function overloading, operator overloading, inheritance, and dynamic memory allocation. Each exercise includes an aim, algorithm, program code, output, and a result indicating successful execution. The document serves as a comprehensive guide for understanding and applying fundamental C++ programming principles.

Uploaded by

22uca12
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/ 57

EX.

NO: 01 CLASS AND OBJECT

DATE:

Aim:

To demonstrate the class and object using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Create a class name

STEP 3: Initialize the member variables when an object is created.

STEP 4: In member function display the person's name and age.

STEP 5: In the 'main' function Create two objects

STEP 6: Call the member function to display their information.

STEP 7: End the program.

Flowchart:
Program:
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) {
name = n;
age = a;
}
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person person1("Alice", 25);
Person person2("Bob", 30);
person1.displayInfo();
cout << endl;
person2.displayInfo();
return 0;
}
OUTPUT:
Name: Alice
Age: 25
Name: Bob
Age: 30

Result:
Thus, the C++ program was executed successfully
EX.NO: 02 CONSTRUCTOR, COPY CONSTRUCTOR&DESTRUCTOR

DATE:

Aim:

To demonstrate Constructor, copy constructor and destructor using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Define a class with private member variables

STEP 3: To initialize the object, a copy constructor to create a new object

STEP 4: Create three 'Person' objects: person1, person2, and person3.

STEP 5: Display information for all three objects

STEP 6: End the program.

Flowchart:
Program:
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {
cout << "Constructor called for " << name << endl;
}
Person(const Person &other) : name(other.name), age(other.age) {
cout << "Copy Constructor called for " << name << endl;
}
~Person() {
cout << "Destructor called for " << name << endl;
}
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person person1("Alice", 25);
Person person2("Bob", 30);
Person person3 = person1;
cout << "Displaying person1:" << endl;
person1.displayInfo();
cout << endl;
cout << "Displaying person2:" << endl;
person2.displayInfo();
cout << endl;
cout << "Displaying person3:" << endl;
person3.displayInfo();
cout << endl;
return 0;
}
Output:
Constructor called for Alice
Constructor called for Bob
Copy Constructor called for Alice
Displaying person1:
Name: Alice
Age: 25
Displaying person2:
Name: Bob
Age: 30
Displaying person3:
Name: Alice
Age: 25
Destructor called for Alice
Destructor called for Bob
Destructor called for Alice

Result:
Thus, the C++ program was executed successfully
EX.NO: 03 FUNCTION OVERLOADING

DATE:

Aim:

To demonstrate Function Overloading using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Define a function with the same name but different parameter lists.

STEP 3: In the main function, call the overloaded functions with different
argument types and store the results in variables.

STEP 4: Display the results to demonstrate the function overloading.

STEP 5: End the program.

Flowchart:
Program:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
string add(string a, string b) {
return a + b;
}
int main() {
int sum1 = add(5, 10);
float sum2 = add(3.5, 2.7);
string result = add("Hello, ", "world!");
cout << "Sum of integers: " << sum1 << endl;
cout << "Sum of floats: " << sum2 << endl;
cout << "Concatenated string: " << result << endl;
return 0;
}
Output:
Sum of integers: 15
Sum of floats: 6.2
Concatenated string: Hello, world!

Result:
Thus, the C++ program was executed successfully
EX.NO: 04 FRIEND FUNCTION

DATE:

Aim:

To demonstrate Friend Function using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Declare the class and named the class.

STEP 3: Declare the friend function prototype outside the class.

STEP 4: Define the class with its private members and constructor.

STEP 5: Declare the friend function within the class using the friend keyword.

STEP 6: In the main function, create an object of the class and call the friend
function on that object.

STEP 7:Display the result obtained from the friend function.

STEP 8: End the program.

Flowchart:
Program:
#include <iostream>
using namespace std;
class MyClass;

int add(MyClass obj);


class MyClass {
private:
int x;
public:
MyClass(int val) : x(val) {}
friend int add(MyClass obj);
};
int add(MyClass obj) {
return obj.x + 10;
}
int main() {
MyClass myObject(5);
int result = add(myObject);
cout << "Result: " << result << endl;
return 0;
}
Output:
Result: 15

Result:
Thus, the C++ program was executed successfully
EX.NO: 05 PASSING OBJECT TO FUNCTION

DATE:

Aim:

To demonstrate concept of Passing object to function using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Define a class with its members and member functions.

STEP 3: Create functions that accept an object as an argument using different


methods:

STEP 4: In the main function, create an object of the class.

STEP 5: Call the member function of the object to display its initial information.

STEP 6: Pass the object to each of the functions using different methods

STEP 7: Display the object's information to observe the changes.

STEP 8: End the program.

Flowchart:
Program:
#include <iostream>
using namespace std;

class Person {
public:
string name;
int age;
Person(string n, int a) : name(n), age(a) {}
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
void passByValue(Person p) {
cout << "Inside passByValue function:" << endl;
p.displayInfo();
p.age = 35;
}
void passByReference(Person &p) {
cout << "Inside passByReference function:" << endl;
p.displayInfo();
p.age = 40;
}
void passByPointer(Person *p) {
cout << "Inside passByPointer function:" << endl;
p->displayInfo();
p->age = 45;
}

int main() {
Person person("Alice", 30);
cout << "Original object:" << endl;
person.displayInfo();
cout << endl;
passByValue(person);
cout << "After passByValue:" << endl;
person.displayInfo();
cout << endl;
passByReference(person);
cout << "After passByReference:" << endl;
person.displayInfo();
cout << endl;
passByPointer(&person);
cout << "After passByPointer:" << endl;
person.displayInfo();
return 0;
}
Output:
Original object:
Name: Alice
Age: 30
Inside passByValue function:
Name: Alice
Age: 30
After passByValue:
Name: Alice
Age: 30
Inside passByReference function:
Name: Alice
Age: 30
After passByReference:
Name: Alice
Age: 40
Inside passByPointer function:
Name: Alice
Age: 40
After passByPointer:
Name: Alice
Age: 45

Result:
Thus, the C++ program was executed successfully
EX.NO: 06 DYNAMIC MEMORY ALLOCATION

DATE:

Aim:

To demonstrate pointers Dynamic memory allocation using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Define a class with its members and member functions.

STEP 3: In the main function, declare a pointer to the class type

STEP 4: To create an object of the class on the heap and assign its address to the
pointer.

STEP 6: Access the object's members using the pointer

STEP 7: Modify the object's properties through the pointer.

STEP 8: Display the modified information.

STEP 9: Release the dynamically allocated memory using delete to avoid


memory leaks.

STEP 10 : End the program.

Flowchart:
Program:
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) : name(n), age(a) {}
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person *personPtr = new Person("Alice", 30);
cout << "Accessing object using pointer:" << endl;
personPtr->displayInfo();
cout << endl;
personPtr->name = "Bob";
personPtr->age = 35;
cout << "Modified object information:" << endl;
personPtr->displayInfo();
cout << endl;
delete personPtr;
return 0;
}
Output:
Accessing object using pointer:
Name: Alice
Age: 30

Modified object information:


Name: Bob
Age: 35

Result:
Thus, the C++ program was executed successfully
EX.NO: 07 UNARY OPERATOR OVERLOADING

DATE:

Aim:

To demonstrate Unary operator overloading using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Define a class with its members and member functions.

STEP 3: Overload the unary operator that provide custom behavior for within the
class.

STEP 4: In the operator overloading functions, specify the operator to behave


when applied to objects of your class.

STEP 5: In the main function, create an object of the class .

STEP 6: Apply unary operators to the object and store the results in other objects.

STEP 7: Display the results to demonstrate the custom behavior of the overloaded
unary operators.

STEP 8: End the program.

Flowchart:
Program:
#include <iostream>
using namespace std;
class MyNumber {
private:
int value;
public:
MyNumber(int val) : value(val) {}
MyNumber operator+() {
return MyNumber(value);
}
MyNumber operator-() {
return MyNumber(-value);
}
void displayNumber() {
cout << "Number: " << value << endl;
}
};

int main() {
MyNumber num1(10);
MyNumber num2 = +num1; // Unary '+' operator
MyNumber num3 = -num1; // Unary '-' operator
cout << "Original number:" << endl;
num1.displayNumber();
cout << endl;
cout << "Using unary '+' operator:" << endl;
num2.displayNumber();
cout << endl;
cout << "Using unary '-' operator:" << endl;
num3.displayNumber();
return 0;
}
Output:
Original number:
Number: 10

Using unary '+' operator:


Number: 10

Using unary '-' operator:


Number: -10

Result:
Thus, the C++ program was executed successfully
EX.NO: 08 BINARY OPERATOR OVERLOADING

DATE:

Aim:

To demonstrate Binary operator overloading using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Define a class with its members and member functions.

STEP 3: Overload the binary operatorand provide custom behavior for within the
class.

STEP 4: In the operator overloading functions, specify the operator to behave


objects of class

STEP 5: In the main function, create objects of the class and apply binary
operators

STEP 6: Display the results to demonstrate the custom behavior of the overloaded
binary operators.

STEP 7: End the program.

Flowchart:
Program:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) {
return Complex(real - other.real, imag - other.imag);
}
void displayComplex() {
cout << "(" << real << " + " << imag << "i)" << endl;
}
};
int main() {
Complex num1(2.5, 3.0);
Complex num2(1.5, 2.0);
Complex sum = num1 + num2; // Binary '+' operator
Complex diff = num1 - num2; // Binary '-' operator
cout << "Complex number 1: ";
num1.displayComplex();
cout << "Complex number 2: ";
num2.displayComplex();
cout << "Sum of complex numbers: ";
sum.displayComplex();
cout << "Difference of complex numbers: ";
diff.displayComplex();
return 0;
}
Output:
Complex number 1: (2.5 + 3i)
Complex number 2: (1.5 + 2i)
Sum of complex numbers: (4 + 5i)
Difference of complex numbers: (1 + 1i)

Result:

Thus, the C++ program was executed successfully


EX.NO: 09 INHERITANCE

DATE:

Aim:

To demonstrate Single Inheritance using C++ program

Algorithm:

STEP 1: Start the program

STEP 2:Create a base class with attributes and methods.

STEP 3:Create a derived class that inherits from the base class

STEP 4:Define additional attributes and methods in the derived class.

STEP 5:Access both base class and derived class methods in the main program.

STEP 5: End the program.

Flowchart:
Program:
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog is barking" << endl;
}
};
int main() {
Dog myDog;
myDog.eat();
myDog.bark();
return 0;
}

Output
Animal is eating
Dog is barking
Aim:

To demonstrate Multilevel Inheritance using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Create a base class with attributes and methods.

STEP 3: Create an intermediate class that inherits from the base class.
STEP 4: Create a derived class that inherits from the intermediate class.
STEP 5: Define additional attributes and methods in the derived class.
STEP 6: Access methods from all levels of the hierarchy in the main

STEP 5: End the program.

Flowchart:

Program:
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};
class Mammal : public Animal {
public:
void giveBirth() {
cout << "Mammal is giving birth" << endl;
}
};
class Dog : public Mammal {
public:
void bark() {
cout << "Dog is barking" << endl;
}
};
int main() {
Dog myDog;
myDog.eat();
myDog.giveBirth();
myDog.bark();
return 0;
}
Output
Animal is eating
Mammal is giving birth
Dog is barking
Aim:

To demonstrate Multiple Inheritance using C++ program

Algorithm:

STEP 1: Start the program

STEP 1: Create multiple base classes with attributes and methods.


STEP 1: Create a derived class that inherits from multiple base classes.
STEP 1: Define additional attributes and methods in the derived class.
STEP 1: Access methods from all base classes and the derived class in the main
program.
STEP 5: End the program.

Flowchart:

Program:
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};
class Machine {
public:
void operate() {
cout << "Machine is operating" << endl;
}
};
class Robot : public Animal, public Machine {
public:
void work() {
cout << "Robot is working" << endl;
}
};
int main() {
Robot myRobot;
myRobot.eat();
myRobot.operate();
myRobot.work();
return 0;
}
Output
Animal is eating
Machine is operating
Robot is working
Aim:

To demonstrate Hierarchical Inheritance using C++ program

Algorithm:

STEP 1: Start the program

STEP 1: Create a base class with attributes and methods.


STEP 2: Create multiple derived classes, each inheriting from the same base
class.
STEP 3: Define additional attributes and methods in the derived classes.
STEP 4: Access base class and derived class methods in the main program for
each derived class.
STEP 5: End the program.

Flowchart:

Program:
class Shape {
public:
void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void drawCircle() {
cout << "Drawing a circle" << endl;
}
};
class Square : public Shape {
public:
void drawSquare() {
cout << "Drawing a square" << endl;
}
};
int main() {
Circle myCircle;
Square mySquare;
myCircle.draw();
myCircle.drawCircle();
mySquare.draw();
mySquare.drawSquare();
return 0;
}
Output
Drawing a shape
Drawing a circle
Drawing a shape
Drawing a square
Result:
Thus, the C++ program was executed successfully
EX.NO: 10 VIRTUAL FUNCTION

DATE:

Aim:

To demonstrate virtual function using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Create a base class with a virtual function

STEP 3: Create derived classes that inherit from the base class.

STEP 4: Override the virtual function in each derived class with its own
implementation.

STEP 5: In the main() function, create instances of the derived classes and a
pointer to the base class.

STEP 6: Assign the derived class objects to the base class pointer.
End the program.

STEP 7: Call the virtual function using the base class pointer.

STEP 8: End the program

Flowchart:
Program:
#include <iostream>
using namespace std;
class Animal {
public:
virtual void makeSound() {
cout << "Animal makes a generic sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
cout << "Cat meows" << endl;
}
};
int main() {
Animal* myAnimal;
Dog myDog;
Cat myCat;
myAnimal = &myDog;
myAnimal->makeSound();
myAnimal = &myCat;
myAnimal->makeSound();
return 0;
}

Output:
Dog barks
Cat meows

Result:
Thus, the C++ program was executed successfully
EX.NO: 11 TEXT FILE

DATE:

Aim:

To manipulate a text file using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Open the input file for reading.


STEP 3: Check if the input file opened successfully.
STEP 4: Open the output file for writing.
STEP 5: Check if the output file opened successfully.
STEP 6: Read lines from the input file one by one until the end of the file.
STEP 7: Write each line to the output file.
STEP 8: Close both the input and output files.
STEP 9: Display a success message.
STEP10: End the program

Flow chart:
Program:
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("input.txt");
if (!inputFile) {
std::cerr << "Failed to open input file!" << std::endl;
return 1;
}

std::ofstream outputFile("output.txt");
if (!outputFile) {
std::cerr << "Failed to open output file!" << std::endl;
return 1;
}
std::string line;
while (std::getline(inputFile, line)) {
outputFile << line << std::endl;
}
inputFile.close();
outputFile.close();
std::cout << "Text copied from input.txt to output.txt successfully." << std::endl;
return 0;
}
Output:
g++ file_copy.cpp -o file_copy
./file_copy

Result:

Thus, the C++ program was executed successfully


EX.NO: 12 I/O OPERATION ON A FILE

DATE:

Aim:

To perform sequential I/O operation on a file using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Open the input file for reading.

STEP 3: Check if the input file opened successfully.


STEP 4: Open the output file for writing.
STEP 5: Check if the output file opened successfully.
STEP 6: Define variables to store the data read from the input file.
STEP 7: Use a while loop to read data from the input file using the >> operator.
STEP 8: Perform operations with the read data as needed.
STEP 9: Close both the input and output files using the close() method.
STEP10: Display a success message indicating that the data has been copied
STEP11: End the program

Flowchart:
Program:
#include <iostream>
#include <fstream>
int main() {
// Open an input file for reading
std::ifstream inputFile("input.txt");
if (!inputFile) {
std::cerr << "Failed to open input file!" << std::endl;
return 1;
}
std::ofstream outputFile("output.txt");
if (!outputFile) {
std::cerr << "Failed to open output file!" << std::endl;
return 1;
}
int number;
std::string text;
while (inputFile >> number >> text) {
outputFile << "Number: " << number << ", Text: " << text << std::endl;
}
inputFile.close();
outputFile.close();
std::cout << "Data copied from input.txt to output.txt successfully." << std::endl;
return 0;
}
Output
Data copied from input.txt to output.txt successfully

Result:
Thus, the C++ program was executed successfully
EX.NO: 13 COMMAND LINE ARGUMENTS

DATE:

Aim:

To find the biggest number in command line arguments using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Check the number of command-line arguments

STEP 3: Initialize a variable largest with the integer value of the first command-

line argument

STEP 4: Use a for loop to iterate through the remaining command-line arguments

(argv[i] for i starting from 2

STEP 5: Inside the loop, convert the current command-line argument to an integer

using the atoi function and store it in a variable

STEP 6: print the value of largest to the console

STEP 7: End the program

Flowchart:
Program:
#include <iostream>
#include <cstdlib>
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " number1 number2 number3 ..." <<
std::endl;
return 1;
}
int largest = atoi(argv[1]);
for (int i = 2; i < argc; ++i) {
int currentNumber = atoi(argv[i]);
if (currentNumber > largest) {
largest = currentNumber;
}
}
std::cout << "The largest number is: " << largest << std::endl;
return 0;
}
Output:
The largest number is: 20

Result:
Thus, the C++ program was executed successfully
EX.NO: 14 CLASS TEMPLATE

DATE:

Aim:

To demonstrate class template using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Define the class template using the template keyword

STEP 3: Inside the class template declare member variables and functions that use
the template parameter T
STEP 4: In the main function instantiate objects of the class template by
specifying the template argument
STEP 5: Initialize the objects with appropriate values
STEP 6: Call member functions on these objects to perform operations
STEP 7: Compile and run the program
STEP 8: End the program

Flowchart:
Program:
#include <iostream>
template <typename T>
class MyTemplateClass {
public:
MyTemplateClass(T value) : data(value) {}

void printData() {
std::cout << "Data: " << data << std::endl;
}
private:
T data;
};
int main() {
MyTemplateClass<int> intObj(42);
MyTemplateClass<double> doubleObj(3.14);
MyTemplateClass<std::string> stringObj("Hello, World!");
intObj.printData();
doubleObj.printData();
stringObj.printData();
return 0;
}
Output:
Hello, World!

3.14
42

Result:
Thus, the C++ program was executed successfully
EX.NO: 15 FUNCTION TEMPLATE

DATE:

Aim:

To demonstrate function template using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Declare a function template findMax with a template parameter T.

STEP 3: Inside the function template, define two parameters a and b of type T.

STEP 4: Use the conditional operator (?:) to compare a and b.


STEP 5: In the main function, use the findMax function template with different
data types
STEP 6: Print the results.

STEP 7: End the program

Flowchart:
Program:
#include <iostream>
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int intResult = findMax(10, 20);
double doubleResult = findMax(3.14, 2.71);
std::cout << "Max of 10 and 20 is: " << intResult << std::endl;
std::cout << "Max of 3.14 and 2.71 is: " << doubleResult << std::endl;
return 0;
}
Output:
Max of 10 and 20 is: 20
Max of 3.14 and 2.71 is: 3.14

Result:
Thus, the C++ program was executed successfully
EX.NO: 16 EXCEPTION HANDLING

DATE:

Aim:

To demonstrate Exception handling using C++ program

Algorithm:

STEP 1: Start the program

STEP 2: Create a function (divide that can potentially throw an exception

STEP 3: In this function, check if the denominator is zero


STEP 4: In the main function, set up a try block. Inside the try block
STEP 5: If an exception is thrown within the try block, it is caught by a
corresponding catch block
STEP 6: Compile and run the program.
STEP 7: End the program

Flowchart:
Program:
#include <iostream>
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw std::runtime_error("Division by zero is not allowed.");
}
return static_cast<double>(numerator) / denominator;
}

int main() {
try {
int numerator, denominator;
std::cout << "Enter numerator: ";
std::cin >> numerator;
std::cout << "Enter denominator: ";
std::cin >> denominator;
double result = divide(numerator, denominator);
std::cout << "Result of division: " << result << std::endl;
}
catch (const std::runtime_error& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
return 0;
}
Output:
Enter numerator: 10
Enter denominator: 2
Result of division: 5
Enter numerator: 5
Enter denominator: 0
Error: Division by zero is not allowed.

Result:
Thus, the C++ program was executed successfully

You might also like