0% found this document useful (0 votes)
39 views

BCA C++ Lab Solutions

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)
39 views

BCA C++ Lab Solutions

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/ 28

1. Write a C++ Program to create a class to implement the data structure STACK.

Write a constructor to initialize the TOP of the STACK. Write a member function
PUSH ( ) to insert an element and member function POP () to delete an element
check for over flow and under flow conditions..

#include <iostream>
class Stack {
static const int MAX_SIZE = 5;
int top;
int elements[MAX_SIZE];

// Constructor
Stack() : top(-1) {}

// Push method
void push(int value) {
if (top == MAX_SIZE - 1) {
std::cout << "Stack Overflow\n";
} else {
elements[++top] = value;
std::cout << "Pushed: " << value << std::endl;
}
}

// Pop method
void pop() {
if (top == -1) {
std::cout << "Stack Underflow\n";
} else {
std::cout << "Popped: " << elements[top--] << std::endl;
}
}

friend int main(); // Declaring main() as a friend for simplicity


};
int main() {
Stack myStack;

myStack.push(3);
myStack.push(7);
myStack.push(9);
myStack.push(11);
myStack.push(13);
myStack.push(15);

myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop(); // This will demonstrate stack underflow
myStack.pop();

return 0;
}
Output:
Pushed: 3
Pushed: 7
Pushed: 9
Pushed:11
Pushed:13
Stack Overflow
Pop:13
Pop:11
Pop:9
Pop:7
Pop:3

2. Write a C++ Program to create a class ARITHMETIC which consists of a


FLOAT and an INTEGER variable. Write member functions ADD(),
SUB(),MUL(),DIV()to perform addition, subtraction, multiplication, division
respectively. Write a member function to get and Display values.

#include <iostream>
class ARITHMETIC {
float floatingNumber;
int integerNumber;

ARITHMETIC(float fNum, int iNum) : floatingNumber(fNum),


integerNumber(iNum) {}

float ADD() {
return floatingNumber + integerNumber;
}

float SUB() {
return floatingNumber - integerNumber;
}

float MUL() {
return floatingNumber * integerNumber;
}

float DIV() {
if (integerNumber != 0) {
return floatingNumber / integerNumber;
} else {
std::cout << "Error: Division by zero.\n";
return 0.0;
}
}

void displayValues() {
std::cout << "Floating Number: " << floatingNumber << "\n";
std::cout << "Integer Number: " << integerNumber << "\n";
}

friend int main(); // Declaring main() as a friend for simplicity


};

int main() {
ARITHMETIC arithmeticObj(5.5, 2);

arithmeticObj.displayValues();

std::cout << "Addition: " << arithmeticObj.ADD() << "\n";


std::cout << "Subtraction: " << arithmeticObj.SUB() << "\n";
std::cout << "Multiplication: " << arithmeticObj.MUL() << "\n";
std::cout << "Division: " << arithmeticObj.DIV() << "\n";

return 0;
}

Output:
Floating Number: 5.5
Integer Number: 2
Addition: 7.5
Subtraction: 3.5
Multiplication: 11
Division: 2.75

3. Write a C++ Program to read an integer number and find the sum of all the digits
until it reduces to a single digit using constructors, destructors and inline member
functions.

#include <iostream>

class DigitSum {
int number;
inline int calculateSum() const {
int sum = 0;
int temp = number;

while (temp != 0) {
sum += temp % 10;
temp /= 10;
}

return sum;
}

DigitSum(int num) : number(num) {


std::cout << "Constructed with number: " << number << std::endl;
}

~DigitSum() {
std::cout << "Destructed with number: " << number << std::endl;
}

void performDigitSum() {
while (number >= 10) {
int sum = calculateSum();
std::cout << "Sum of digits: " << sum << std::endl;
number = sum;
}

std::cout << "Final Single Digit Sum: " << number << std::endl;
}

friend int main(); // Declaring main() as a friend for simplicity


};

int main() {
int inputNumber;
std::cout << "Enter an integer number: ";
std::cin >> inputNumber;

DigitSum digitSumObj(inputNumber);
digitSumObj.performDigitSum();

return 0;
}

Input:
9875
Output:
Enter an integer number: 9875
Constructed with number: 9875
Sum of digits: 29
Sum of digits: 11
Sum of digits: 2
Final Single Digit Sum: 2
Destructed with number: 9875

4. Write a C++ Program to create a class FLOAT that contains one float data
member. Overload all the four Arithmetic operators so that they operate on the
object FLOAT.

#include <iostream>

class FLOAT {
float value;

FLOAT(float val) : value(val) {}

FLOAT operator+(const FLOAT& other) const {


return FLOAT(value + other.value);
}
FLOAT operator-(const FLOAT& other) const {
return FLOAT(value - other.value);
}

FLOAT operator*(const FLOAT& other) const {


return FLOAT(value * other.value);
}

FLOAT operator/(const FLOAT& other) const {


if (other.value != 0) {
return FLOAT(value / other.value);
} else {
std::cerr << "Error: Division by zero.\n";
return FLOAT(0.0);
}
}

void displayValue() const {


std::cout << "Value: " << value << std::endl;
}

friend int main();


};

int main() {
float input1, input2;

// Get user input


std::cout << "Enter first float number: ";
std::cin >> input1;

std::cout << "Enter second float number: ";


std::cin >> input2;
FLOAT num1(input1);
FLOAT num2(input2);

// Perform arithmetic operations


FLOAT resultAdd = num1 + num2;
std::cout << "Addition result: ";
resultAdd.displayValue();

FLOAT resultSub = num1 - num2;


std::cout << "Subtraction result: ";
resultSub.displayValue();

FLOAT resultMul = num1 * num2;


std::cout << "Multiplication result: ";
resultMul.displayValue();

FLOAT resultDiv = num1 / num2;


std::cout << "Division result: ";
resultDiv.displayValue();

return 0;
}

Input:
Enter first float number: 12.5
Enter second float number: 3.5
Output:
Addition result: Value: 16
Subtraction result: Value: 9
Multiplication result: Value: 43.75
Division result: Value: 3.57143

5. Write a C++ Program to create a class STRING. Write a Member Function to


initialize, get and is play stings. Overload the operators ++ and == to concatenate
two Strings and to compare two strings respectively.
#include <iostream>
#include <cstring>

class STRING {
char* str;

public:
STRING(const char* s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}

void displayString() const {


std::cout << "String: " << str << std::endl;
}

STRING& operator++() {
char* temp = new char[strlen(str) * 2 + 1];
strcpy(temp, str);
strcat(temp, str);
delete[] str;
str = temp;
return *this;
}

bool isEqual(const STRING& other) const {


return strcmp(str, other.str) == 0;
}

~STRING() {
delete[] str;
}
};
int main() {
char input1[100], input2[100];

std::cout << "Enter the first string: ";


std::cin.getline(input1, sizeof(input1));

STRING str1(input1);

std::cout << "Enter the second string: ";


std::cin.getline(input2, sizeof(input2));

STRING str2(input2);

std::cout << "Initial Strings:\n";


str1.displayString();
str2.displayString();

++str1;

std::cout << "Concatenated String:\n";


str1.displayString();

if (str1.isEqual(str2)) {
std::cout << "Strings are equal\n";
} else {
std::cout << "Strings are not equal\n";
}

return 0;
}

Input:
Enter the first string: Hello
Enter the second string: World
Output:
Initial Strings:
String: Hello
String: World
Concatenated String:
String: HelloHello
Strings are not equal

6. Write a C++ Program to create class, which consists of EMPLOYEE Detail like
E_Number, E_Name, Department, Basic,Salary,Grade.Writea member function to
get and display them.
Derive a class PAY from the above class and write a member function to calculate
DA, HRA and PF depending on the grade.

#include <iostream>
#include <string>

class Employee {
public:
int E_Number;
std::string E_Name;
std::string Department;
double BasicSalary;
char Grade;

// Member function to get employee details


void getDetails() {
std::cout << "Enter Employee Number: ";
std::cin >> E_Number;

std::cin.ignore(); // Clear the newline character from the buffer

std::cout << "Enter Employee Name: ";


std::getline(std::cin, E_Name);

std::cout << "Enter Department: ";


std::getline(std::cin, Department);

std::cout << "Enter Basic Salary: ";


std::cin >> BasicSalary;

std::cout << "Enter Grade: ";


std::cin >> Grade;
}

// Member function to display employee details


void displayDetails() const {
std::cout << "Employee Details:\n";
std::cout << "Employee Number: " << E_Number << "\n";
std::cout << "Employee Name: " << E_Name << "\n";
std::cout << "Department: " << Department << "\n";
std::cout << "Basic Salary: " << BasicSalary << "\n";
std::cout << "Grade: " << Grade << "\n";
}
};

class Pay : public Employee {


public:
// Member function to calculate DA (Dearness Allowance)
double calculateDA() const {
if (Grade == 'A') {
return 0.1 * BasicSalary;
} else {
return 0.05 * BasicSalary;
}
}

// Member function to calculate HRA (House Rent Allowance)


double calculateHRA() const {
if (Grade == 'A') {
return 0.2 * BasicSalary;
} else {
return 0.1 * BasicSalary;
}
}

// Member function to calculate PF (Provident Fund)


double calculatePF() const {
return 0.12 * BasicSalary;
}
};

int main() {
Pay employee;

// Get employee details from the user


employee.getDetails();

// Display employee details


employee.displayDetails();

// Calculate and display DA, HRA, and PF


std::cout << "DA: " << employee.calculateDA() << "\n";
std::cout << "HRA: " << employee.calculateHRA() << "\n";
std::cout << "PF: " << employee.calculatePF() << "\n";

return 0;
}

Input:
Enter Employee Number: 101
Enter Employee Name: John Doe
Enter Department: IT
Enter Basic Salary: 50000.50
Enter Grade: A
Output:
Employee Details:
Employee Number: 101
Employee Name: John Doe
Department: IT
Basic Salary: 50000.5
Grade: A
DA: 5000.05
HRA: 10000.1
PF: 6000.06

7. Write a C++ Program to create a class SHAPE which consists of two VIRTUAL
FUNCTIONS Calculate_Area () and Calculate_Perimeter () to calculate area and
perimeter of various figures. Derive three classes SQUARE, RECTANGLE,
TRIANGE from class Shape and Calculate Are a and Perimeter of each class
separately and display the result.

#include <iostream>
#include <cmath>

class Shape {
public:
virtual void calculateArea() = 0;
virtual void calculatePerimeter() = 0;
};

class Square : public Shape {


private:
double side;

public:
Square(double s) : side(s) {}

void calculateArea() override {


std::cout << "Area of Square: " << side * side << "\n";
}
void calculatePerimeter() override {
std::cout << "Perimeter of Square: " << 4 * side << "\n";
}
};

class Rectangle : public Shape {


private:
double length;
double width;

public:
Rectangle(double l, double w) : length(l), width(w) {}

void calculateArea() override {


std::cout << "Area of Rectangle: " << length * width << "\n";
}

void calculatePerimeter() override {


std::cout << "Perimeter of Rectangle: " << 2 * (length + width) << "\n";
}
};

class Triangle : public Shape {


private:
double a;
double b;
double c;

public:
Triangle(double sideA, double sideB, double sideC) : a(sideA), b(sideB),
c(sideC) {}

void calculateArea() override {


double s = (a + b + c) / 2;
double area = sqrt(s * (s - a) * (s - b) * (s - c));
std::cout << "Area of Triangle: " << area << "\n";
}

void calculatePerimeter() override {


std::cout << "Perimeter of Triangle: " << a + b + c << "\n";
}
};

int main() {
double sideSquare, lengthRectangle, widthRectangle, sideATriangle,
sideBTriangle, sideCTriangle;

std::cout << "Enter side length for Square: ";


std::cin >> sideSquare;

std::cout << "Enter length for Rectangle: ";


std::cin >> lengthRectangle;

std::cout << "Enter width for Rectangle: ";


std::cin >> widthRectangle;

std::cout << "Enter side A for Triangle: ";


std::cin >> sideATriangle;

std::cout << "Enter side B for Triangle: ";


std::cin >> sideBTriangle;

std::cout << "Enter side C for Triangle: ";


std::cin >> sideCTriangle;

Square square(sideSquare);
Rectangle rectangle(lengthRectangle, widthRectangle);
Triangle triangle(sideATriangle, sideBTriangle, sideCTriangle);
square.calculateArea();
square.calculatePerimeter();

rectangle.calculateArea();
rectangle.calculatePerimeter();

triangle.calculateArea();
triangle.calculatePerimeter();

return 0;
}

Input:
Enter side length for Square: 5.0
Enter length for Rectangle: 4.0
Enter width for Rectangle: 6.0
Enter side A for Triangle: 3.0
Enter side B for Triangle: 4.0
Enter side C for Triangle: 5.0

Output:
Area of Square: 25
Perimeter of Square: 20
Area of Rectangle: 24
Perimeter of Rectangle: 20
Area of Triangle: 6
Perimeter of Triangle: 12

8. Write a C++ Program to create two classes each class consists of two private
variables, a integer and a float variable. Write member functions to get and display
them. Write a FRIEND Function common to both classes, which takes the object of
above two classes as arguments and the integer and float values of both objects
separately and display the result.

#include <iostream>
class Class1; // Forward declaration

class Class2 {
private:
int intValue;
float floatValue;

public:
// Member functions to get and display values
void getValues() {
std::cout << "Enter integer value for Class2: ";
std::cin >> intValue;
std::cout << "Enter float value for Class2: ";
std::cin >> floatValue;
}

void displayValues() const {


std::cout << "Class2 Values:\n";
std::cout << "Integer: " << intValue << "\n";
std::cout << "Float: " << floatValue << "\n";
}

// Friend function declaration


friend void displayCommonValues(const Class1& obj1, const Class2& obj2);
};

class Class1 {
private:
int intValue;
float floatValue;

public:
// Member functions to get and display values
void getValues() {
std::cout << "Enter integer value for Class1: ";
std::cin >> intValue;
std::cout << "Enter float value for Class1: ";
std::cin >> floatValue;
}

void displayValues() const {


std::cout << "Class1 Values:\n";
std::cout << "Integer: " << intValue << "\n";
std::cout << "Float: " << floatValue << "\n";
}

// Friend function declaration


friend void displayCommonValues(const Class1& obj1, const Class2& obj2);
};

// Friend function definition


void displayCommonValues(const Class1& obj1, const Class2& obj2) {
std::cout << "Common Values:\n";
std::cout << "Integer from Class1: " << obj1.intValue << "\n";
std::cout << "Float from Class1: " << obj1.floatValue << "\n";
std::cout << "Integer from Class2: " << obj2.intValue << "\n";
std::cout << "Float from Class2: " << obj2.floatValue << "\n";
}

int main() {
Class1 object1;
Class2 object2;

object1.getValues();
object2.getValues();

object1.displayValues();
object2.displayValues();
// Call the friend function with objects of both classes
displayCommonValues(object1, object2);

return 0;
}

Input:
Enter integer value for Class1: 10
Enter float value for Class1: 5.5
Enter integer value for Class2: 20
Enter float value for Class2: 3.14

Output:
Class1 Values:
Integer: 10
Float: 5.5
Class2 Values:
Integer: 20
Float: 3.14
Common Values:
Integer from Class1: 10
Float from Class1: 5.5
Integer from Class2: 20
Float from Class2: 3.14

9. Write a C++ Program using Function Over loading to read two Matrices of
different Data Types such as integers and floating point numbers.Find out the sum
of the above two matrices separately and display the sum of the searrays
individually.

#include <iostream>

// Function to sum matrices of integers


void sumIntMatrices(int matrix1[3][3], int matrix2[3][3]) {
int sumMatrix[3][3];
std::cout << "Sum of Matrices (Integers):\n";
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
std::cout << sumMatrix[i][j] << " ";
}
std::cout << "\n";
}
}

// Function to sum matrices of floating-point numbers


void sumFloatMatrices(float matrix1[3][3], float matrix2[3][3]) {
float sumMatrix[3][3];

std::cout << "Sum of Matrices (Floating-Point Numbers):\n";


for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
std::cout << sumMatrix[i][j] << " ";
}
std::cout << "\n";
}
}

int main() {
int intMatrix1[3][3], intMatrix2[3][3];
float floatMatrix1[3][3], floatMatrix2[3][3];

std::cout << "Enter elements for Matrix 1 (Integers):\n";


for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
std::cin >> intMatrix1[i][j];

std::cout << "Enter elements for Matrix 2 (Integers):\n";


for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
std::cin >> intMatrix2[i][j];

std::cout << "Enter elements for Matrix 1 (Floating-Point Numbers):\n";


for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
std::cin >> floatMatrix1[i][j];

std::cout << "Enter elements for Matrix 2 (Floating-Point Numbers):\n";


for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
std::cin >> floatMatrix2[i][j];

sumIntMatrices(intMatrix1, intMatrix2);
sumFloatMatrices(floatMatrix1, floatMatrix2);

return 0;
}

Input:
Enter elements for Matrix 1 (Integers):
123
456
789
Enter elements for Matrix 2 (Integers):
987
654
321
Enter elements for Matrix 1 (Floating-Point Numbers):
1.1 2.2 3.3
4.4 5.5 6.6
7.7 8.8 9.9
Enter elements for Matrix 2 (Floating-Point Numbers):
9.9 8.8 7.7
6.6 5.5 4.4
3.3 2.2 1.1

Output:
Sum of Matrices (Integers):
10 10 10
10 10 10
10 10 10
Sum of Matrices (Floating-Point Numbers):
10 10 10
10 10 10
10 10 10

10. Write a C++ Program to check whether the given string is a palindrome or not
using Pointers.

#include <iostream>
#include <cstring>

int isPalindrome(const char* str) {


const char* start = str;

// Move end pointer to the end of the string


const char* end = str;
while (*end != '\0') {
++end;
}
--end; // Move back from null terminator

while (start < end) {


if (*start != *end) {
return 0; // Not a palindrome
}
++start;
--end;
}

return 1; // Palindrome
}

int main() {
char input[100];

std::cout << "Enter a string: ";


std::cin.getline(input, sizeof(input));

if (isPalindrome(input)) {
std::cout << "The string is a palindrome.\n";
} else {
std::cout << "The string is not a palindrome.\n";
}

return 0;
}

Input:
Enter a string: radar
Output:
The string is a palindrome.

11. Write a C++ Program to create a File and to display the contents of that file
with line numbers.

Algorithm:
1. The mergeFiles function takes two input file names (inputFile1 and inputFile2)
and an output file name (outputFile).
2. It opens the first and second input files for reading and the output file for
writing.
3. The contents of the first file are read and written to the output file.
4. Then, the contents of the second file are read and appended to the output file.
5. Finally, all files are closed, and a success message is displayed.

Make sure to replace "file1.txt", "file2.txt", and "mergedFile.txt" with the actual
file names you want to use.

#include <iostream>
#include <fstream>

void createAndDisplayFile(const char* filename) {


// Create and write content to the file
std::ofstream outFile(filename);
if (!outFile) {
std::cerr << "Error creating the file.\n";
return;
}

outFile << "Hello, this is line 1.\n";


outFile << "And here is line 2.\n";
outFile << "This is line 3.\n";

outFile.close();

// Display the contents of the file with line numbers


std::ifstream inFile(filename);
if (!inFile) {
std::cerr << "Error opening the file.\n";
return;
}

int lineNumber = 1;
std::string line;
while (std::getline(inFile, line)) {
std::cout << "Line " << lineNumber << ": " << line << std::endl;
lineNumber++;
}

inFile.close();
}

int main() {
const char* filename = "sample.txt";

createAndDisplayFile(filename);

return 0;
}

Input:
Hello, this is line 1.
And here is line 2.
This is line 3.

Output:
Line 1: Hello, this is line 1.
Line 2: And here is line 2.
Line 3: This is line 3.

12. Write a C++ Program to merge two files into a single file.
#include <iostream>
#include <fstream>

void mergeFiles(const char* inputFile1, const char* inputFile2, const char*


outputFile) {
// Open the first input file
std::ifstream file1(inputFile1);
if (!file1) {
std::cerr << "Error opening the first input file.\n";
return;
}
// Open the second input file
std::ifstream file2(inputFile2);
if (!file2) {
std::cerr << "Error opening the second input file.\n";
return;
}

// Open the output file for writing


std::ofstream mergedFile(outputFile);
if (!mergedFile) {
std::cerr << "Error creating the output file.\n";
return;
}

// Merge contents of the first file


char ch;
while (file1.get(ch)) {
mergedFile.put(ch);
}

// Merge contents of the second file


while (file2.get(ch)) {
mergedFile.put(ch);
}

// Close all files


file1.close();
file2.close();
mergedFile.close();

std::cout << "Files merged successfully.\n";


}

int main() {
const char* inputFile1 = "file1.txt";
const char* inputFile2 = "file2.txt";
const char* outputFile = "mergedFile.txt";

mergeFiles(inputFile1, inputFile2, outputFile);

return 0;
}

Input:
Content of file1.txt:
This is the content of file1.
It has multiple lines.

Content of file2.txt:
And this is the content of file2.
It also has multiple lines.

(//Now, let's run the program with these inputs. The output will be a new file
named mergedFile.txt with the merged content:)

Output:
Content of mergedFile.txt:
This is the content of file1.
It has multiple lines.
And this is the content of file2.
It also has multiple lines.

You might also like