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

C++ assignment 3 (Deepti)

Uploaded by

kumarideepti2901
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C++ assignment 3 (Deepti)

Uploaded by

kumarideepti2901
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

C++ Assignment-3

B.Sc. (H) Computer


Science
Sem-2

Submitted by:
DEEPTI
(230421)
Section-A
1. Copy the contents of one text file to another file, after removing
all whitespaces.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
// Input and output filenames
string inputFile, outputFile;

cout << "Enter the name of the input file: ";


cin >> inputFile;

cout << "Enter the name of the output file: ";


cin >> outputFile;

// Open files
ifstream inputStream(inputFile);
ofstream outputStream(outputFile);

// Check if files opened successfully


if (!inputStream.is_open()) {
cerr << "Error opening input file: " << inputFile << endl;
return 1;
}

if (!outputStream.is_open()) {
cerr << "Error opening output file: " << outputFile << endl;
return 1;
}

string line;
string newLine;

// Read line by line from input file


while (getline(inputStream, line)) {
// Remove whitespaces (spaces, tabs, newlines)
for (char c : line) {
if (!isspace(c)) {
newLine += c;
}
}
// Write the modified line to the output file
outputStream << newLine << endl;
// Clear newLine for next iteration
newLine.clear();
}
// Close files
inputStream.close();
outputStream.close();

cout << "File copied successfully! Whitespaces removed." << endl;

return 0;
}

2. Count the number of words in the given text file. Words can be
separated by space(s), or tab(s).

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
// Input filename
string filename;

cout << "Enter the name of the text file: ";


cin >> filename;
// Open file
ifstream file(filename);

// Check if file opened successfully


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

string line;
int wordCount = 0;

// Read line by line


while (getline(file, line)) {
// Split line into words using a stream
istringstream iss(line);
string word;

// Count words using the istream


while (iss >> word) {
wordCount++;
}
}

// Close file
file.close();
cout << "The text file contains " << wordCount << " words." << endl;

return 0;
}

3. Define a class Person having a name as a data member. Inherit


two classes, Student and Employee, from Person. The student has
additional attributes such as course, marks and year, and the
Employee has department and salary. Write a display () method in
all three classes to display the corresponding attributes. Provide
the necessary methods to show runtime polymorphism.

#include <iostream>
#include <string>

class Person {
public:
Person(const std::string& name) : name(name) {}

void display() {
std::cout << "Name: " << name << std::endl;
}

private:
std::string name;
};

class Student : public Person {


public:
Student(const std::string& name, const std::string& course, int marks)
: Person(name), course(course), marks(marks) {}

void display() override {


Person::display(); // Call base class display
std::cout << "Course: " << course << ", Marks: " << marks << std::endl;
}

private:
std::string course;
int marks;
};

int main() {
Student student("Alice", "Computer Science", 85);
student.display();

return 0;
}
4. Create a Triangle class. Add exception handling statements to
ensure the following conditions: all sides are greater than 0, and
the sum of any two sides is greater than the third. The class
should also have overloaded functions for calculating the area of a
right-angled triangle and using Heron’s formula to calculate the
area of any type of triangle.

#include <iostream>
#include <cmath>

class Triangle {
public:
Triangle(double side1, double side2, double side3) {
validateSides(side1, side2, side3);
sides[0] = side1;
sides[1] = side2;
sides[2] = side3;
}

double calculateArea(bool isRightAngled = false) const {


if (isRightAngled) {
return calculateRightAngledArea();
} else {
return calculateHeronArea();
}
}
private:
void validateSides(double side1, double side2, double side3) const {
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
throw std::invalid_argument("All sides must be positive values");
}
if (!(side1 + side2 > side3 && side2 + side3 > side1 && side1 + side3 > side2)) {
throw std::invalid_argument("Triangle inequality violated");
}
}

double calculateRightAngledArea() const {


// Assuming one of the sides is the hypotenuse (longest) based on sorting
return 0.5 * sides[0] * sides[1];
}

double calculateHeronArea() const {


double s = (sides[0] + sides[1] + sides[2]) / 2.0;
return std::sqrt(s * (s - sides[0]) * (s - sides[1]) * (s - sides[2]));
}

double sides[3];
};

int main() {
try {
Triangle triangle(3, 4, 5);
std::cout << "Area (Heron's formula): " << triangle.calculateArea() << std::endl;

// Assuming triangle is right-angled (modify as needed)


std::cout << "Area (Right-angled): " << triangle.calculateArea(true) << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}

return 0;
}

5. Write the declaration and definition for geometric classes defined


as follows and show their implementation:

Use the following requirements:


a. Define Shape, TwoDim and ThreeDim as abstract classes.
b. Define PI as a static class member in the Shape class
c. Define area calculation and print functions as pure virtual
functions in the Shape class.
d. Use public inheritance.
e. Define all data or member functions common to two-dimensional
shapes in the TwoDim class. Do the same for all common data or
member functions to three-dimensional shapes in the ThreeDim
class.

#include <iostream>
#include <string>

using namespace std;

// Abstract class Shape


class Shape {
public:
virtual double area() const = 0;
virtual void printInfo() const = 0;
};

// Triangle class
class Triangle : public Shape {
public:
Triangle(double base, double height) : m_base(base), m_height(height) {}

double area() const override { return 0.5 * m_base * m_height; }

void printInfo() const override {


cout << "Triangle with base " << m_base << " and height " << m_height << endl;
}

private:
double m_base, m_height;
};

// Rectangle class
class Rectangle : public Shape {
public:
Rectangle(double width, double height) : m_width(width), m_height(height) {}

double area() const override { return m_width * m_height; }

void printInfo() const override {


cout << "Rectangle with width " << m_width << " and height " << m_height <<
endl;
}

private:
double m_width, m_height;
};

// Circle class
class Circle : public Shape {
public:
Circle(double radius) : m_radius(radius) {}
double area() const override { return 3.14159 * m_radius * m_radius; }

void printInfo() const override {


cout << "Circle with radius " << m_radius << endl;
}

private:
double m_radius;
};

int main() {
Triangle triangle(5, 3);
Rectangle rectangle(4, 6);
Circle circle(2);

triangle.printInfo();
cout << "Triangle Area: " << triangle.area() << endl;

rectangle.printInfo();
cout << "Rectangle Area: " << rectangle.area() << endl;

circle.printInfo();
cout << "Circle Area: " << circle.area() << endl;

return 0;
}
6. Create a template function findPos() that accepts an array, the
size of the array and a key element. The function finds the key in
the given array and returns the index value if the key is found else
returns -1. Show the implementation with int, double and string
datatypes.

#include <iostream>
#include <string>

using namespace std;

template <typename T>


int findPos(const T arr[], int size, const T& key) {
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
return i; // Key found, return its index
}
}
return -1; // Key not found
}

int main() {
// Example with int array
int intArr[] = {10, 20, 30, 40, 50};
int intKey = 30;
int intPos = findPos(intArr, 5, intKey);
if (intPos != -1) {
cout << "Key " << intKey << " found at index " << intPos << " in intArr." << endl;
} else {
cout << "Key " << intKey << " not found in intArr." << endl;
}

// Example with double array


double doubleArr[] = {1.5, 2.4, 3.1, 4.2};
double doubleKey = 2.4;
int doublePos = findPos(doubleArr, 4, doubleKey);
if (doublePos != -1) {
cout << "Key " << doubleKey << " found at index " << doublePos << " in
doubleArr." << endl;
} else {
cout << "Key " << doubleKey << " not found in doubleArr." << endl;
}

// Example with string array


string stringArr[] = {"apple", "banana", "cherry"};
string stringKey = "banana";
int stringPos = findPos(stringArr, 3, stringKey);
if (stringPos != -1) {
cout << "Key " << stringKey << " found at index " << stringPos << " in stringArr."
<< endl;
} else {
cout << "Key " << stringKey << " not found in stringArr." << endl;
}
return 0;
}

7. Create a template class Vector to show input, display, and


addition of two Vectors. Implement it with int and double datatypes.

#include <iostream>
#include <vector>

template <typename T>


class Vector {
public:
// Constructor to initialize vector with size
Vector(int size) : data(size) {}

// Function to input elements of the vector


void input() {
for (int i = 0; i < data.size(); ++i) {
std::cout << "Enter element " << i + 1 << ": ";
std::cin >> data[i];
}
}

// Function to display elements of the vector


void display() const {
for (const T& element : data) {
std::cout << element << " ";
}
std::cout << std::endl;
}

// Function to add two vectors (assuming they have the same size)
Vector<T> operator+(const Vector<T>& other) const {
if (data.size() != other.data.size()) {
std::cerr << "Error: Vectors must have the same size for addition." << std::endl;
return Vector<T>(0); // Return empty vector on error
}
Vector<T> result(data.size());
for (int i = 0; i < data.size(); ++i) {
result.data[i] = data[i] + other.data[i];
}
return result;
}

private:
std::vector<T> data;
};

int main() {
int size;
std::cout << "Enter size of the vectors: ";
std::cin >> size;

// Vector of integers
Vector<int> intVec(size);
std::cout << "Enter elements for integer vector:\n";
intVec.input();

// Vector of doubles
Vector<double> doubleVec(size);
std::cout << "Enter elements for double vector:\n";
doubleVec.input();

std::cout << "Integer vector: ";


intVec.display();

std::cout << "Double vector: ";


doubleVec.display();

// Add vectors (assuming they have the same size)


Vector<int> intResult = intVec + intVec;
Vector<double> doubleResult = doubleVec + doubleVec;

if (intResult.data.size() > 0) {
std::cout << "Sum of integer vectors: ";
intResult.display();
}
if (doubleResult.data.size() > 0) {
std::cout << "Sum of double vectors: ";
doubleResult.display();
}

return 0;
}

You might also like