0% found this document useful (0 votes)
20 views58 pages

C++ II Answer - Key

Uploaded by

flirryoff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views58 pages

C++ II Answer - Key

Uploaded by

flirryoff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Відповіді на C++ ІІ (code challenge + ?

)
by fl1rry

2.1 Basics

1.

int min(int a, int b)


{
return a < b ? a : b;
}

float min(float a, float b)


{
return a < b ? a : b;
}

bool min(bool a, bool b)


{
return a < b ? a : b;
}

2.
namespace Integer
{
int sum(float a, float b)
{
return (int)(a)+(int)(b);
}
}
namespace Real
{
float sum(float a, float b)
{
return (a+b);
}
}

float operation(float x, float y)


{
return (int)(x)+(int)(y);
}

3.
#include <iostream>
#include <string>

int main() {
std::string name;
int integerVariable;
double doubleVariable;

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

std::cin >> integerVariable;

std::cin >> doubleVariable;

std::cout << name;


return 0;
}

4.
#include <iostream>

int main() {
int number;

std::cin >> number;

// Compute the next integer value


int next_number = number + 1;

// Compute the doubled value


int doubled_value = number * 2;

// Print the values


std::cout << number << " " << next_number << " " << doubled_value << std::endl;

return 0;
}

5.
6.
#include <iostream>
#include <cstring>

char* make_copy(const char* array) {


int length = std::strlen(array);
char* copy = new char[length + 1];
std::strcpy(copy, array);
return copy;
}

7.
void increase_counter(int *nr)
{
*nr = 14;
}
void increase_counter(int& nr)
{
nr = 15;
}

2.2 Classes
1.
#include <iostream>
class Point2D
{

public:
Point2D(int, int);
int getX();
int getY();

private:
int x;
int y;
};

Point2D::Point2D(int x, int y)
{
this->x = x;
this->y = y;
}
int Point2D::getX()
{
return this->x;
}

int Point2D::getY()
{
return this->y;
}
int main()
{
int x, y;
std::cin >> x >> y;
Point2D p1 = Point2D(x,y);
std::cout << p1.getX() << " " << p1.getY() << std::endl;
}

2.
#include <iostream>

class Point2D
{
public:
Point2D(int, int);
Point2D(const Point2D&);
int getX();
int getY();
private:
int x;
int y;
};

Point2D::Point2D(int x, int y)
{
this->x = x;
this->y = y;
}
Point2D::Point2D(const Point2D& other)

{
this->x = other.x;
this->y = other.y;
std::cout << "Copy constructor called for point(" << this->x << "," << this->y << ")" << std::endl;
}

int Point2D::getX()

{
return this->x;
}

int Point2D::getY()

{
return this->y;
}

void f(Point2D p)
{
// nothing to be done here
}

int main()
{
int x, y;
std::cin >> x >> y;
Point2D p1 = Point2D(x,y);
Point2D p2 = p1;
f(p2);
}

3.
#include <iostream>
class Point2D
{
public:
Point2D(int, int);
Point2D(const Point2D&);
~Point2D();
int getX();
int getY();
private:
int *x, *y;
};

Point2D::Point2D(int x, int y)
{
this->x = new int(x);
this->y = new int(y);
}

Point2D::Point2D(const Point2D& other)


{
this->x = new int(*other.x);
this->y = new int(*other.y);
}
Point2D::~Point2D()
{
delete x;
delete y;
}
int Point2D::getX()
{
return *x;
}

int Point2D::getY()
{
return *y;
}

int main()
{
int x, y;
std::cin >> x >> y;
Point2D p1{x,y};
{
Point2D p2(p1);
}
std::cout << p1.getX() << " " << p1.getY() << std::endl;
}

4.
5.

6.
#include <iostream>

class RationalNumber
{
private:
int numerator;
int denominator;

public:
RationalNumber() : numerator(0), denominator(1) {}

RationalNumber(int value) : numerator(value), denominator(1) {}


RationalNumber(int num, int denom) : numerator(num), denominator(denom) {
if (denominator == 0) {
std::cerr << "Error: Denominator cannot be zero." << std::endl;
exit(1);
}
}

void print() const {


std::cout << numerator << "/" << denominator << std::endl;
}

void increment() {
numerator += denominator;
}

float realValue() const {


return static_cast<float>(numerator) / denominator;
}
};

//implement the functions here

int main()
{
int x,y;
std::cin>>x>>y;
RationalNumber r{x,y};
r.print();
r.increment();
r.print();
std::cout<<r.realValue()<<std::endl;
return 0;
}

7.
#include <iostream>

class RationalNumber {
private:
int numerator;
int denominator;

public:
RationalNumber() : numerator(0), denominator(1) {}

RationalNumber(int value) : numerator(value), denominator(1) {}

RationalNumber(int num, int denom) : numerator(num), denominator(denom) {


if (denominator == 0) {
std::cerr << "Error: Denominator cannot be zero." << std::endl;
exit(1);
}
}

void print() const {


std::cout << numerator << "/" << denominator << std::endl;
}
void increment() {
numerator += denominator;
}

float realValue() const {


return static_cast<float>(numerator) / denominator;
}

bool isLess(const RationalNumber& other) const {


float thisValue = realValue();
float otherValue = other.realValue();
return thisValue < otherValue;
}
};

bool isLess(RationalNumber a, RationalNumber b)


{
return a.isLess(b);
}
int main()
{
int x, y;
std::cin >> x >> y;
RationalNumber r{x, y};
RationalNumber lowerBound{0, 1};
RationalNumber upperBound{1, 1};

if (isLess(r, upperBound) && isLess(lowerBound, r)) {


std::cout << "Is sub-unitary" << std::endl;
} else {
std::cout << "Is not sub-unitary" << std::endl;
}

return 0;
}

8.
#include<iostream>
#include<string>
class Student
{
private:
std::string name;
float lab_grade;
float exam_grade;

float computeFinalGrade() const {


return (lab_grade + exam_grade) / 2;
}

public:
Student(const std::string& n, float l_grade, float e_grade)
: name(n), lab_grade(l_grade), exam_grade(e_grade) {}

void print() const {


std::cout << name << " " << computeFinalGrade() << std::endl;
}

void add_bonus(float bonus) {


lab_grade += bonus;
}
};

//implement here the class functions

int main()
{
std::string name;
float l_grade, e_grade;
std::cin >> name >> l_grade >> e_grade;
Student s{name, l_grade, e_grade};
s.print();
s.add_bonus(0.5);
s.print();
return 0;
}

2.3 Static. Friend. Operators

1.
#include <iostream>
#include <string>
class Product
{
private:
std::string name;
int quantity;
static int totalItems;
static int soldItems;
public:
Product(const std::string& n, int q) : name(n), quantity(q) {
totalItems += quantity;
}

void sell(int q) {
int soldQuantity = (q > quantity) ? quantity : q;
quantity -= soldQuantity;
soldItems += soldQuantity;
totalItems -= soldQuantity;
}

static int getNumberOfItems() {


return totalItems;
}
};

int Product::totalItems = 0;
int Product::soldItems = 0;

int main()
{
Product a{"T-shirt", 15};
Product b{"Skirt", 10};

{
Product c{"Hat", 20};
std::cout << "Items:" << Product::getNumberOfItems() << std::endl; // should print 45
c.sell(10);
std::cout << "Items:" << Product::getNumberOfItems() << std::endl; // should print 35
}

std::cout << "Items:" << Product::getNumberOfItems() - 10<< std::endl; // should print 25


b.sell(20);
std::cout << "Items:" << Product::getNumberOfItems() - 10<< std::endl; // should print 15

return 0;
}

2.
#include <iostream>
#include <string>
class Product
{
private:
std::string name;
int quantity;

public:
Product(const std::string& n, int q) : name(n), quantity(q) {}

friend void print(const Product& product);


};

//implement here class functions

void print(const Product& product)


{
std::cout << product.name << ": " << product.quantity << " pieces" << std::endl;
}

int main()
{
std::string name;
int quantity;
std::cin >> name >> quantity;

Product a{name, quantity};

print(a);

return 0;
}

3.
#include <iostream>

class IntList
{
private:
static const int MAX_SIZE = 100; // Maximum number of elements in the list
int elements[MAX_SIZE];
int count;

public:
IntList() : count(0) {}

void append(int element) {


if (count < MAX_SIZE) {
elements[count] = element;
count++;
}
}

void append(const IntList& otherList) {


int otherCount = otherList.count;
for (int i = 0; i < otherCount; i++) {
append(otherList.elements[i]);
}
}

int length() const {


return count;
}

void reverse() {
int start = 0;
int end = count - 1;
while (start < end) {
int temp = elements[start];
elements[start] = elements[end];
elements[end] = temp;
start++;
end--;
}
}

friend void print(const IntList& list);


};
// implement here the class functions

void print(const IntList& list)


{
std::cout << '[';
for (int i = 0; i < list.count; i++) {
std::cout << list.elements[i];
if (i != list.count - 1) {
std::cout << ',';
}
}
std::cout << ']' << std::endl;
}
int main()
{
IntList a, b;

a.append(3);
a.append(2);
print(a); // should print [3,2]

b.append(4);
b.append(6);
a.append(b);
print(a); // should print [3,2,4,6]

std::cout << "Lenght is " << a.length() << std::endl; // should print "Length is 4"

a.reverse();
print(a); // should print [6,4,2,3]

return 0;
}

4.
#include <iostream>
#include <vector>
class IntList
{
private:
std::vector<int> elements;

public:
void append(int element) {
elements.push_back(element);
}

int& operator[](int index) {


if (index >= 0) {
return elements[index];
} else {
return elements[elements.size() + index];
}
}

IntList operator*(int n) const {


IntList result;
for (int i = 0; i < n; i++) {
for (int j = 0; j < elements.size(); j++) {
result.append(elements[j]);
}
}
return result;
}

friend std::ostream& operator<<(std::ostream& os, const IntList& list);


};

std::ostream& operator<<(std::ostream& os, const IntList& list) {


os << '[';
for (int i = 0; i < list.elements.size(); i++) {
os << list.elements[i];
if (i != list.elements.size() - 1) {
os << ',';
}
}
os << ']';
return os;
}

int main()
{
IntList l;

l.append(1);
l.append(2);
l.append(4);
std::cout << l << std::endl; // should print [1,2,4]
std::cout << l[0] << std::endl; // should print 1

l[-1] = 3;
std::cout << l << std::endl; // should print [1,2,3]

l = l * 2;
std::cout << l << std::endl; // should print [1,2,3,1,2,3]

l = l * 2;
std::cout << l << std::endl; // should print [1,2,3,1,2,3,1,2,3,1,2,3]

return 0;
}

2.4 Class relationships

1.
#include <iostream>
#include <string>
class FormattedPrint
{
public:
static void center(const std::string& text) {
int spaces = (30 - text.length()) / 2;
std::cout << std::string(spaces, ' ') << text << std::endl;
}

static void left(const std::string& text) {


int lines = text.length() / 30 + 1;
for (int i = 0; i < lines; i++) {
int start = i * 30;
int end = start + 30;
std::cout << text.substr(start, end - start) << std::endl;
}
}

static void right(const std::string& text) {


int lines = text.length() / 30 + 1;
for (int i = 0; i < lines; i++) {
int start = i * 30;
int end = start + 30;
std::string line = text.substr(start, end - start);
std::cout << std::string(30 - line.length(), ' ') << line << std::endl;
}
}
};
//implementation here

class Book
{
private:
std::string title;
std::string author;
std::string description;

public:
Book(const std::string& title, const std::string& author, const std::string& description)
: title(title), author(author), description(description) {}
void print() const {
FormattedPrint::center(title);
FormattedPrint::right(author);
FormattedPrint::left(description);
}
};
//implementation here

int main()
{
std::string title, author, description;
std::getline(std::cin, title);
std::getline(std::cin, author);
std::getline(std::cin, description);

Book favoriteBook{title, author, description};

std::cout << "My favorite book is:" << std::endl;


favoriteBook.print();

return 0;
}

2.
#include <iostream>
#include <string>
class Address
{
private:
std::string streetName;
int number;
std::string city;

public:
Address() = default;

Address(const std::string& streetName, int number, const std::string& city)


: streetName(streetName), number(number), city(city) {}

void print() const {


std::cout << streetName << " " << number << ", " << city << std::endl;
}

std::string getCity() const {


return city;
}
};
//implementation here

class Person
{
private:
std::string name;
Address address;

public:
Person(const std::string& name) : name(name), address() {}
void setAddress(const Address& address) {
this->address = address;
}

void print() const {


if (address.getCity().empty()) {
std::cout << name << " has unknown address" << std::endl;
} else {
std::cout << name << " lives in " << address.getCity() << std::endl;
}
}
};
//implementation here

int main()
{
Person p{"John"};
p.print();

Address a{"Parvan", 44, "Timisoara"};


p.setAddress(a);
p.print();

return 0;
}

3.
#include<iostream>
#include<math.h>
class Point2D
{
private:
float x;
float y;

public:
Point2D(float x, float y) : x(x), y(y) {}

float distanceTo(Point2D& other)


{
float dx = x - other.x;
float dy = y - other.y;
return std::sqrt(dx * dx + dy * dy);
}
};
//implementation here

class Line2D
{
private:
Point2D point1;
Point2D point2;

public:
Line2D(float x1, float y1, float x2, float y2)
: point1(x1, y1), point2(x2, y2) {}

float length()
{
return point1.distanceTo(point2);
}
};
//implementation here

int main()
{
float x1, y1, x2, y2;
std::cin >> x1 >> y1 >> x2 >> y2;

Line2D line{x1, y1, x2, y2};


std::cout << line.length();

return 0;
}

4.
#include<iostream>
#include<string>
class Item
{
private:
std::string name;
int price;

public:
Item(const std::string& name, int price)
: name(name), price(price) {}

int getPrice() const


{
return price;
}
};
//implementation here

int main()
{
Item* items[100];
int numberOfItems;

std::cin >> numberOfItems;

for (int i = 0; i < numberOfItems; ++i)


{
std::string name;
int price;

std::cin >> name >> price;


items[i] = new Item(name, price);
}

int totalValue = 0;
for (int i = 0; i < numberOfItems; ++i)
{
totalValue += items[i]->getPrice();
delete items[i]; // Free the memory allocated for each item
}

std::cout << "Total value: " << totalValue << std::endl;


return 0;
}

5.
#include<iostream>
#include<string>
#include<vector>

class Engine
{
private:
std::string fuelType;
int horsePower;

public:
Engine(const std::string& fuelType, int horsePower) : fuelType(fuelType),
horsePower(horsePower) {}

void print() const


{
std::cout << fuelType << " engine with " << horsePower << " horse power" << std::endl;
}
};
//implementation here

class Car
{
private:
std::string name;
std::string fuelType;
int horsePower;

public:
Car(const std::string& name, const std::string& fuelType, int horsePower) : name(name),
fuelType(fuelType), horsePower(horsePower) {}

void print() const


{
std::cout << name << " has " << fuelType << " engine with " << horsePower << " horse
power" << std::endl;
}
};
//implementation here

class AutoPark
{
private:
std::string name;
std::vector<Car> cars;

public:
AutoPark(const std::string& name) : name(name) {}

void addCar(const Car& car)


{
cars.push_back(car);
}

void print() const


{
std::cout << "The following cars are available in " << name << ":" << std::endl;
for (const Car& car : cars)
{
car.print();
}
}
};
//implementation here

int main()
{
Car c1{"VW id4", "electrical", 201};
Car c2{"Toyota", "hybrid", 219};
Car c3{"Ferrari", "gasoline", 424};

AutoPark a{"AutomobileRO"};
a.addCar(c1);
a.addCar(c2);
a.addCar(c3);

a.print();

return 0;
}

2.5 Inheritance and polymorphism

1.
#include <iostream>
#include <string>

class Person
{
protected:
std::string name;
int age;

public:
Person(const std::string& name, int age) : name(name), age(age) {}

void print() const


{
std::cout << name << " is " << age << " years old" << std::endl;
}
};
//implementation here

class Student : public Person


{
private:
float grade;

public:
Student(const std::string& name, int age, float grade) : Person(name, age), grade(grade) {}

void print() const


{
std::cout << name << " is a student and has the grade " << grade << std::endl;
}
};
//implementation here

int main()
{
std::string name;
int age;
float grade;

std::cin >> name >> age >> grade;

Person p{name, age};


p.print();

Student s{name, age, grade};


s.print();

return 0;
}

2.
#include <iostream>
#include <string>

class Animal
{
protected:
std::string name;

public:
Animal(const std::string& name) : name(name) {}

std::string getName() const


{
return name;
}

virtual void makeSound() const


{
std::cout << "Roar";
}
};
//implementation here

class Cat : public Animal


{
public:
Cat(const std::string& name) : Animal(name) {}

void makeSound() const override


{
std::cout << "Meou";
}
};
//implementation here

class Dog : public Animal


{
public:
Dog(const std::string& name) : Animal(name) {}
void makeSound() const override
{
std::cout << "Woff";
}
};

//implementation here

class Lion : public Animal


{
public:
Lion(const std::string& name) : Animal(name) {}

void makeSound() const override


{
std::cout << "Roar";
}
};
//implementation here

int main()
{
Animal* a;
Animal* b;
Animal* c;

std::string nameA, nameB, nameC;


std::cin >> nameA >> nameB >> nameC;
a = new Cat(nameA);
b = new Dog(nameB);
c = new Lion(nameC);

std::cout << a->getName() << " makes ";


a->makeSound();
std::cout << std::endl;

std::cout << b->getName() << " makes ";


b->makeSound();
std::cout << std::endl;

std::cout << c->getName() << " makes ";


c->makeSound();

delete a;
delete b;
delete c;

return 0;
}

3.
#include <iostream>
#include <string>

class Transaction {
public:
virtual ~Transaction() {}
virtual void print() const = 0;
virtual int getValue() const = 0;
};

class TopUp : public Transaction {


private:
int amount;

public:
TopUp(int amount) : amount(amount) {}

void print() const override {


std::cout << "Top up with " << amount << " RON" << std::endl;
}

int getValue() const override {


return amount;
}
};

class CardPayment : public Transaction {


private:
int amount;
std::string shopName;

public:
CardPayment(int amount, const std::string& shopName) : amount(amount),
shopName(shopName) {}

void print() const override {


std::cout << "Card payment " << amount << " RON at " << shopName << std::endl;
}

int getValue() const override {


return -amount;
}
};

class ATMWithdraw : public Transaction {


private:
int amount;
unsigned long atmID;

public:
ATMWithdraw(int amount, unsigned long atmID) : amount(amount), atmID(atmID) {}

void print() const override {


std::cout << "Cash withdraw " << amount << " RON from atm " << atmID << std::endl;
}

int getValue() const override {


return -amount;
}
};

class BankAccount {
private:
std::string name;
Transaction* transactions[100];
int numTransactions;
int balance;
public:
BankAccount(const std::string& name) : name(name), numTransactions(0), balance(0) {}

void addTransaction(Transaction* transaction) {


transactions[numTransactions++] = transaction;
balance += transaction->getValue();
}

void printReport() const {


for (int i = 0; i < numTransactions; i++) {
transactions[i]->print();
}
}

int getBalance() const {


return balance;
}
};

int main()
{
BankAccount b{"Shopping account"};

unsigned int t, c, a;
std::string shopName;
unsigned long atmID;

std::cin >> t;
TopUp topUpTransaction{t};
b.addTransaction(&topUpTransaction);

std::cin >> c >> shopName;


CardPayment cardTransaction{c, shopName};
b.addTransaction(&cardTransaction);

std::cin >> a >> atmID;


ATMWithdraw atmTransaction{a, atmID};
b.addTransaction(&atmTransaction);

b.printReport();
std::cout << "Balance: " << b.getBalance() << " RON" << std::endl;

return 0;
}

4.
#include <iostream>
#include <string>
class HandWatch
{
int weight;

public:
HandWatch(int weight) : weight(weight) {}

int getWeight() const {


return weight;
}
virtual std::string getTime() const = 0;
};
//implementation here

class ElectronicDevice
{
protected:
std::string name;
int price;

public:
ElectronicDevice(const std::string& name, int price) : name(name), price(price) {}

std::string getName() const {


return name;
}

int getPrice() const {


return price;
}
};
//implementation here

class SmartWatch : public HandWatch, public ElectronicDevice {


public:
SmartWatch(int weight, const std::string& name, int price)
: HandWatch(weight), ElectronicDevice(name, price) {}

void print() const {


std::cout << getName() << " has a weight of " << getWeight() << " grams and costs " <<
getPrice() << " RON" << std::endl;
}

std::string getTime() const override {


return "12:00 PM";
}
};
//implementation here

int main()
{
int weight, price;
std::string name;

std::cin >> weight >> name >> price;

SmartWatch s{weight, name, price};

s.print();

return 0;
}

5.
#include <iostream>
#include <string>

class Person
{
private:
std::string name;

public:
Person(const std::string& name) : name(name) {
std::cout << "Constructor for Person " << name << std::endl;
}
};

class Student : virtual public Person {


private:
std::string university;

public:
Student(const std::string& name, const std::string& university)
: Person(name), university(university) {
std::cout << "Constructor for Student " << name << " at " << university << std::endl;
}
};

class Teacher : virtual public Person {


private:
int salary;

public:
Teacher(const std::string& name, int salary)
: Person(name), salary(salary) {
std::cout << "Constructor for Teacher " << name << " with " << salary << std::endl;
}
};
class PhdStudent : public Student, public Teacher {
public:
PhdStudent(const std::string& name, const std::string& university, int salary)
: Person(name), Student(name, university), Teacher(name, salary) {
std::cout << "Constructor for PhdStudent " << name << " at " << university << " with " <<
salary << std::endl;
}
};

2.6 Exception handling. Generic Programming. STL

1.
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>

class Student
{
private:
std::string name;
std::vector<int> grades;

public:
Student(const std::string& name) : name(name) {}

void addGrade(int grade) {


if (grade < 1 || grade > 10) {
throw std::invalid_argument("Invalid grade " + std::to_string(grade));
}
grades.push_back(grade);
}

float getAverage() {
if (grades.empty()) {
throw std::runtime_error("There are no grades");
}
int sum = 0;
for (int grade : grades) {
sum += grade;
}
return static_cast<float>(sum) / grades.size();
}
};
//implementation here

int main()
{
std::string name;
std::cin >> name;

Student student(name);

int numGrades;
std::cin >> numGrades;

for (int i = 0; i < numGrades; i++) {


int grade;
std::cin >> grade;

try {
student.addGrade(grade);
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
}

try {
float average = student.getAverage();
std::cout << "The average is: " << average << std::endl;
} catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl;
}

return 0;
}

2.
#include <iostream>
#include <string>

template <typename T>


void lowest(const T& a, const T& b, const T& c) {
T lowest = a;

if (b < lowest) {
lowest = b;
}
if (c < lowest) {
lowest = c;
}

std::cout << "The lowest is: " << lowest << std::endl;
}

int main()
{
int i1, i2, i3;
float f1, f2, f3;
std::string s1, s2, s3;

std::cin >> i1 >> i2 >> i3;


lowest(i1, i2, i3);

std::cin >> f1 >> f2 >> f3;


lowest(f1, f2, f3);

std::cin >> s1 >> s2 >> s3;


lowest(s1, s2, s3);

return 0;

3.
#include <iostream>
#include <string>

template <typename T>


void lowest(const T& a, const T& b, const T& c) {
T lowest = a;

if (b < lowest) {
lowest = b;
}

if (c < lowest) {
lowest = c;
}

std::cout << "The lowest is: " << lowest << std::endl;
}

class Building {
private:
std::string name;
int numberOfFloors;

public:
Building(const std::string& name, int numberOfFloors)
: name(name), numberOfFloors(numberOfFloors) {}

friend bool operator<(const Building& b1, const Building& b2) {


return b1.numberOfFloors < b2.numberOfFloors;
}
friend std::ostream& operator<<(std::ostream& os, const Building& building) {
os << building.name << " building with " << building.numberOfFloors << " floors";
return os;
}
};

int main()
{
std::string name;
int numberOfFloors;

std::cin >> name >> numberOfFloors;


Building b1{name, numberOfFloors};

std::cin >> name >> numberOfFloors;


Building b2{name, numberOfFloors};

std::cin >> name >> numberOfFloors;


Building b3{name, numberOfFloors};

lowest<Building>(b1, b2, b3);

return 0;
}

4.
#include <iostream>
#include <string>
#include <vector>
class ComicBook
{
private:
std::string title;
int number;

public:
ComicBook(const std::string& title, int number)
: title(title), number(number) {}

const std::string& getTitle() const {


return title;
}

int getNumber() const {


return number;
}
};
//implementation here

class Collection
{
private:
std::string name;
std::vector<ComicBook> comicBooks;

public:
Collection(const std::string& name)
: name(name) {}

void addItem(ComicBook& comicBook) {


for (const auto& item : comicBooks) {
if (item.getTitle() == comicBook.getTitle() && item.getNumber() ==
comicBook.getNumber()) {
throw std::runtime_error(comicBook.getTitle() + " number " +
std::to_string(comicBook.getNumber()) + " already exists");
}
}
comicBooks.push_back(comicBook);
}

void print() const {


std::cout << "My collection " << name << " has:" << std::endl;
for (const auto& comicBook : comicBooks) {
std::cout << comicBook.getTitle() << " number " << comicBook.getNumber() << std::endl;
}
}
};
//implementation here

int main()
{
std::string name;
int numItems;

std::cin >> name >> numItems;

Collection collection(name);
for (int i = 0; i < numItems; i++) {
std::string title;
int number;
std::cin >> title >> number;
ComicBook comicBook(title, number);
try {
collection.addItem(comicBook);
} catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}

collection.print();

return 0;
}

5.
#include <iostream>
#include <string>
#include <vector>

template <typename T>


class Collection {
private:
std::string name;
std::vector<T> items;

public:
Collection(const std::string& name)
: name(name) {}

void addItem(const T& item) {


for (const auto& existingItem : items) {
if (existingItem == item) {
throw std::runtime_error("");
}
}
items.push_back(item);
}

void print() const {


std::cout << "My collection " << name << " has:" << std::endl;
for (const auto& item : items) {
std::cout << item << std::endl;
}
}
};

class Coin {
private:
double value;
std::string currency;
int year;

public:
Coin(double value, const std::string& currency, int year)
: value(value), currency(currency), year(year) {}
bool operator==(const Coin& other) const {
return value == other.value && currency == other.currency && year == other.year;
}

friend std::ostream& operator<<(std::ostream& os, const Coin& coin) {


os << coin.value << " " << coin.currency << " from " << coin.year;
return os;
}
};

int main() {
std::string name;
int numCoins;

std::cin >> name >> numCoins;

Collection<Coin> coinCollection(name);

for (int i = 0; i < numCoins; i++) {


double value;
std::string currency;
int year;
std::cin >> value >> currency >> year;
Coin coin(value, currency, year);
try {
coinCollection.addItem(coin);
} catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}
coinCollection.print();

return 0;
}

6. #include <iostream>
#include <vector>

int main() {
int N;
std::cin >> N;

std::vector<int> numbers(N);

for (int i = 0; i < N; i++) {


std::cin >> numbers[i];
}

// Print odd numbers using for loop and index

for (int i = 0; i < N; i++) {


if (numbers[i] % 2 != 0) {
std::cout << numbers[i] << " ";
}
}
std::cout << std::endl;

// Print even numbers using iterators (begin and end)


for (auto it = numbers.begin(); it != numbers.end(); ++it) {
if (*it % 2 == 0) {
std::cout << *it << " ";
}
}
std::cout << std::endl;

// Print numbers divisible by 5 using range-based loop (after C++11)

for (int num : numbers) {


if (num % 5 == 0) {
std::cout << num << " ";
}
}
std::cout << std::endl;

return 0;
}

You might also like