From 48af70474b726b82cf3bbdd1f6148c74174adb23 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:08:51 +0400 Subject: [PATCH 01/38] 1: homework 01 - library management system --- .../homework-01-library-management-system.cpp | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp index 4a06271..6fb2469 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp @@ -1,44 +1,51 @@ #include #include - using namespace std; - /* Exercise: Library Management System - Description: Design and implement a Library Management System using classes and access specifiers in C++. The system should allow you to manage books in a library. - Requirements: - 1. Create a class named "Book" with the following attributes: Title (a string) Author (a string) Publication Year (an integer) ISBN (a string) - 2. Make the attributes private to encapsulate them. - 3. Include member functions to: Set the book details (title, author, publication year, ISBN). Display the book details. 4. Create objects of the "Book" class and demonstrate accessing and modifying the attributes using member functions. - Tips: Use access specifiers (public and private) to control access to class members. You can choose to implement the member functions directly in the class declaration (inline) or define them outside the class. Test the functionality of the class by creating book objects, setting their details, and displaying the information. This exercise will help you practice using access specifiers to control the visibility of class members and understand the concept of encapsulation. */ - - - /* Solution */ - - - +class Book{ + private: + string Title; + string Author; + int PublicYear; + string ISBN; + public: + void setBookDetails(string bookname ,string author , int year , string isbn){ + Title = bookname; + Author = author; + PublicYear = year; + ISBN = isbn; + } + void displayBookDetails(){ + cout << Title < Date: Wed, 9 Sep 2026 14:09:19 +0400 Subject: [PATCH 02/38] Update homework-01-library-management-system.cpp --- .../homework/homework-01-library-management-system.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp index 6fb2469..2ec108f 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-01-library-management-system.cpp @@ -7,7 +7,7 @@ using namespace std; Design and implement a Library Management System using classes and access specifiers in C++. The system should allow you to manage books in a library. Requirements: - 1. Create a class named "Book" with the following attributes: + 1. Create a class named "Book" with the following attributes: Title (a string) Author (a string) Publication Year (an integer) From a6faf0f9545002c4ac8b567e483001586fc662cf Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:21:29 +0400 Subject: [PATCH 03/38] Update homework-02-employee-management-system.cpp --- ...homework-02-employee-management-system.cpp | 77 ++++++++----------- 1 file changed, 31 insertions(+), 46 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-02-employee-management-system.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-02-employee-management-system.cpp index 5899341..4efbb7c 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-02-employee-management-system.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-02-employee-management-system.cpp @@ -1,51 +1,36 @@ #include #include - using namespace std; - -/* - Exercise: Employee Management System - - Description: - Design and implement an Employee Management System using classes and constructors in C++. - The system should allow you to create and manage employee records. - - Requirements: - - 1. Create a class named "Employee" with the following attributes: - Employee ID (an integer) - Employee name (a string) - Employee designation (a string) - Employee salary (a floating-point number) - - 2. Implement the following constructors for the "Employee" class: - A parameterized constructor that initializes all the attributes based on provided values. - A default constructor that sets default values for the attributes. - - 3. Include member functions to: - Set and get the employee attributes (ID, name, designation, salary). - Display the employee details. - - 4. Create multiple employee objects using different constructors and display their details. - - Tips: - Use appropriate access specifiers (such as private and public) for the class members. - Consider using default values in the parameterized constructor to provide flexibility when creating objects. - Test the functionality of constructors by creating objects with and without providing initial values. - This exercise will help you practice creating and initializing objects using constructors and defaulted constructors, as well as accessing and displaying object attributes. -*/ - - - -/* Solution */ - - - -int main() { - - /* Example usage: */ - - // Creating employee objects using different constructors +class Employee{ + private: + int ID; + string name; + string designation; + double salary; + public: + Employee(int pID = 0 , string Pname = "Unknown" , string Pdesignation = "unknown" , double Psalary = 0.0){ + ID = pID; + name = Pname; + designation = Pdesignation; + salary = Psalary; + } + + void setID(int pID){ID = pID;} + void setName(string Pname){name = Pname;} + void setDesignation(string Pdesignation){designation = Pdesignation;} + void setSalary(double Psalary){salary = Psalary;} + + void displayDetails(){ + cout << ID << endl; + cout << name << endl; + cout << designation << endl; + cout << salary << endl; + + } + +}; +int main(){ + system("cls"); Employee emp1(101, "John Doe", "Manager", 5000.0); Employee emp2; @@ -64,4 +49,4 @@ int main() { cout << endl; return 0; -} \ No newline at end of file +} From 0268d9c73e31f2c15149542619003474352af175 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:22:19 +0400 Subject: [PATCH 04/38] Update homework-03-bank-account-encapsulation.cpp --- ...homework-03-bank-account-encapsulation.cpp | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-03-bank-account-encapsulation.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-03-bank-account-encapsulation.cpp index b6f503a..cabc95b 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-03-bank-account-encapsulation.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-03-bank-account-encapsulation.cpp @@ -29,6 +29,23 @@ class BankAccount { // Constructor BankAccount(int accountNumber, const string &holderName, double initialBalance) { // TODO: Initialize member variables + this -> accountNumber = accountNumber; + this -> holderName = holderName; + balance = initialBalance; + } + void deposit(double amount){ + balance = balance + amount; + } + void withdraw(double amount){ + if(amount < balance){ + balance = balance - amount; + } + else{ + cout << "Invalid" << endl; + } + } + double CheckBalance(){ + return balance; } // Member functions @@ -38,6 +55,7 @@ class BankAccount { int main() { + system("cls"); // TODO: Create an instance of the BankAccount class // TODO: Test the deposit, withdraw, and check balance operations @@ -55,7 +73,15 @@ int main() { This exercise will help you practice encapsulation and understand how to hide implementation details while exposing a controlled interface to the users of your class! */ + BankAccount acc1(12, "Shamkhal", 890.8); + BankAccount acc2(15, "Ali", 500.0); + + acc1.deposit(32.1); + acc1.withdraw(44.3); + cout << "Shamkhal balance: " << acc1.CheckBalance() << endl; - return 0; + acc2.deposit(100.0); + acc2.withdraw(50.0); + cout << "Ali balance: " << acc2.CheckBalance() << endl; } From db44394b34716211744972a6c20ce5454f48eb0d Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:23:03 +0400 Subject: [PATCH 05/38] Update homework-04-employee-setters-and-getters.cpp --- ...mework-04-employee-setters-and-getters.cpp | 75 ++++++++----------- 1 file changed, 32 insertions(+), 43 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-04-employee-setters-and-getters.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-04-employee-setters-and-getters.cpp index 8e4975f..13a9a2f 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-04-employee-setters-and-getters.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-04-employee-setters-and-getters.cpp @@ -1,41 +1,7 @@ #include #include - using namespace std; - -/* - Exercise: Employee Management System - - You are tasked with creating an employee management system for a company. - Each employee has a name, age, position, and salary. - Your goal is to implement a class called Employee that encapsulates - these attributes and provides appropriate setters and getters. - - Your task is to create a C++ class called Employee with the following specifications: - - 1. Private member variables: - name (string): Holds the name of the employee. - age (int): Holds the age of the employee. - position (string): Holds the position/title of the employee. - salary (double): Holds the salary of the employee. - - 2. Public member functions: - setName(const string& name): Sets the name of the employee. - setAge(int age): Sets the age of the employee. - setPosition(const string& position): Sets the position of the employee. - setSalary(double salary): Sets the salary of the employee. - getName() const: Returns the name of the employee. - getAge() const: Returns the age of the employee. - getPosition() const: Returns the position of the employee. - getSalary() const: Returns the salary of the employee. - - Your implementation should allow external code to set and get the attributes of - an Employee object using the appropriate setter and getter functions. - - Here's a code template to get you started: -*/ - -class Employee { +class Employee{ private: string name; int age; @@ -43,15 +9,38 @@ class Employee { double salary; public: - // TODO: Implement setters and getters - + void setName(const string& name){this -> name = name;} + void setAge(int age){this -> age = age;} + void setPosition(const string& position){this -> position = position;} + void setSalary(double salary){this -> salary = salary;} + + string getName()const{return name;} + int getAge()const{return age;} + string getPosition() const{return position;} + double getSalary() const{return salary;} }; +int main(){ + system("cls"); + Employee employee; + employee.setName("Shamkhal"); + employee.setAge(18); + employee.setPosition("data scientist"); + employee.setSalary(0); + cout << "about of employee" << endl; + cout << employee.getName() << endl; + cout << employee.getAge() << endl; + cout << employee.getPosition() < Date: Wed, 9 Sep 2026 14:23:41 +0400 Subject: [PATCH 06/38] Update homework-05-online-shop-system.cpp --- .../homework-05-online-shop-system.cpp | 105 +++++++++--------- 1 file changed, 55 insertions(+), 50 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-05-online-shop-system.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-05-online-shop-system.cpp index 1f024fd..421d6b0 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-05-online-shop-system.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-05-online-shop-system.cpp @@ -1,60 +1,65 @@ #include - +#include +#include using namespace std; - -/* - Exercise: Online Shop System - - Description: - Design and implement an Online Shop System using multiple files and classes in C++. - The system should allow you to manage products and orders in an online shop. - - Requirements: - - 1. Create two classes: "Product" and "Order". - - 2. The "Product" class should have the following attributes: - Product ID (an integer) - Product name (a string) - Product price (a floating-point number) - - 3. The "Order" class should have the following attributes: - Order ID (an integer) - Customer name (a string) - Ordered products (an array/vector of Product objects) - (Vectors: https://www.geeksforgeeks.org/vector-in-cpp-stl/) - - 4. Define the "Product" class in a separate header file called "Product.h" - and implement its member functions. - - 5. Define the "Order" class in a separate header file called "Order.h" - and implement its member functions - - 6. Include the necessary header files in the main program file. - - 7. Demonstrate the functionality of the Online Shop System by creating products, - creating orders, and performing operations like adding products to orders, calculating order totals, etc. - - Tips: - - Use header files to declare the class structure and member function prototypes. - Use include guards or pragma once to prevent multiple inclusion of header files. - - This exercise will help you practice creating separate classes in different files - and including them in a main program file to build a functional Online Shop System! -*/ - - -/* - Solution -*/ +class Product{ + private: + int ProductId; + string ProductName; + double ProductPrice; + public: + Product(int ProductId = 0 , string ProductName = "0" , double ProductPrice = 0){ + this -> ProductId = ProductId; + this -> ProductName = ProductName; + this -> ProductPrice = ProductPrice; + } + int getId() const { + return ProductId; + } + string getProductName()const{ + return ProductName; + } + double getProductPrice()const{ + return ProductPrice; + } +}; +class Order{ + private: + int OrderId; + string CustomerName; + vector products; + public: + Order(int OrderId = 0 , string CustomerName = "0"){ + this -> OrderId = OrderId; + this -> CustomerName = CustomerName; + } + void addProduct(Product product){ + products.push_back(product); + } + double calculateOrderTotal(){ + double total = 0; + for(int i = 0; i < products.size(); i++){ + total = total + products[i].getProductPrice(); + } + return total; + } + int getOrderID(){ + return OrderId; + } + string getCustomerName(){ + return CustomerName; + } + vector getOrderedProducts(){ + return products; + } +}; int main() { - system("clear"); + system("cls"); // Create products Product p1(1, "Product 1", 10.0); @@ -84,4 +89,4 @@ int main() { cout << "Total: $" << total << endl; return 0; -} \ No newline at end of file +} From bc0cd8b6991162e64e7a8119228af4fc375f20e4 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:25:31 +0400 Subject: [PATCH 07/38] Update homework-06-library-oop-principles.cpp --- .../homework-06-library-oop-principles.cpp | 85 ++++++++----------- 1 file changed, 34 insertions(+), 51 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-06-library-oop-principles.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-06-library-oop-principles.cpp index 2738acb..30560e9 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-06-library-oop-principles.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-06-library-oop-principles.cpp @@ -1,62 +1,45 @@ - #include - using namespace std; +class Book{ + private: + string title; + string author; + int year; + public: + Book(string title = "Unknown" , string author = "Unknown" , int year = 0){ + this -> title = title; + this -> author = author; + this -> year = year; + } + void Display(){ + cout << title << endl; + cout << author << endl; + cout << year << endl; + } -/* - Exercise: - Create a program to manage a library with books using Object-Oriented Programming (OOP) principles in C++. - Implement the following features: - - 1. Define a class named Book with the following private attributes: - title (string): to store the title of the book. - author (string): to store the author of the book. - year (int): to store the year of publication of the book. - - 2. Implement a default constructor for the Book class that initializes all attributes to empty or zero. - - 3. Implement a parameterized constructor for the Book class that allows setting the values for title, - author, and year during object creation. - - 4. Implement a member function named display() inside the Book class that displays the details of the book (title, author, and year). - - 5. In the main() function, create an array named library of Book objects with a size of 5. - - 6. Prompt the user to enter the details of the books (title, author, and year) - and populate the library array accordingly using the parameterized constructor. - - 7. Display the details of all the books in the library using the display() method. - - 8. Compile and run the program to test its functionality. - - Your task is to implement the missing parts and ensure that the program runs correctly, - allowing the user to input the details of the books and displaying them. - - Hint: You can use a loop (e.g., for or while) to prompt the user for input and populate the library array. -*/ - - -/* Solution */ - -class Book { - // TODO: }; - int main() { - const int librarySize = 5; Book library[librarySize]; - - cout << "Enter details for " << librarySize << " books:" << endl; - for (int i = 0; i < librarySize; ++i) { - // TODO: + for(int i = 0 ; i < librarySize ; i++){ + string title1 , author1; + int year1; + cout << i + 1 << "ci kitabin adi: "; + getline(cin , title1); + cout << i + 1 << "ci kitabin muellifi: "; + getline(cin,author1); + cout << i+1 << "ci kitabin nesr olundugu il: "; + cin >> year1; + cin.ignore(); + library[i] = Book(title1 , author1 ,year1); } - - cout << endl << "Library Contents:" << endl; - for (int i = 0; i < librarySize; ++i) { - cout << "Book " << i + 1 << ":" << endl; - // TODO: + for(int i = 0 ; i < librarySize ; i++){ + cout << i + 1 << "ci kitab haqqinda melumat: " << endl; + library[i].Display(); } -} \ No newline at end of file + + + +} From 54543171dd29aa1d4fe5a887d742d3f60174b799 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:26:26 +0400 Subject: [PATCH 08/38] Update homework-07-bank-account-basics.cpp --- .../homework-07-bank-account-basics.cpp | 78 ++++++++----------- 1 file changed, 32 insertions(+), 46 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-07-bank-account-basics.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-07-bank-account-basics.cpp index d8aa3b2..e9e3f32 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-07-bank-account-basics.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-07-bank-account-basics.cpp @@ -1,58 +1,44 @@ #include - using namespace std; - -/* - Exercise: - Imagine you are developing a simple banking application in C++. - You have a class called BankAccount that represents a user's bank account. - - The BankAccount class has the following attributes: - accountNumber (integer) - represents the account number - balance (double) - represents the account balance - - The BankAccount class also has the following methods: - deposit(amount) - deposits the specified amount into the account - withdraw(amount) - withdraws the specified amount from the account - getBalance() - returns the current account balance - - In addition to the above functionality, you need to ensure that when a BankAccount object is destroyed, - it writes a log message indicating that the account is closed. - - Your task is to implement the BankAccount class with appropriate constructors, methods, and a destructor. - Demonstrate the need for a destructor by creating multiple BankAccount objects, manipulating them, - and observing the log messages when the objects are destroyed. - - Hint: - To keep things simple, you can use a static variable to keep track of the number of BankAccount objects created, - and increment it in the constructor. - In the destructor, decrement the count and check if it reaches zero. - If so, write the log message. -*/ - - -/* - Solution -*/ class BankAccount { -} - + private: + int accountNumber; + double balance; + static int totalAccount; + public: + BankAccount(int accountNumber , int balance = 0.0){ + this -> accountNumber = accountNumber; + this -> balance = balance; + ++totalAccount; + } + void deposit(double amount){ + balance = balance + amount; + } + void withdraw(double amount){ + if(amount > 0 && amount <= balance){ + balance = balance - amount; + } + else{ + cout << "Invalid Balance " < Date: Wed, 9 Sep 2026 14:42:54 +0400 Subject: [PATCH 09/38] Update homework-08-bank-and-account-classes.cpp --- .../homework-08-bank-and-account-classes.cpp | 111 ++++++++++-------- 1 file changed, 59 insertions(+), 52 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-08-bank-and-account-classes.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-08-bank-and-account-classes.cpp index f3dfae4..30a6108 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-08-bank-and-account-classes.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-08-bank-and-account-classes.cpp @@ -1,64 +1,71 @@ #include #include - using namespace std; - - -/* - Exercise: - Create a program that simulates a simple bank account system. - The program should have two classes: BankAccount and Bank. - - 1. BankAccount class should have the following private members: - int accountNumber: An integer representing the account number. - double balance: A double representing the current balance. - It should also have the following public member functions: - BankAccount(int accNumber): A constructor that takes an account number as a parameter and initializes the balance to 0. - void deposit(double amount): A function that takes an amount and adds it to the account's balance. - void withdraw(double amount): A function that takes an amount and subtracts it from the account's balance. - void displayBalance(): A function that displays the current balance of the account. - - 2. Bank class should have the following private members: - BankAccount* accounts: A pointer to an array of BankAccount objects. - int numAccounts: An integer representing the number of accounts in the bank. - It should also have the following public member functions: - Bank(int num): A constructor that takes the number of accounts as a parameter and dynamically allocates memory for the accounts. - ~Bank(): A destructor that frees the dynamically allocated memory for the accounts. - void performTransactions(): A function that performs some transactions (e.g., deposits and withdrawals) on the bank accounts. - void displayAllBalances(): A function that displays the balances of all the bank accounts. - - Instructions: - - 1. Implement the member functions of the BankAccount class. - 2. Implement the constructor and destructor of the Bank class. - 3. Implement the performTransactions function in the Bank class, - which simulates some transactions(ex: accounts[0]->deposit(1000) - accounts[1]->deposit(500) - accounts[2]->deposit(200) - accounts[2]->withdraw(50)) on the bank accounts. - 4. In the main function, create an instance of the Bank class with a specific number of accounts. - 5. Call the performTransactions function on the Bank object to simulate transactions. - 6. Finally, call the displayAllBalances function to display the balances of all bank accounts. - 7. Make sure to deallocate any dynamically allocated memory in the appropriate locations. - - This exercise demonstrates the need for destructors because the Bank class dynamically allocates memory - for the BankAccount objects. Without a destructor, this memory would not be freed, leading to memory leaks. -*/ - - -/* - Solution -*/ - - +class BankAccount{ + private: + int AccountNumber; + int balance; + public: + BankAccount(int AccountNumber = 0, int balance = 0){ + this -> AccountNumber = AccountNumber; + this -> balance = balance; + } + void Deposit(double amount){ + if(amount > 0){ + balance = balance + amount; + } + } + void WithDraw(double amount){ + if(amount > 0 && amount <= balance){ + balance = balance - amount; + } + else{ + cout << "Invalid balance" << endl; + } + } + void DisplayBalnces(){ + cout << "Accoutn Number: " << AccountNumber << endl; + cout << "Balance: " << balance << endl; + } +}; + +class Bank{ + private: + BankAccount* accounts; + int NumAccounts; + public: + Bank(int NumAccounts = 0){ + this -> NumAccounts = NumAccounts; + accounts = new BankAccount[NumAccounts]; + for(int i = 0; i < NumAccounts; i++){ + accounts[i] = BankAccount(i + 1); + } + } + ~Bank(){ + delete [] accounts; + } + void performTransactions(){ + if(NumAccounts >= 3){ + accounts[0].Deposit(100); + accounts[1].Deposit(100); + accounts[2].Deposit(89); + accounts[2].WithDraw(10); + } + } + void displayAllBalances(){ + for(int i = 0 ; i < NumAccounts ; i++){ + accounts[i].DisplayBalnces(); + } + } +}; int main() { + system("cls"); - /* Example usage: */ Bank bank(3); bank.performTransactions(); bank.displayAllBalances(); return 0; -} \ No newline at end of file +} From f531162a106d90eb73ef206c053c07c85cc13a8f Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:43:25 +0400 Subject: [PATCH 10/38] Update homework-09-math-chaining-with-pointers.cpp --- ...omework-09-math-chaining-with-pointers.cpp | 73 ++++++++++--------- 1 file changed, 39 insertions(+), 34 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-09-math-chaining-with-pointers.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-09-math-chaining-with-pointers.cpp index 85337e9..54e3954 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-09-math-chaining-with-pointers.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-09-math-chaining-with-pointers.cpp @@ -1,44 +1,49 @@ #include - using namespace std; -/* - Exercise: - Implement a class called MathOperations that performs basic mathematical operations. - The class should support chaining calls using pointers. - The following operations should be supported: - - 1. add(int val): Adds the given value to the current result. - 2. subtract(int val): Subtracts the given value from the current result. - 3. multiply(int val): Multiplies the current result by the given value. - 4. divide(int val): Divides the current result by the given value. - - Additionally, the class should provide a getResult() function that returns the current result. - - In the main() function, create an instance of MathOperations and demonstrate - the use of chained calls by performing the following operations: - - 1. Start with an initial result of 10. - 2. Add 5, subtract 2, multiply by 3, and divide by 4. - 3. Print the final result. - - Note: Ensure that the class handles division by zero gracefully and returns an appropriate message. -*/ - - -/* Solution */ - - - +class MathOperations{ + private: + int result; + public: + MathOperations(int result){ + this -> result = result; + } + MathOperations* add(int val){ + result = result + val; + return this; + } + MathOperations* subtract(int val){ + result = result - val; + return this; + } + MathOperations* multiply(int val){ + result = result * val; + return this; + } + MathOperations* divide(int val){ + if(val != 0){ + result = result / val; + } + else{ + cout << "Invalid" <subtract(2)->multiply(3)->divide(4); - + cout << "Final result: " << math.getResult() << endl; - + return 0; -} \ No newline at end of file +} From 69c5c53ca77feee04c66352eb5805953a802bebd Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:43:51 +0400 Subject: [PATCH 11/38] Update homework-10-math-chaining-with-references.cpp --- ...ework-10-math-chaining-with-references.cpp | 66 ++++++++++--------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-10-math-chaining-with-references.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-10-math-chaining-with-references.cpp index a4ad714..9363065 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-10-math-chaining-with-references.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-10-math-chaining-with-references.cpp @@ -1,37 +1,39 @@ #include - using namespace std; - -/* - Exercise: - Implement a class called MathOperations that performs basic mathematical operations. - The class should support chaining calls using references. - The following operations should be supported: - - 1. MathOperations& add(int val): Adds the given value to the current result. - 2. MathOperations& subtract(int val): Subtracts the given value from the current result. - 3. MathOperations& multiply(int val): Multiplies the current result by the given value. - 4. MathOperations& divide(int val): Divides the current result by the given value. - - Additionally, the class should provide a getResult() function that returns the current result. - - In the main() function, create an instance of MathOperations and demonstrate - the use of chained calls by performing the following operations: - - 1. Start with an initial result of 10. - 2. Add 5, subtract 2, multiply by 3, and divide by 4. - 3. Print the final result. - - Note: Ensure that the class handles division by zero gracefully and returns an appropriate message. -*/ - - -/* Solution */ - - - - +class MathOperations{ + private: + int result; + public: + MathOperations(int result){ + this -> result = result; + } + MathOperations& add(int val){ + result = result + val; + return *this; + } + MathOperations& subtract(int val){ + result = result - val; + return *this; + } + MathOperations& multiply(int val){ + result = result * val; + return *this; + } + MathOperations& divide(int val){ + if(val != 0){ + result = result / val; + } + else{ + cout << "Invalid" < Date: Wed, 9 Sep 2026 14:45:15 +0400 Subject: [PATCH 12/38] Update homework-11-student-classroom-struct.cpp --- .../homework-11-student-classroom-struct.cpp | 54 ++++++++++--------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-11-student-classroom-struct.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-11-student-classroom-struct.cpp index 4efd904..2bb7113 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-11-student-classroom-struct.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-11-student-classroom-struct.cpp @@ -1,31 +1,14 @@ #include #include - +#include using namespace std; -/* - Exercise: - Implement a program to store and manage the information of students in a class. - Each student should have the following attributes: name, roll number, - and marks in three subjects (Maths, Physics, and Chemistry). - - 1. Define a struct called Student that holds the attributes mentioned above. - - 2. Implement a class called Classroom that represents a class of students. - The class should have the following functionalities: - Add a new student to the class. - Display the details of all students in the class. - Calculate and display the average marks of each student. - - 3. In the main() function, create an instance of the Classroom class. - Prompt the user to enter the details of multiple students and add them to the class. - After adding the students, display the details of all students and their average marks. -*/ - - -/* Solution */ struct Student { - // Complete the code + string name; + int rollNumber; + int mathMarks; + int physicsMarks; + int chemistryMarks; }; class Classroom { @@ -33,7 +16,28 @@ class Classroom { vector students; public: - // Complete the code + void addStudent(Student student){ + students.push_back(student); + } + void displayStudents(){ + for(int i = 0 ; i < students.size() ; i++){ + cout << "Name: " << students[i].name << endl; + cout << "Roll Number: " << students[i].rollNumber < Date: Wed, 9 Sep 2026 14:46:36 +0400 Subject: [PATCH 13/38] Update homework-12-linked-list.cpp --- .../homework/homework-12-linked-list.cpp | 213 ++++++------------ 1 file changed, 63 insertions(+), 150 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-12-linked-list.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-12-linked-list.cpp index dd96872..0875b84 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-12-linked-list.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-12-linked-list.cpp @@ -1,136 +1,69 @@ #include - using namespace std; - -/* - A linked list is a linear data structure that includes a series of connected nodes. - Here, each node stores the data and the address of the next node. - Examples: - https://media.geeksforgeeks.org/wp-content/uploads/20220712172013/Singlelinkedlist.png - https://media.geeksforgeeks.org/wp-content/uploads/20220901153812/LLdrawio.png - - - Linked list Pros and Cons with comparing Arrays: - - Linked List Pros: - 1. Dynamic Size: Linked lists have a dynamic size, - meaning they can easily grow or shrink as elements are added or removed. - 2. This flexibility allows for efficient memory utilization and avoids the need for resizing operations. - 3. Efficient Insertions and Deletions: Insertions and deletions at the beginning or middle of a linked list - can be performed in constant time (O(1)) by updating the references, - without the need for shifting elements like in an array. - 4. No Memory Wastage: Linked lists do not suffer from the memory wastage that can occur in arrays. - They use exactly the amount of memory required for the elements and the node references. - - Linked List Cons: - 1. Sequential Access: Unlike arrays, linked lists do not provide direct or random access to elements. - To access a specific element, you need to traverse the list from the beginning, - which can be less efficient when searching for elements or accessing elements by index. - 2. Additional Memory Overhead: Linked lists require extra memory to store the references - (pointers) to the next node, resulting in increased memory overhead compared to arrays. - 3. No Constant-Time Element Access: Finding an element in a linked list requires traversing the list sequentially, - potentially leading to slower search operations compared to arrays with direct access by index. - - Array Pros: - 1. Random Access: Arrays provide direct and constant-time access to elements by their index, - allowing for efficient element retrieval. - 2. Cache Friendliness: Arrays have better cache locality since elements are stored contiguously in memory. - This can lead to faster access times when accessing adjacent elements. - 3. Compact Memory Representation: Arrays use a compact memory representation, - requiring less memory compared to linked lists for storing the same number of elements. - - Array Cons: - 1. Fixed Size: Arrays have a fixed size, - which means they require resizing or allocation of a new array when the number of elements changes, l - eading to overhead in terms of time and memory. - 2. Costly Insertions and Deletions: Insertions and deletions in the middle or beginning of an array require shifting elements, - resulting in less efficient operations and potentially affecting performance. - 3. Wasted Memory: If the array size is initially larger than needed, - memory can be wasted since it is allocated for all elements, regardless of their presence or absence. - - In summary, linked lists are advantageous when frequent insertions and deletions are required, - while arrays are more suitable for scenarios where random access and cache efficiency are important. - The choice between linked lists and arrays depends on the specific requirements and trade-offs of the application at hand. - - - Linked list use cases: - 1. Implementation of Stacks and Queues: Linked lists are commonly used to implement stack and queue data - structures due to their efficient insertion and deletion operations at the beginning or end of the list. - Each node in the list represents an element in the stack or queue, - and the references allow for easy manipulation of the data. - - 2. Dynamic Memory Allocation: Linked lists are useful when dynamic memory allocation is required. - Since linked lists don't require contiguous memory, - they can efficiently allocate and deallocate memory as needed, - making them suitable for scenarios where the size of the data structure may change frequently. - - 3. File Systems: Linked lists can be used to represent file systems. - Each node in the linked list represents a file or directory, - and the references between nodes allow for easy navigation and organization of the file structure. - 4. Music and Video Playlists: Linked lists are often used to implement playlists in music or video players. - Each node in the list represents a song or video, - and the references between nodes allow for easy traversal and manipulation of the playlist, - such as adding, removing, and reordering items. - - 5. Symbol Tables: Linked lists can be used in symbol table implementations. - Each node contains a key-value pair, and the references allow for efficient lookup, - insertion, and deletion of elements in the symbol table. - - 6. Polynomial Representation: Linked lists can be used to represent polynomials in mathematics. - Each node represents a term in the polynomial, with the data storing the coefficient and exponent of each term. - - 7. Graph Algorithms: Linked lists are often used in graph algorithms, - such as representing adjacency lists for graph traversal. - Each node in the linked list represents a neighboring vertex, - and the references allow for efficient representation and traversal of the graph. -*/ - -/* - Exercise: - - 1. Define a struct called Node that represents a single node in the linked list. - The struct should have two members: a data member to store the value of the node - and a pointer member to point to the next node in the list. - - 2. Define a class called LinkedList that represents the linked list itself. - The class should have a private member to store the head node pointer. - - 3. Implement a constructor for the LinkedList class that initializes the head pointer to nullptr, - indicating an empty list. - - 4. Implement a member function in the LinkedList class called insert, - which takes a value as a parameter and inserts a new node with that value at the beginning of the list. - - 5. Implement a member function in the LinkedList class called display, - which traverses the linked list and prints the values of all the nodes. - - 6. Implement a member function in the LinkedList class called search, - which takes a value as a parameter and searches for a node with that value in the list. - If found, it should return true; otherwise, it should return false. - - 7. Implement a member function in the LinkedList class called remove, - which takes a value as a parameter and removes the first occurrence of a node with that value from the list. - If the value is not found, it should do nothing. - - 8. Implement a member function in the LinkedList class called append, - which takes a value as a parameter and adds a new node with that value to the end of the list. - - 9. Implement a destructor for the LinkedList class that deletes all the nodes in the list. - - 10. Test your implementation by creating an instance of the LinkedList class, inserting several nodes, - and then calling the display function to verify that the nodes are correctly inserted and displayed. - Test the search, remove, and append functions as well. - - Remember to use the appropriate access specifiers (private, public) to encapsulate the members of the classes properly. - This exercise will help you understand how to implement a linked list using OOP principles in C++. -*/ - - -/* Solution */ - - +struct Node{ + int data; + Node*next; +}; +class LinkedList{ + private: + Node*head; + public: + LinkedList(){ + head = nullptr; + } + ~LinkedList(){ + Node*current = head; + while(current != nullptr){ + Node*temp = current; + current = current -> next; + delete temp; + } + } + LinkedList& insert(int value){ + Node*NewNode = new Node{value , head}; + head = NewNode; + return *this; + } + LinkedList& append(int value){ + Node*NewNode = new Node{value , nullptr}; + if(head == nullptr){ + head = NewNode; + return *this; + } + Node*current = head; + while(current->next != nullptr){ + current = current -> next; + } + current->next = NewNode; + return *this; + } + bool search(int value){ + Node*current = head; + while(current != nullptr){ + if(current -> data == value){ + return true; + } + current = current->next; + } + return false; + } + LinkedList& remove(int value){ + //yaza bilmedim. + + } + LinkedList& display(){ + Node*current = head; + while(current != nullptr){ + cout << current->data <next; + } + return *this; + } + +}; int main() { + system("cls"); /* Example usage: */ LinkedList list = LinkedList(); @@ -150,24 +83,4 @@ int main() { list.remove(3).display().remove(4).display().remove(5).display(); cout << endl; - - /* - Example Output: - - [1 | 0x7f9092f05c80] ---> [2 | 0x7f9092f05c90] ---> [3 | 0x7f9092f05ca0] ---> [4 | 0x0] - [5 | 0x7f9092f05c70] ---> [1 | 0x7f9092f05c80] ---> [2 | 0x7f9092f05c90] ---> [3 | 0x7f9092f05ca0] ---> [4 | 0x0] - - true - - [5 | 0x7f9092f05c70] ---> [1 | 0x7f9092f05c80] ---> [2 | 0x7f9092f05ca0] ---> [4 | 0x0] - [5 | 0x7f9092f05c70] ---> [1 | 0x7f9092f05c80] ---> [2 | 0x0] - [1 | 0x7f9092f05c80] ---> [2 | 0x0] - - Destructor: - delete on 0 - delete on 1 - delete on 2 - */ - - return 0; -} \ No newline at end of file +} From f0ba6233e786a68655c0a2db88bb5c002f80d062 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:47:14 +0400 Subject: [PATCH 14/38] Update homework-13-stack.cpp --- .../homework/homework-13-stack.cpp | 222 ++++++++++-------- 1 file changed, 125 insertions(+), 97 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-13-stack.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-13-stack.cpp index 8418a26..61c32f1 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-13-stack.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-13-stack.cpp @@ -1,80 +1,133 @@ -#include "LinkedList.h" -#include "LinkedList.h" +#include +using namespace std; + +struct Node { + int data; + Node* next; +}; + +class LinkedList { +protected: + Node* head; +public: + LinkedList() { head = nullptr; } + + ~LinkedList() { + Node* current = head; + while (current != nullptr) { + Node* temp = current; + current = current->next; + delete temp; + } + } + + LinkedList& insert(int value) { + Node* NewNode = new Node{value, head}; + head = NewNode; + return *this; + } + + LinkedList& append(int value) { + Node* NewNode = new Node{value, nullptr}; + if (head == nullptr) { + head = NewNode; + return *this; + } + Node* current = head; + while (current->next != nullptr) current = current->next; + current->next = NewNode; + return *this; + } + + bool search(int value) { + Node* current = head; + while (current != nullptr) { + if (current->data == value) return true; + current = current->next; + } + return false; + } -/* - Definition of Stack: - - A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. - It is an abstract data type with a collection of elements in which elements are added and removed from only one end, - known as the "top" of the stack. - - In a stack, the element that is added last is the first one to be removed. - This behavior is similar to a stack of objects, where you can only add or remove items from the top of the stack. - Due to its LIFO nature, a stack can be visualized as a vertical stack of items, where you can only access the topmost item. - - The two primary operations performed on a stack are: - 1. Push: Adds an element to the top of the stack. - 2. Pop: Removes and returns the topmost element from the stack. - - Other common operations associated with a stack include: - - Peek or Top: Retrieves the value of the topmost element without removing it. - - Size: Returns the number of elements currently in the stack. - - isEmpty: Checks if the stack is empty. - - Stacks are widely used in various computer science applications, such as expression evaluation, - function call management, undo/redo functionality, backtracking algorithms, memory management, and more. - The simplicity and efficiency of stacks make them an essential data structure in many programming scenarios. -*/ - -/* - Exercise: - - 1. Once the "LinkedList" class is implemented and tested, use it to build the "LinkedListStack" class. - - 2. Define a class called "LinkedListStack" that represents the stack using a linked list. - The class should have a private member to store the top node pointer. - - 3. Implement a constructor for the LinkedListStack class that initializes the top pointer to nullptr, indicating an empty stack. - - 4. Implement a member function in the LinkedListStack class called "push", - which takes a value as a parameter and pushes (inserts) that value onto the top of the stack. - - 5. Add a "getHead" member function to the "LinkedList" class, which returns the head node pointer. - - 6. Implement a member function in the LinkedListStack class called "pop", - which removes and returns the value from the top of the stack. - If the stack is empty, return a special value or throw an exception to indicate an underflow condition. - - 7. Implement a member function in the LinkedListStack class called "peek", - which returns the value from the top of the stack without removing it. - If the stack is empty, return a special value or throw an exception to indicate an underflow condition. - - 8. Implement a member function in the LinkedListStack class called "isEmpty", - which checks if the stack is empty and returns a boolean value accordingly. - - 9. Implement a member function in the LinkedListStack class called "size", which returns the number of elements currently in the stack. - 10. Implement a "destructor" for the LinkedListStack class that deletes all the nodes in the stack. - - 11. Test your implementation by creating an instance of the LinkedListStack class, pushing several values onto the stack, - and then performing pop, peek, isEmpty, size, and destructor operations to verify the correctness of the stack behavior. - - [Stack use cases]: https://www.enjoyalgorithms.com/blog/application-of-stack-data-structure-in-programming -*/ - - -/* Solution */ - - - + LinkedList& remove(int value) { + if (head == nullptr) return *this; + + if (head->data == value) { + Node* temp = head; + head = head->next; + delete temp; + return *this; + } + + Node* current = head; + while (current->next != nullptr && current->next->data != value) { + current = current->next; + } + + if (current->next != nullptr) { + Node* temp = current->next; + current->next = temp->next; + delete temp; + } + return *this; + } + + int size() { + int count = 0; + Node* current = head; + while (current != nullptr) { count++; current = current->next; } + return count; + } + + LinkedList& display() { + Node* current = head; + while (current != nullptr) { + cout << current->data << endl; + current = current->next; + } + return *this; + } +}; +class Stack : public LinkedList{ + public: + Stack& push(int value){ + insert(value); + return*this; + + } + Stack& pop(){ + if(head == nullptr){ + cout << "Nothing pop" <data); + return *this; + } + + } + Stack& peek(){ + if(head == nullptr){ + cout << "Nothing peek" < data < [4 | 0x7ff5cf705ca0] ---> [3 | 0x7ff5cf705c90] ---> [2 | 0x7ff5cf705c80] ---> [1 | 0x0] - Display Stack: [4 | 0x7ff5cf705ca0] ---> [3 | 0x7ff5cf705c90] ---> [2 | 0x7ff5cf705c80] ---> [1 | 0x0] - - Peek: [4 | 0x7ff5cf705ca0] - - Nothing to pop (^_^) - Stack is empty! - - Start Stack Deallocation: - -Destructor: - delete on 0 - End of Stack Deallocation - */ - - - return 0; -} \ No newline at end of file +} From 0ee8a81423a09448baaeb26da5bda7aaf0da7321 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:48:24 +0400 Subject: [PATCH 15/38] Update homework-14-queue.cpp --- .../homework/homework-14-queue.cpp | 160 +++++++++--------- 1 file changed, 78 insertions(+), 82 deletions(-) diff --git a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-14-queue.cpp b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-14-queue.cpp index 101eefb..8a779e1 100644 --- a/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-14-queue.cpp +++ b/1-CLASSES-OBJECTS-AND-DATA-STRUCTURES/homework/homework-14-queue.cpp @@ -1,85 +1,81 @@ #include - using namespace std; - -/* - - Source: https://www.geeksforgeeks.org/queue-data-structure/ - - A queue is a common data structure that follows the "first-in, first-out" (FIFO) principle. - It can be visualized as a line of people waiting for a service, - where the person who arrives first gets served first. - - In a queue, elements are added at one end called the "rear" or "enqueue" operation, - and elements are removed from the other end called the "front" or "dequeue" operation. - This ensures that the element that has been in the queue the longest gets dequeued first. - - Some key operations associated with a queue are: - - 1. Enqueue: Adds an element to the rear of the queue. - 2. Dequeue: Removes the front element from the queue and returns it. - 3. Peek/Front: Returns the front element of the queue without removing it. - 4. IsEmpty: Checks if the queue is empty. - 5. Size: Returns the number of elements currently in the queue. - - Queues can be implemented using various data structures such as arrays, - linked lists, or even built-in collections in programming languages. - The choice of implementation depends on the specific requirements and constraints of the application. - - [Application of Queues] - Queues have many practical use cases in computer science and everyday programming. - Here are some common scenarios where queues are used: - - 1. Task Scheduling: Queues are often used to manage and schedule tasks or jobs in various systems. - For example, in an operating system, a queue can be used to schedule processes for execution based on their arrival time or priority. - - 2. Message Queues: In messaging systems or distributed systems, - queues are used to handle asynchronous communication between components. - Messages are placed in a queue and processed by the receiving components at their own pace. - - 3. Print Spooling: In print management systems, - queues are used to store print jobs in the order they were submitted. - The jobs are then printed one by one, following the FIFO principle. - - 4. Web Server Request Handling: Web servers typically use queues to handle incoming requests. - Each request is added to a queue, and the server processes them in the order they arrived. - This ensures fair handling and prevents overload on the server. - - 5. Breadth-First Search (BFS): BFS is a graph traversal algorithm that explores all the vertices of a graph in breadth-first order. - A queue is used to keep track of the vertices to be visited, - allowing the algorithm to visit adjacent vertices before exploring deeper into the graph. - - 6. Buffering in I/O Operations: Queues can be used to buffer input and output operations in various scenarios. - For example, when reading data from a file or a network socket, the data can be stored in a queue before being processed. - - 7. Call Center Systems: In call center applications, queues are used to manage incoming calls. - Calls are placed in a queue and are assigned to available agents in the order they were received, ensuring a fair distribution of calls. -*/ - - -/* - Exercise: Implement a Queue using a Linked List - - Implement the queue data structure using your previous linked list solution. - The linked list should have nodes that store an integer value and a reference to the next node. - The queue should support the following operations: - - 1. Enqueue: Add an element to the rear of the queue. - 2. Dequeue: Remove and return the front element of the queue. - 3. Peek/Front: Returns the front element of the queue without removing it. - 4. IsEmpty: Check if the queue is empty. - 5. Size: Return the number of elements currently in the queue. -*/ - - -/* Solution */ - - - -int main() { - - /* Example usage: */ - +struct Node{ + int data; + Node*next; +}; +class Queue{ + private: + Node*front; + Node*rear; + public: + Queue(){ + front = nullptr; + rear = nullptr; + } + ~Queue(){ + while(front != nullptr){ + Node*current = front; + front = front -> next; + delete current; + } + } + int isEmpty(){ + if(front == nullptr){ + return 1; + } + else{ + return 0; + } + } + int peek(){ + if(front == nullptr){ + cout << "Queue is empt: " < data; + } + Queue& enqueue(int value){ + Node*NewNode = new Node{value , nullptr}; + if(rear == nullptr){ + rear = NewNode; + front = NewNode; + return *this; + } + else{ + rear->next = NewNode; + rear = NewNode; + return *this; + } + } + int dequeue(){ + if(front == nullptr){ + cout << "nothing" <data; + front = front -> next; + if(front == nullptr){ + rear = nullptr; + } + delete temp; + return value; + + + } + int size(){ + Node*current = front; + int size1 = 0; + while(current != nullptr){ + size1++; + current = current->next; + } + return size1; + } + +}; +int main(){ Queue queue; queue.enqueue(10); @@ -97,5 +93,5 @@ int main() { cout << "Dequeued: " << queue.dequeue() << endl; // Output: Dequeued: 30 cout << "Is Empty? " << queue.isEmpty() << endl; // Output: Is Empty? 1 (true) - return 0; -} \ No newline at end of file + +} From cd1ce9f777f6929cc66700f6506332ca0687eadb Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:52:54 +0400 Subject: [PATCH 16/38] Update homework-01-protected-members.cpp --- .../homework-01-protected-members.cpp | 81 +++++++------------ 1 file changed, 27 insertions(+), 54 deletions(-) diff --git a/2-INHERITANCE/homework/homework-01-protected-members.cpp b/2-INHERITANCE/homework/homework-01-protected-members.cpp index 1788a24..b6cb8b5 100644 --- a/2-INHERITANCE/homework/homework-01-protected-members.cpp +++ b/2-INHERITANCE/homework/homework-01-protected-members.cpp @@ -1,60 +1,33 @@ #include #include - using namespace std; - -/* - Exercise: - - You'll define two classes, Person and Teacher, to represent individuals within the school. - The goal is to demonstrate the concept of inheritance and access control modifiers in C++. - - In this example: - - The Person class has protected properties like name, age, and grades. - The Teacher class is derived from Person. - It can directly access the grades property for reviewing purposes using the ReviewGrades method. - The grades property is not directly accessible from outside the class hierarchy. - This example reflects your analogy: Teacher objects, which are a type of Person, - can access the grades of students (also a type of Person) for reviewing purposes. - However, the grades property remains encapsulated and not directly accessible - from outside the class hierarchy, preserving data encapsulation. - - - Class Descriptions: - - 1. Person Class: - The Person class will serve as the base class for all individuals in the school. - It will have three protected member variables: - name (string): Stores the name of the person. - age (int): Stores the age of the person. - grades (int): Stores the grades of the person. - It will have a constructor that takes the name, age, and grades as parameters and initializes the corresponding member variables. - It will have a public member function: - int GetGrades() const: Returns the grades of the person. - - 2. Teacher Class (Derived from Person): - The Teacher class will inherit from the Person class. - It will have a constructor that takes name, age, - and grades as parameters and passes them to the base class constructor. - It will have a public member function: - void ReviewGrades(): Outputs a message indicating that the teacher is reviewing grades, along with the teacher's name and grades. -*/ - -/* Solution */ - - - - +class Person{ + protected: + string name; + int age; + int grades; + public: + Person(string name = "Unknown" , int age = 0 , int grades = 0){ + this -> name = name; + this -> grades = grades; + this -> age = age; + } +}; +class Teacher : public Person{ + public: + Teacher(string name , int age , int grades) : Person(name , age , grades){}; /* daha rahat "using Person :: Person" da yazila bilerdi.Yeni bir basa + persondaki konstruktoru kopyalayiram Teacher(child konstruktora). Menim yazdigim numunede ise men Teacher konstruktoru yaradiram ve o konstruktorla + Person konstruktorun cagiriram , yəni bir nov yeni funksiya yaradiram.*/ + void ReviewGrades(){ + cout << name << " is reviewing grades" < Date: Wed, 9 Sep 2026 14:54:20 +0400 Subject: [PATCH 17/38] Update homework-02-library-management-system.cpp --- .../homework-02-library-management-system.cpp | 141 ++++++++---------- 1 file changed, 65 insertions(+), 76 deletions(-) diff --git a/2-INHERITANCE/homework/homework-02-library-management-system.cpp b/2-INHERITANCE/homework/homework-02-library-management-system.cpp index 1e7c93b..d4b3a22 100644 --- a/2-INHERITANCE/homework/homework-02-library-management-system.cpp +++ b/2-INHERITANCE/homework/homework-02-library-management-system.cpp @@ -1,65 +1,69 @@ #include -#include #include - +#include using namespace std; - -/* - Exercise: Library Management System - - In this exercise, we'll create a simple Library Management System - using object-oriented programming and inheritance in C++. - This exercise simulates a real-world application in software engineering where - different types of library items are managed within a library system. - - Background: - Imagine you are developing a library management software for a university. - The software needs to handle two types of items: Books and DVDs. - Both items have common properties such as title, author/director, and publication year, - but they also have some specific properties. - Books have an ISBN (International Standard Book Number) while DVDs have a runtime. - - Requirements: - - 1. Create a base class called LibraryItem with the following attributes and methods: - Attributes: title, authorOrDirector, publicationYear - Methods: displayInfo() - Display the common attributes of the library item. - - Note! ~ Make displayInfo method "virtual" in parent class, - which is the part of polymorphism that will be described in the next chapter. - - ~ "virtual void displayInfo() {...}" - Virtual methods will be described broadly in the next chapter. - - 2. Derive two classes Book and DVD from the LibraryItem base class. - Add the following attributes and methods to each derived class: - Book class: - Additional attribute: isbn - Additional method: displayInfo() - Override the base class method to include ISBN. - DVD class: - Additional attribute: runtime - Additional method: displayInfo() - Override the base class method to include runtime. - - 3. Create a class called Library which can store an array/vector of pointers to LibraryItem objects. - It should have the following methods: - addItem() - Add a new library item to the collection. - displayAllItems() - Display information about all items in the library. -*/ - -/* - Explanation: - This exercise demonstrates the concept of inheritance in C++ where the Book and DVD classes - inherit properties and methods from the LibraryItem base class. - The Library class manages a collection of library items, both books and DVDs. -*/ - - -/* Solution */ - - - -int main() { - - /* Example usage: */ +class LibraryItem{ + protected: + string title; + string authorOrDirector; + int publicationYear; + public: + LibraryItem(string title , string authorOrDirector , int publicationYear){ + this -> title = title; + this -> authorOrDirector = authorOrDirector; + this -> publicationYear = publicationYear; + } + void virtual DisplayInfo(){ + cout << "Title: " << title < isbn = isbn; + } + void DisplayInfo(){ + LibraryItem ::DisplayInfo(); + cout << "ISBN: " << isbn << endl; + } + +}; +class DVD : public LibraryItem{ + private: + int runtime; + public: + DVD(string title , string authorOrDirector , int publicationYear , int runtime) : LibraryItem(title , authorOrDirector , publicationYear){ + this -> runtime = runtime; + } + void DisplayInfo(){ + LibraryItem :: DisplayInfo(); + cout << "Runtime: " << runtime << endl; + } +}; +class Library{ + private: + vectoritems; + public: + void addItem(LibraryItem*item){ + items.push_back(item); + } + void displayAllItems(){ + for(int i = 0 ; iDisplayInfo(); + cout << "------------" < Date: Wed, 9 Sep 2026 14:56:01 +0400 Subject: [PATCH 18/38] Update homework-03-multiple-inheritance.cpp --- .../homework-03-multiple-inheritance.cpp | 143 +++++++----------- 1 file changed, 54 insertions(+), 89 deletions(-) diff --git a/2-INHERITANCE/homework/homework-03-multiple-inheritance.cpp b/2-INHERITANCE/homework/homework-03-multiple-inheritance.cpp index 29b4b5f..234d1da 100644 --- a/2-INHERITANCE/homework/homework-03-multiple-inheritance.cpp +++ b/2-INHERITANCE/homework/homework-03-multiple-inheritance.cpp @@ -3,87 +3,74 @@ #include using namespace std; - -/* - What You Will Learn: - - By completing this exercise, you will not only have enhanced your understanding of constructor design - and access specifiers but also gained insights into the principles of encapsulation and object-oriented design. - You will be better equipped to create classes with well-designed constructors - and appropriately chosen access specifiers for improved code organization and maintainability. -*/ - - -/* - Exercise Description: - - In this exercise, you will work on enhancing the provided C++ program - that models a basic object-oriented project and task management system. - The focus will be on constructing classes with optimal constructor design - and understanding the selection of access specifiers (public, protected, private) to achieve encapsulation. - Your task is to both complete the exercise objectives and respond to questions about constructor design and access specifiers. -*/ - - -/* Starter Code: */ - class Project { - // ... (Same as provided code) + private: + string ProjectName; + public: + Project(){ + ProjectName = "unknown"; + } + Project(string ProjectName){ + this ->ProjectName = ProjectName; + } + string getProject(){ + return ProjectName; + } }; - class TeamMember { - // ... (Same as provided code) + private: + string TeamMemberName; + public: + TeamMember(){ + TeamMemberName = "unknown"; + } + TeamMember(string TeamMemberName){ + this -> TeamMemberName = TeamMemberName; + } + string getTeamMember(){ + return TeamMemberName; + } }; class Task { - // ... (Same as provided code) + private: + string TaskName; + public: + Task(){ + TaskName = "unknown"; + } + Task(string TaskName){ + this -> TaskName = TaskName; + } + string getTask(){ + return TaskName; + } + }; class ProjectTeamMember : public Project, public TeamMember { - // ... (Same as provided code) + public: + ProjectTeamMember(string Pname , string TMname) : Project(Pname) , TeamMember(TMname){ + } + string displayProjectTeamMember(){ + cout << "Project Name: " << getProject() < Date: Wed, 9 Sep 2026 14:56:30 +0400 Subject: [PATCH 19/38] Update homework-04-inheritance-access-types.cpp --- .../homework-04-inheritance-access-types.cpp | 122 ++++++++---------- 1 file changed, 53 insertions(+), 69 deletions(-) diff --git a/2-INHERITANCE/homework/homework-04-inheritance-access-types.cpp b/2-INHERITANCE/homework/homework-04-inheritance-access-types.cpp index 004e429..9aa3670 100644 --- a/2-INHERITANCE/homework/homework-04-inheritance-access-types.cpp +++ b/2-INHERITANCE/homework/homework-04-inheritance-access-types.cpp @@ -1,67 +1,58 @@ #include #include - +#include using namespace std; - -/* - Exercise Description: - In this exercise, you will explore the concepts of public, protected, and private inheritance in C++. - You'll be presented with a scenario involving different classes and their relationships, - and you'll need to decide which type of inheritance - should be used in each case to achieve the desired behavior and access levels. - - Scenario: - Imagine you are developing a software system to model various types of vehicles for a transportation company. - You need to create a hierarchy of classes to represent different types of vehicles and their attributes. - Additionally, there will be a Manager class that handles the management of these vehicles. -*/ - -/* - Classes: - - 1. Vehicle: This is the base class that will hold common attributes of all vehicles, - such as the vehicle's identification number (id), maximum speed (maxSpeed), - and a function to display information about the vehicle (display()). - - 2. Car: This class represents a car and should inherit from the Vehicle class. - It will have additional attributes like the number of doors (numDoors) - and a function to calculate fuel efficiency (calculateFuelEfficiency()). - - 3. Bus: This class represents a bus and should also inherit from the Vehicle class. - It will have attributes like the maximum passenger capacity (maxPassengers) - and a function to announce the next bus stop (announceNextStop()). - - 4. Manager: This class is responsible for managing the fleet of vehicles. - It should have a collection of vehicles, a function to add vehicles to the fleet (addVehicle()), - and a function to display information about all vehicles in the fleet (displayFleet()). -*/ - -/* - Instructions: - - 1. Determine the appropriate type of inheritance (public, protected, or private) between the Vehicle, Car, and Bus classes. - 2. Decide which attributes and functions should be accessible from the Manager class and other derived classes. - 3. Implement the necessary inheritance relationships and access specifiers to achieve the desired behavior. - - Discussion Points: - Why would you choose public inheritance for certain classes? - When is protected inheritance useful and in what scenarios should it be avoided? - How does private inheritance restrict access compared to public and protected inheritance? - - Note: This exercise is designed to encourage understanding of inheritance types and their implications. - It does not involve actual coding, but rather requires conceptual analysis - and decision-making regarding inheritance relationships and access specifiers in C++. -*/ - - -/* Solution */ - - - - -int main() { - - /* Example Usage */ +class Vehicle{ + protected: + int id; + int MaxSpeed; + public: + Vehicle(int id , int MaxSpeed){ + this -> id = id; + this -> MaxSpeed = MaxSpeed; + } + void displayVehicle(){ + cout << "ID: " << id < NumDoors = NumDoors; + } + void calculateFuelEfficiency(){ + cout <<"Fuel Efficiency is calculated:" < maxPassengers = maxPassengers; + } + void announceNextStop(){ + cout << "Announce!" <fleet; + public: + void addVehicle(Vehicle * v ){ + fleet.push_back(v); + } + void displayFleet(){ + for(int i = 0 ; i < fleet.size() ; i++){ + fleet[i] -> displayVehicle(); + } + } + +}; +int main(){ Car car1(1, 150, 4); Bus bus1(2, 80, 40); @@ -71,13 +62,6 @@ int main() { manager.addVehicle(&bus1); manager.displayFleet(); - - /* - [Output] - - Vehicle ID: 1, Max Speed: 150 km/h - Vehicle ID: 2, Max Speed: 80 km/h - */ - return 0; + } From 9d1f5f3bd29a6f09717baa0964a0dd72458ea2b7 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:57:11 +0400 Subject: [PATCH 20/38] Update homework-05-banking-inheritance-types.cpp --- .../homework-05-banking-inheritance-types.cpp | 139 +++++++++--------- 1 file changed, 73 insertions(+), 66 deletions(-) diff --git a/2-INHERITANCE/homework/homework-05-banking-inheritance-types.cpp b/2-INHERITANCE/homework/homework-05-banking-inheritance-types.cpp index f9e2765..714f331 100644 --- a/2-INHERITANCE/homework/homework-05-banking-inheritance-types.cpp +++ b/2-INHERITANCE/homework/homework-05-banking-inheritance-types.cpp @@ -1,59 +1,77 @@ -#include -#include - +#include using namespace std; - - -/* - Exercise: Inheritance in a Banking Software Application - - In this exercise, you will design a simplified banking software application using C++ classes - to demonstrate the real need for public, protected, and private inheritance. - The application will model a basic bank system with different types of accounts and transactions. - You will create a base class for "Account" and derive three different types of accounts from it. - Then, you will demonstrate the appropriate usage of public, protected, and private inheritance in this context. - - Part 1: Base Class and Inheritance - 1. Create a base class called Account with the following properties and methods: - Properties: accountNumber, accountHolder, balance - Methods: deposit, withdraw, getBalance - - 2. Derive three classes from the Account base class: - a. SavingsAccount: This should inherit using public inheritance. - Add a method called applyInterest that increases the balance based on an interest rate. - b. CheckingAccount: This should inherit using protected inheritance. - Add a method called applyMonthlyFee that deducts a fixed fee from the balance every month. - c. CreditCardAccount: This should inherit using private inheritance. - Add a method called makePurchase that deducts a specified amount from the balance. - - Part 2: Demonstration - 1. In your main function, instantiate objects of each of the derived classes (SavingsAccount, CheckingAccount, CreditCardAccount). - 2. Simulate transactions using the instantiated objects: - Deposit and withdraw funds from each account. - Apply interest to the SavingsAccount. - Apply monthly fees to the CheckingAccount. - Make purchases using the CreditCardAccount. - 3. Display the account details and balances after each transaction. - - Part 3: Analysis - - 1. Explain why public inheritance is suitable for the SavingsAccount class. - 2. Discuss the advantages of using protected inheritance for the CheckingAccount class. - 3. Justify the use of private inheritance for the CreditCardAccount class. -*/ - - -/* - Solution -*/ - - -int main() { - - system("clear"); - - /* Example Usage */ - +class Account{ + protected: + int AccountNumber; + string AccountHolder; + double balance; + public: + Account(int AccountNumber = 0 , string AccountHolder = "Unknown" , double balance = 0){ + this -> AccountNumber = AccountNumber; + this -> AccountHolder = AccountHolder; + this -> balance = balance; + } + void deposit(double value){ + if(value > 0){ + cout << "deposit: " << value < 0 && value < balance){ + balance = balance - value; + cout << "balance: " << balance << endl; + } + else{ + cout << "Invalid balance" <= val){ + balance = balance - val; + cout << "balance: " < val && val > 0){ + balance = balance - val; + cout << "balance: " << balance << endl; + } + else{ + cout << "Invalid purchase" << endl; + } + } +}; +int main(){ + system("cls"); SavingsAccount savings(1001, "John Doe", 1000.0); CheckingAccount checking(2001, "Jane Smith", 1500.0); CreditCardAccount creditCard(3001, "Alice Johnson", 500.0); @@ -66,15 +84,4 @@ int main() { creditCard.makePurchase(200); creditCard.makePurchase(400); - - /* - [Output] - - Deposit: 500 Balance: 1500 - Interest Applied: Balance: 1575 - Withdraw: 200 Balance: 1375 - Monthly Fee Applied: Balance: 1490 - Purchase Made: Amount: 200 Balance: 300 - Insufficient Funds - */ } From 68f61714c92f4a88176a2545eb85fb54ed67339b Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:57:43 +0400 Subject: [PATCH 21/38] Update homework-06-custom-constructors-with-inheritance.cpp --- ...6-custom-constructors-with-inheritance.cpp | 196 +++++++----------- 1 file changed, 73 insertions(+), 123 deletions(-) diff --git a/2-INHERITANCE/homework/homework-06-custom-constructors-with-inheritance.cpp b/2-INHERITANCE/homework/homework-06-custom-constructors-with-inheritance.cpp index 757341f..714f331 100644 --- a/2-INHERITANCE/homework/homework-06-custom-constructors-with-inheritance.cpp +++ b/2-INHERITANCE/homework/homework-06-custom-constructors-with-inheritance.cpp @@ -1,137 +1,87 @@ -#include -#include - +#include using namespace std; - - -/* - Exercise Title: Understanding Custom Constructors with Inheritance -*/ - - -/* - Tasks: - - 1. In the below code describe the purpose of the GameObject class. - What common functionality does it provide for its derived classes? - - 2. Explain the concept of inheritance as demonstrated in the code. - How are the Player, Enemy, and Character classes related to the GameObject class? - - 3. Identify and describe the purpose of the constructors in the derived classes (Player, Enemy, Character). - How do they initialize the member variables of the derived classes and the base class? - - 4. In the main function, three objects are created: player, enemy, and character. - Explain how these objects are constructed using the provided constructors. - - 5. Describe the benefits of using inheritance in this scenario. - How does it contribute to code organization and reusability? - - 6. Imagine you need to add a new class called Weapon that inherits from GameObject and has an additional attribute called damage. - Extend the code to include the Weapon class and demonstrate its usage in the main function. - - 7. Modify the Character class to include an additional attribute, - such as experience, and update its constructor and displayInfoCharacter method accordingly. - Reflect on how these changes affect the overall structure of the program. - - 8. Discuss potential improvements or alternative approaches that - could be taken to design a similar system with better maintainability and extensibility. -*/ - - - -class GameObject { +class Account{ + protected: + int AccountNumber; + string AccountHolder; + double balance; public: - GameObject(const string& name) : name(name) { - // Common initialization for all game objects + Account(int AccountNumber = 0 , string AccountHolder = "Unknown" , double balance = 0){ + this -> AccountNumber = AccountNumber; + this -> AccountHolder = AccountHolder; + this -> balance = balance; + } + void deposit(double value){ + if(value > 0){ + cout << "deposit: " << value < 0 && value < balance){ + balance = balance - value; + cout << "balance: " << balance << endl; } - - private: - string name; + else{ + cout << "Invalid balance" <= val){ + balance = balance - val; + cout << "balance: " < val && val > 0){ + balance = balance - val; + cout << "balance: " << balance << endl; } - - void displayInfoCharacter() { - displayInfo(); - cout << "Level: " << level << "\n"; + else{ + cout << "Invalid purchase" << endl; } - - private: - int level; + } }; - - -int main() { - - system("clear"); - - /* Example Usage */ - Player player("Hero", 100); - Enemy enemy("Goblin", 20); - Character character("Adventurer", 5); - - player.displayInfoPlayer(); - cout << endl; - - enemy.displayInfoEnemy(); - cout << endl; - - character.displayInfoCharacter(); - - /* - [Output] - - Name: Hero - Health: 100 - - Name: Goblin - Damage: 20 - - Name: Adventurer - Level: 5 - */ - - return 0; -} \ No newline at end of file +int main(){ + system("cls"); + SavingsAccount savings(1001, "John Doe", 1000.0); + CheckingAccount checking(2001, "Jane Smith", 1500.0); + CreditCardAccount creditCard(3001, "Alice Johnson", 500.0); + + savings.deposit(500); + savings.applyInterest(0.05); + savings.withdraw(200); + + checking.applyMonthlyFee(10); + + creditCard.makePurchase(200); + creditCard.makePurchase(400); +} From c62cc45c906d855b388d9ca3ada547f2ac9eb89d Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 14:59:13 +0400 Subject: [PATCH 22/38] Update homework-01-shape-hierarchy.cpp --- .../homework/homework-01-shape-hierarchy.cpp | 116 ++++++++++-------- 1 file changed, 64 insertions(+), 52 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-01-shape-hierarchy.cpp b/3-POLYMORPHISM/homework/homework-01-shape-hierarchy.cpp index 5451eb8..7620f2f 100644 --- a/3-POLYMORPHISM/homework/homework-01-shape-hierarchy.cpp +++ b/3-POLYMORPHISM/homework/homework-01-shape-hierarchy.cpp @@ -1,57 +1,70 @@ -#include -#include - +#include using namespace std; +class Shape{ + private: + string name; + public: + Shape(string name){ + this -> name = name; + } + virtual void draw(){ + cout << "Drawing a "; + } - -/* - Exercise: Polymorphism in C++ - - Instructions: - - 1. Create a C++ program that models geometric shapes. - 2. Define a base class Shape with the following properties and methods: - Properties: - name (string): The name of the shape. - Methods: - virtual void draw(): A virtual function that prints a message indicating that a shape is being drawn. - The message should include the shape's name. - 3. Create two derived classes, Circle and Rectangle, that inherit from the Shape class. - Each derived class should have its own specific properties and methods: - Circle: - Properties: - radius (double): The radius of the circle. - Methods: - Override the draw() method to print a message indicating that a circle is being drawn, along with its radius. - Rectangle: - Properties: - length (double): The length of the rectangle. - width (double): The width of the rectangle. - Methods: - Override the draw() method to print a message indicating that a rectangle is being drawn, along with its length and width. - 4. In the main() function, create instances of the Circle and Rectangle classes. - 5. Create an array of pointers to Shape objects and store the addresses of the Circle and Rectangle objects in the array. - 6. Use a loop to iterate through the array and call the draw() method for each object. - Observe how polymorphism allows you to call the appropriate draw() method based on the actual type of the object. - 7. Compile and run the program to verify that the correct messages are printed for each shape. - - Example Output: - Drawing a circle with radius 5.0 - Drawing a rectangle with length 6.0 and width 4.0 - - 8. Challenge: Extend the program by adding more derived classes (e.g., Triangle, Square) - and further explore polymorphism by creating objects of these classes and adding them to the array of shapes. - Update the draw() methods in the derived classes accordingly. -*/ - -// Solution: - - - +}; +class Circle : public Shape{ + private: + double radius; + public: + Circle(string name , double radius) : Shape(name){ + this -> radius = radius; + } + virtual void draw()override{ + Shape :: draw(); + cout << "Circle with its radius is " << radius < width = width; + this -> height = height; + } + virtual void draw()override{ + Shape :: draw(); + cout << "Rectangle with its width is " << width << " and its height is " << height < katet = katet; + this -> hipotenuz = hipotenuz; + } + virtual void draw()override{ + Shape :: draw(); + cout << "Triangle with its katet is " << katet << " and its hipotenuz is " << hipotenuz < side = side; + } + virtual void draw()override{ + Shape :: draw(); + cout << "Square with its side is " << side <draw(); } - return 0; } From cd25998d1bf17b921a8969bfa455baa40d7b4204 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 15:00:02 +0400 Subject: [PATCH 23/38] Update homework-02-library-item-hierarchy.cpp --- .../homework-02-library-item-hierarchy.cpp | 152 +++++++++--------- 1 file changed, 74 insertions(+), 78 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-02-library-item-hierarchy.cpp b/3-POLYMORPHISM/homework/homework-02-library-item-hierarchy.cpp index 5fd6b3d..b8fab11 100644 --- a/3-POLYMORPHISM/homework/homework-02-library-item-hierarchy.cpp +++ b/3-POLYMORPHISM/homework/homework-02-library-item-hierarchy.cpp @@ -1,81 +1,77 @@ -#include -#include - +#include using namespace std; +class LibraryItem{ + private: + string title; + int year; + bool checkedout; + public: + LibraryItem(string title , int year , bool checkedout){ + this -> title = title; + this -> year = year; + this -> checkedout = checkedout; + } + ~LibraryItem(){}; + virtual void checkout(){ + checkedout = true; + } + virtual void checkin(){ + checkedout = false; /* checkout , ve check in funksiyalarinin her hansi bir fealiyyeti yoxdur menim kodumda.Sadece tapsirirqda yazin deyilib deye yazmisam + */ + } + virtual void displayInfo(){ + cout << "Title: " << title << endl; + cout << "Year: " << year << endl; + cout << "Status: " << (checkedout ? "Checked out" : "Checked in") << endl; + } +}; +class Book : public LibraryItem{ + private: + string author; + public: + Book(string title , int year , bool checkedout , string author) : LibraryItem(title , year , checkedout){ + this -> author = author; + } + virtual void displayInfo()override{ + LibraryItem :: displayInfo(); + cout << "Author: " << author << endl; + } + +}; +class EBook : public LibraryItem{ + private: + string format; + public: + EBook(string title , int year , bool checkedout , string format) : LibraryItem(title , year , checkedout){ + this -> format = format; + } + virtual void displayInfo(){ + LibraryItem :: displayInfo(); + cout << "Format: " << format < artist = artist; + } + virtual void displayInfo(){ + LibraryItem :: displayInfo(); + cout << "Artist: " << artist << endl; + } +}; +int main(){ + system("cls"); + Book book1("The Karamazov Brothers" , 1870 , true , "Fyodr Dostoevski"); // burda true - (Checked out un true oldugun gosterir) false ise checked in. + EBook ebook1("Ses" , 1970 , false , "Sabahattin Ali"); + AudioBook audiobook1("Chess" , 1800 , true , "Stefan Zweig"); + LibraryItem * items[] = {&book1 , &ebook1 , &audiobook1}; + for(int i = 0 ; i < 3 ; i++){ + items[i] -> displayInfo(); + cout << "--------------" < Date: Wed, 9 Sep 2026 15:01:14 +0400 Subject: [PATCH 24/38] Update homework-03-polymorphic-methods-theory-question.cpp --- ...mework-03-polymorphic-methods-theory-question.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/3-POLYMORPHISM/homework/homework-03-polymorphic-methods-theory-question.cpp b/3-POLYMORPHISM/homework/homework-03-polymorphic-methods-theory-question.cpp index f256b54..bdabc02 100644 --- a/3-POLYMORPHISM/homework/homework-03-polymorphic-methods-theory-question.cpp +++ b/3-POLYMORPHISM/homework/homework-03-polymorphic-methods-theory-question.cpp @@ -31,6 +31,8 @@ using namespace std; /* Solution: + Burda cavab move() methodudur. Cunki hereket mentiqi motorcycle da ve car da ferqlidir.Diger getter setter methodlar ise saddece qiymet qebul edib qiymet qaytarir. + Umumiyyetle ekser vaxt getter/setter funksiyalari polimorfik olmur.(istisnalar xaric). */ @@ -61,6 +63,9 @@ using namespace std; /* Solution: + Burda cavab calculateTax() , calculateShipping() dir.Bu methodlarin mentiqi butun child klasslarda ferqlidir.Meselen Book klassi olsun bezi olkelerde + kitablardan vergi almirlar bezilerinde alinir.Bezi olkelerde elektronik esyalardan vergi cox alinir bezi lkelrede ise az ve s.Diger getter/setter funksiyalari + ise ancaq qiymet qebul edib qiymet qaytarir. */ @@ -93,6 +98,13 @@ using namespace std; /* Solution: + Burda cavab postContent() , deleteContent() dir. + manageUsers() - polimorfik deyil.Sadece adminstrator sinifine aid olan bir methoddur. + postContent() - post un movzusu meselen regularUser de insanar metn mesaj paylasa bilerler contentCreator sinifinin numayendeleri sekil video paylasa biler. + deleteContent() - bu da child classlard ferqlidir.meselen regular user dekiler oz mesajlarin ve yazdiqlari metni sile bilerler amma content creator lar oz videolarin + sekillerin ve postlarinin altina yazilmis reyleri sile bilerler. + digerleri ise getter/setter methodlaridir ki onlar ancaq melumat qebul edib qaytarirlar.Amma polimorfik olanlar child classlarda coxuzlu ve coxformali olurlar. + yeni temelde eynidiler amma child classlarda ferqli esas emliyyatin ferqli formasin aparirlar. */ From f9925d029cb3b3a3cc297ebb0ac5bba230599232 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 15:01:52 +0400 Subject: [PATCH 25/38] Update homework-04-payment-virtual-methods.cpp --- .../homework-04-payment-virtual-methods.cpp | 71 +++++-------------- 1 file changed, 17 insertions(+), 54 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-04-payment-virtual-methods.cpp b/3-POLYMORPHISM/homework/homework-04-payment-virtual-methods.cpp index 69a31b8..537524b 100644 --- a/3-POLYMORPHISM/homework/homework-04-payment-virtual-methods.cpp +++ b/3-POLYMORPHISM/homework/homework-04-payment-virtual-methods.cpp @@ -1,32 +1,6 @@ -#include -#include - +#include +#include using namespace std; - -/* - Exercise: Decide on Virtual Methods - - You are provided with a payment processing system implemented in C++. - The system includes a base class Payment and three derived classes: CreditCardPayment, - DebitCardPayment, and PayPalPayment. Each payment method has its own unique behavior. - - Your task is to decide which methods should be polymorphic (i.e., override in derived classes) - and modify the code accordingly. - - Follow these steps: - - 1. Review the existing code and identify methods that should be made virtual (polymorphic). - Polymorphic methods are those that have a different implementation in the derived classes - and are related to the specific payment method. - 2. Implement virtual methods in the derived classes by overriding the base class method. - 3. Update the main function to create instances of different payment methods, set payment details, - and process payments using polymorphism. - 4. Test the code to ensure that each payment method behaves correctly and that polymorphism is used effectively. - - Note: You can make any method virtual if it is related to the specific payment method's behavior. - Some methods may not need to be virtual if they have a common implementation across all payment methods. -*/ - class Payment { public: Payment() : amount(0.0), currency("USD"), status("Pending") {} @@ -39,8 +13,9 @@ class Payment { string getCurrency() const { return currency; } string getStatus() const { return status; } - // Decide which methods should be virtual and make them so. - + virtual void ProcessPayment(){ + cout << "Process payment..." << endl; + } virtual ~Payment() {} @@ -49,8 +24,6 @@ class Payment { string currency; string status; }; - - class CreditCardPayment : public Payment { public: CreditCardPayment(const string& cardType) : cardType(cardType) {} @@ -59,15 +32,13 @@ class CreditCardPayment : public Payment { cout << "Authorizing Credit Card Payment of " << getAmount() << " " << getCurrency() << " (Card Type: " << cardType << ")" << endl; setStatus("Authorized"); } - - // Override the base class method if it's virtual - + virtual void ProcessPayment() override{ + authorizePayment(); + } private: string cardType; }; - - class DebitCardPayment : public Payment { public: DebitCardPayment(const string& cardType) : cardType(cardType) {} @@ -76,15 +47,13 @@ class DebitCardPayment : public Payment { cout << "Verifying Funds for Debit Card Payment of " << getAmount() << " " << getCurrency() << " (Card Type: " << cardType << ")" << endl; setStatus("Funds Verified"); } - - // Override the base class method if it's virtual - + virtual void ProcessPayment() override{ + verifyFunds(); + } private: string cardType; }; - - class PayPalPayment : public Payment { public: PayPalPayment(const string& email) : email(email) {} @@ -93,18 +62,15 @@ class PayPalPayment : public Payment { cout << "Executing PayPal Payment of " << getAmount() << " " << getCurrency() << " (Email: " << email << ")" << endl; setStatus("Executed"); } - - // Override the base class method if it's virtual + virtual void ProcessPayment()override{ + executePayment(); + } - private: string email; }; - - -int main() { - - system("clear"); +int main(){ +system("cls"); CreditCardPayment creditCardPayment("Visa"); DebitCardPayment debitCardPayment("Mastercard"); @@ -117,9 +83,6 @@ int main() { Payment* payments[] = { &creditCardPayment, &debitCardPayment, &payPalPayment }; for (Payment* payment : payments) { - // Use polymorphism to process payments - // TODO: + payment -> ProcessPayment(); } - - return 0; } From aa2970959bb66b0f74884f1ee23ab56b58f070fc Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 15:02:22 +0400 Subject: [PATCH 26/38] Update homework-05-employee-polymorphism.cpp --- .../homework-05-employee-polymorphism.cpp | 114 +++++++++--------- 1 file changed, 54 insertions(+), 60 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-05-employee-polymorphism.cpp b/3-POLYMORPHISM/homework/homework-05-employee-polymorphism.cpp index 2909601..7539fa5 100644 --- a/3-POLYMORPHISM/homework/homework-05-employee-polymorphism.cpp +++ b/3-POLYMORPHISM/homework/homework-05-employee-polymorphism.cpp @@ -1,59 +1,56 @@ -#include - -using namespace std; - - -/* - Exercise: Employee Polymorphism - - In this exercise, you are tasked with implementing a basic employee management system in C++. - You will create a class hierarchy for different types of employees, - calculate their salaries based on their roles, and display their information. - - 1. Create a base class Employee with the following attributes and methods: - Attributes: - name (string): The name of the employee. - baseSalary (double): The base salary of the employee. - Methods: - Employee(const string& n, double salary): Constructor to initialize the name and baseSalary. - virtual double calculateSalary() const: - A virtual function to calculate and return the salary based on the base salary. - You can return the baseSalary as the default implementation. - virtual void display() const: A virtual function to display the employee's name and salary. - 2. Create two derived classes, Manager and Developer, which inherit from the Employee class: - Manager: - Add an additional attribute, bonus (double), representing the bonus amount. - Override the calculateSalary() method to calculate the salary as the sum of the base salary and the bonus. - Override the display() method to display "Manager - " followed by the employee's name and salary. - Developer: - Add an additional attribute, numberOfProjects (int), representing the number of projects the developer has completed. - Override the calculateSalary() method to calculate the salary as the sum of the base salary and a bonus of $1000 per completed project. - Override the display() method to display "Developer - " followed by the employee's name and salary. - 3. In the main() function: - Create an array of Employee* pointers to store instances of both Manager and Developer objects. - Create at least two instances of each type of employee, using the constructor to initialize their attributes. - Loop through the array of employee pointers and call the display() method for each employee to display their information. - - 4. Don't forget to deallocate memory for dynamically allocated objects - using delete in the main() function to prevent memory leaks. - - 5. Compile and run the program to verify that polymorphism is working correctly, - and the correct calculateSalary() and display() methods are called for each employee type. - - 6. You have the flexibility to decide the access specifiers (public, private, protected) - for the Employee, Manager, and Developer classes based on your specific requirements. -*/ - - -/* Solution: */ - - - - - -int main() { +#include +using namespace std; +class Employee{ + protected: + string name; + double baseSalary; + public: + Employee(string name , double baseSalary){ + this -> name = name; + this -> baseSalary = baseSalary; + } + virtual double calculateSalary(){ + return baseSalary; + } + virtual void display(){ + cout << "Name: " << name << endl; + cout << "Base Salary: " << baseSalary < bonus = bonus; + } + virtual double calculateSalary()override{ + return baseSalary + bonus; + } + virtual void display()override{ + Employee::display(); + cout << "New salary(it means Total Salary: ) " << calculateSalary() < numberOfProjects = numberOfProjects; + } + + virtual double calculateSalary()override{ + return baseSalary + 1000*numberOfProjects; + } + virtual void display()override{ + Employee::display(); + cout << "Earnings with profits from additional projects: " << calculateSalary() <display(); + employees[i] ->calculateSalary(); } - - // Clean up - - - return 0; } From 2d3b73d419f455d779a01a8b759323b4a179e1ff Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 15:02:58 +0400 Subject: [PATCH 27/38] Update homework-06-backend-service-hierarchy.cpp --- .../homework-06-backend-service-hierarchy.cpp | 99 ++++++++----------- 1 file changed, 41 insertions(+), 58 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-06-backend-service-hierarchy.cpp b/3-POLYMORPHISM/homework/homework-06-backend-service-hierarchy.cpp index 5afb61c..02b0816 100644 --- a/3-POLYMORPHISM/homework/homework-06-backend-service-hierarchy.cpp +++ b/3-POLYMORPHISM/homework/homework-06-backend-service-hierarchy.cpp @@ -1,67 +1,50 @@ -#include -#include - +#include using namespace std; - - -/* - Exercise: Backend Service Hierarchy - - Create a C++ program that models a hierarchy of backend services. - You will define a base class BackendService with two methods: connect() and performTask(). - Then, create two derived classes, DatabaseService and APIService, each with their own implementations of these methods. - Finally, introduce method overloading and method hiding in the derived classes. - - Here are the steps to complete the exercise: - - 1. Define a base class BackendService with the following methods: - - void connect(): This method should print a message indicating that it's connected to a generic backend service. - - virtual void performTask(): This method should print a message indicating that it's performing a generic task. - - 2. Create a derived class DatabaseService that inherits from BackendService. - In the DatabaseService class: - - Overload the connect() method to accept a std::string parameter connectionString. Print a message indicating that it's connected to a database with the given connection string. - - Override the performTask() method to print a message indicating that it's performing a database-specific task. - - 3. Create a derived class APIService that inherits from BackendService. - In the APIService class: - - Overload the connect() method to accept a std::string parameter apiKey. - Print a message indicating that it's connected to an API with the given API key. - - Override the performTask() method to print a message indicating that it's performing an API-specific task. - - Introduce method hiding by adding a new connect() method without parameters. - In this method, print a message indicating that it's connected to an API without an API key. - - 4. In the main() function: - - Create instances of BackendService, DatabaseService, and APIService. - - Call the connect() and performTask() methods on each of these instances - to observe method overloading, overriding, and method hiding. - - Your program should demonstrate the different behaviors of these methods based on the class hierarchy. -*/ - - -/* Solution: */ - - - - -int main() { - - /* Example Usage */ +class BackendService{ + public: + void connect(){ + cout << "Connected..." < Date: Wed, 9 Sep 2026 15:03:47 +0400 Subject: [PATCH 28/38] Update homework-07-banking-system.cpp --- .../homework/homework-07-banking-system.cpp | 148 ++++++++---------- 1 file changed, 67 insertions(+), 81 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-07-banking-system.cpp b/3-POLYMORPHISM/homework/homework-07-banking-system.cpp index 522410a..2653953 100644 --- a/3-POLYMORPHISM/homework/homework-07-banking-system.cpp +++ b/3-POLYMORPHISM/homework/homework-07-banking-system.cpp @@ -1,89 +1,75 @@ -#include -#include - +#include using namespace std; - -/* - Exercise: Implement a Banking System - - In this exercise, you will create a basic banking system with the following classes: - - 1. Account (Base Class): - Create a base class called Account with the following attributes and methods: - - accountNumber (integer) - - balance (double) - - Account(const int accountNumber, const double balance) constructor. - - A virtual destructor for proper resource cleanup. - - virtual void deposit(double amount) method to deposit funds into the account. - - virtual void withdraw(double amount) method to withdraw funds from the account. - - virtual void displayBalance() method to display the current balance. - - 2. SavingsAccount (Derived Class): - Create a derived class called SavingsAccount that inherits from Account. This class should include: - - A constructor that takes an account number, initial balance, and an interest rate (e.g., 3%). - - An overridden displayBalance() method that displays the current balance along with the interest rate. - - An overridden withdraw() method that checks if the withdrawal amount is less than the balance and, if so, - processes the withdrawal. If the withdrawal amount exceeds the balance, display an error message. - 3. CheckingAccount (Derived Class): - - Create another derived class called CheckingAccount that inherits from Account. This class should include: - - A constructor that takes an account number and initial balance. - - An overridden displayBalance() method that displays the current balance along with a message indicating it's a checking account. - - An overridden withdraw() method that checks if the withdrawal amount is less than the balance and, if so, - processes the withdrawal. If the withdrawal amount exceeds the balance, display an error message. - 4. Main Function: - - In the main() function, create instances of both SavingsAccount and CheckingAccount. - - Deposit and withdraw funds from these accounts, and display their balances to demonstrate polymorphism. - - 5. Proper Cleanup: - - Make sure to delete the account objects at the end of the main() function to ensure that their destructors are called. -*/ - - -class Account { +class Account{ + protected: + int AccountNumber; + double balance; public: - // Constructor, virtual destructor, and methods go here - - + Account(int AccountNumber , double balance){ + this -> AccountNumber = AccountNumber; + this -> balance = balance; + } + virtual void deposit(double amount){ + balance = balance + amount; + } + virtual void withdraw(double amount){ + if(amount > 0 && amount <= balance){ + balance = balance - amount; + } + else{ + cout << "Invalid amount" < InterestRate = InterestRate; + } + virtual void displayBalance()override{ + Account :: displayBalance(); + cout << "Total balance(it means with inherit): " << balance + balance*(InterestRate/100) < withdraw(500.9); + accounts[1] -> deposit(450.3); + accounts[0] -> deposit(65.7); + accounts[1] -> withdraw(7000.8); + for(int i = 0 ; i < 2 ; i++){ + accounts[i] -> displayBalance(); + } + for(int i = 0 ; i<2 ;i++){ + delete accounts[i]; + } + + + + } From 4fad486c10126a4ccfee2507e46441a4cd2baf07 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 15:05:04 +0400 Subject: [PATCH 29/38] Update homework-08-static-keyword-stock-tracker.cpp --- ...mework-08-static-keyword-stock-tracker.cpp | 251 ++++++++---------- 1 file changed, 112 insertions(+), 139 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-08-static-keyword-stock-tracker.cpp b/3-POLYMORPHISM/homework/homework-08-static-keyword-stock-tracker.cpp index c66fda0..d7b97ab 100644 --- a/3-POLYMORPHISM/homework/homework-08-static-keyword-stock-tracker.cpp +++ b/3-POLYMORPHISM/homework/homework-08-static-keyword-stock-tracker.cpp @@ -1,148 +1,121 @@ -#include -#include - +#include +#include +#include +#include using namespace std; +/*double trackStockPrice(string symbol , double currentPrice){ + static mapHighestPrice; + if(currentPrice > HighestPrice[symbol]){ + HighestPrice[symbol] = currentPrice; + } + cout << "The highest price of stock name is: " << symbol << " and its highest price is: "; + return HighestPrice[symbol]; - -/* - Static Keyword in C++ -*/ - - -/* - Exercise-1: Stock Price Tracker - - Write a C++ program that simulates a stock price tracker function. - The stock price tracker function should have the following properties: - - 1. Create a function named trackStockPrice that takes the stock symbol (a string) and the current stock price (a double) as parameters. - 2. Inside the function, maintain a static local variable that stores the highest stock price observed for a given stock symbol. - 3. Update the highest stock price if the current price is higher. - 4. The function should return the highest stock price observed for the given stock symbol. - - -*/ -double trackStockPrice(string symbol, double currentPrice) { - // your code -} - - -/* - Exercise-2: Bank Account Management - - Create a C++ program that models a simplified bank account management system. - In this system, you will create a BankAccount class with the following features: - - 1. Each BankAccount object should have a unique account number that starts from 1001 and increments by 1 for each new account created. - 2. Each account should have an account balance. - 3. Implement methods to deposit and withdraw funds from the account. - 4. Implement a method to display the account details, including the account number and balance. -*/ -class BankAccount { - // your code }; +int main(){ + system("cls"); + cout << trackStockPrice("Etherium" , 800) < balance = balance; + AccountNumber = nextAccountNumber; + nextAccountNumber++; + } + ~Account(){ + nextAccountNumber--; + } + void withdraw(double amount){ + if(balance > amount && amount > 0){ + balance = balance - amount; + } + else{ + cout << "Invalid amount" < 0){ + balance = balance + amount; + } + else{ + cout << "Invalid amount" <GetPrimes(int number){ + static vectorprimes; + for(int num = 2 ; num <= number ; num++){ + bool IsPrime = true; + for(int i = 2 ; iprimes = GetPrimes(100); + for(int x : primes){ + cout << x << " "; + } +}*/ - - - - - - - - -int main() { - - // Exercise-1: example usage - double price1 = trackStockPrice("AAPL", 150.25); - cout << "Highest AAPL Stock Price: $" << price1 << endl; - - double price2 = trackStockPrice("GOOGL", 2700.50); - cout << "Highest GOOGL Stock Price: $" << price2 << endl; - - double price3 = trackStockPrice("AAPL", 155.75); - cout << "Highest AAPL Stock Price: $" << price3 << endl; - - double price4 = trackStockPrice("TSLA", 800.00); - cout << "Highest TSLA Stock Price: $" << price4 << endl; - - - - // Exercise-2: example usage - BankAccount account1; - account1.deposit(1000); - account1.withdraw(500); - account1.displayAccountDetails(); - - BankAccount account2; - account2.deposit(1500); - account2.displayAccountDetails(); - - // Display the total number of accounts created. - cout << "Total Accounts Created: " << BankAccount::totalAccounts << endl; - - - - // Exercise-3: example usage - // your code ;-) - - - - // Exercise-4: example usage - // your code ;-) - - -} \ No newline at end of file From b839d38a4f1d423664857d944eb43202bf0e612f Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 15:06:06 +0400 Subject: [PATCH 30/38] Update homework-09-static-members-late-fees.cpp --- .../homework-09-static-members-late-fees.cpp | 35 ++++++++++--------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-09-static-members-late-fees.cpp b/3-POLYMORPHISM/homework/homework-09-static-members-late-fees.cpp index c9f24d7..dbce155 100644 --- a/3-POLYMORPHISM/homework/homework-09-static-members-late-fees.cpp +++ b/3-POLYMORPHISM/homework/homework-09-static-members-late-fees.cpp @@ -23,20 +23,23 @@ using namespace std; class LibraryItem { public: - LibraryItem(const string& title) : title(title) {} + LibraryItem(const string& title ) : title(title) { + } virtual double calculateLateFee(int daysLate) const = 0; virtual void displayInfo() const { - cout << "Title: " << title << std::endl; + cout << "Title: " << title << endl; } // Add a static member to keep track of the total library items // your code ... + static double totalItems; protected: string title; }; +double LibraryItem::totalItems = 0; // Define the static member totalItems for the LibraryItem class here // Initialize it to 0. @@ -44,12 +47,11 @@ class LibraryItem { class Book : public LibraryItem { public: Book(const string& title, const string& author) : LibraryItem(title), author(author) { - // Increment the totalItems count for each book added. - // Hint: Use the static member of the LibraryItem class. + totalItems++; } double calculateLateFee(int daysLate) const override { - // Implement the late fee calculation for books. + return daysLate*2; } void displayInfo() const override { @@ -64,12 +66,11 @@ class Book : public LibraryItem { class DVD : public LibraryItem { public: DVD(const string& title, int duration) : LibraryItem(title), duration(duration) { - // Increment the totalItems count for each DVD added. - // Hint: Use the static member of the LibraryItem class. + totalItems++; } double calculateLateFee(int daysLate) const override { - // Implement the late fee calculation for DVDs. + return daysLate*3; } void displayInfo() const override { @@ -83,11 +84,13 @@ class DVD : public LibraryItem { int main() { - // Create instances of Book and DVD and test their functionality. - // Hint: Create Book and DVD objects, display their information, and calculate late fees. - - // Display the total number of library items using the static member totalItems. - // Hint: Access the totalItems static member from the LibraryItem class. - - return 0; -} \ No newline at end of file + Book book1("The Karamazov Brothers" , "Feodor Dostoevski"); + DVD dvd1("Oxford listening DVD" , 7); + book1.calculateLateFee(10); + dvd1.calculateLateFee(8); + book1.displayInfo(); + dvd1.displayInfo(); + cout << "Total Item " << LibraryItem::totalItems << endl; + cout << "Book Late fee: " << book1.calculateLateFee(3) << endl; + cout << "DVD Late fee: " << dvd1.calculateLateFee(7) << endl; +} From a2e876c79d1ea0a3d19afb3ca6ce07530643c408 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 15:07:34 +0400 Subject: [PATCH 31/38] Update homework-10-static-members-shape-areas.cpp --- ...homework-10-static-members-shape-areas.cpp | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-10-static-members-shape-areas.cpp b/3-POLYMORPHISM/homework/homework-10-static-members-shape-areas.cpp index 5bd7038..744b64c 100644 --- a/3-POLYMORPHISM/homework/homework-10-static-members-shape-areas.cpp +++ b/3-POLYMORPHISM/homework/homework-10-static-members-shape-areas.cpp @@ -24,24 +24,33 @@ using namespace std; class Shape { public: - // Static method to compare the areas of two shapes - // Hint: You'll need to access the CalculateArea static methods in the derived classes. + static bool CompareAreas(double area1 , double area2){ + if(area1 == area2){ + return true; + } + else{ + return false; + } + } }; class Circle : public Shape { public: + double radius; Circle(double radius) : radius(radius) {} - - // Static method to calculate the area of a circle - // Hint: Use the formula for calculating the area of a circle (A = π * r^2) + static double CalculateArea(double radius , const double pi = 3.14){ + return pi*radius*radius; + } }; class Rectangle : public Shape { public: + double width; + double height; Rectangle(double width, double height) : width(width), height(height) {} - - // Static method to calculate the area of a rectangle - // Hint: Use the formula for calculating the area of a rectangle (A = width * height) + static double CalculateArea(double width , double height){ + return width*height; + } }; int main() { @@ -53,9 +62,12 @@ int main() { cout << "Enter the width and height of a rectangle: "; cin >> rectWidth >> rectHeight; - // Calculate and display the areas using the static methods + double CircleArea = Circle::CalculateArea(circleRadius); + double RectArea = Rectangle::CalculateArea(rectWidth , rectHeight); + cout << "Circle Area: " << CircleArea < Date: Wed, 9 Sep 2026 15:08:13 +0400 Subject: [PATCH 32/38] Update homework-11-user-hierarchy-levels.cpp --- .../homework-11-user-hierarchy-levels.cpp | 75 ++++++++++++------- 1 file changed, 46 insertions(+), 29 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-11-user-hierarchy-levels.cpp b/3-POLYMORPHISM/homework/homework-11-user-hierarchy-levels.cpp index b4564a8..4155504 100644 --- a/3-POLYMORPHISM/homework/homework-11-user-hierarchy-levels.cpp +++ b/3-POLYMORPHISM/homework/homework-11-user-hierarchy-levels.cpp @@ -4,38 +4,55 @@ using namespace std; -/* - Polymorphism - - 11. Inheritance and Polymorphism at different levels -*/ - - -/* - Exercise: Enhancing User Hierarchy - - 1. Create a ModeratorUser class: - Create a new class ModeratorUser that inherits from AdminUser. - A moderator user has the ability to moderate content. - 2. Create a ManagerUser class: - Create a new class ManagerUser that inherits from AdminUser. - A manager user has the ability to manage users. - 3. Implement new functions: - ~ Add a new virtual function in User called viewProfile that prints a message like "Viewing the profile of [username]." - ~ Add a new virtual function in SiteUser called postComment that prints a message like "Comment posted by [username]." - ~ Add a new virtual function in ModeratorUser called moderateContent that prints a message like "Content moderated by [username]." - ~ Add a new virtual function in ManagerUser called manageUsers that prints a message like "Users managed by [username]." - 4. Compile and run your program: Make sure it compiles and runs without errors. -*/ - - - -/* - Solution -*/ +class User{ + protected: + string name; + public: + User(string name){ + this -> name = name; + } + virtual void login(){ + cout << "Login" << endl; + } + virtual void logout(){ + cout << "Logout..." << endl; + } + virtual void performAction(){ + cout << "Perform Action...." < Date: Wed, 9 Sep 2026 16:39:54 +0400 Subject: [PATCH 33/38] Update homework-12-final-keyword-authenticator.cpp --- ...omework-12-final-keyword-authenticator.cpp | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-12-final-keyword-authenticator.cpp b/3-POLYMORPHISM/homework/homework-12-final-keyword-authenticator.cpp index 3a903c8..03da4bd 100644 --- a/3-POLYMORPHISM/homework/homework-12-final-keyword-authenticator.cpp +++ b/3-POLYMORPHISM/homework/homework-12-final-keyword-authenticator.cpp @@ -19,7 +19,7 @@ using namespace std; */ // Base class for user authentication -class Authenticator { +class Authenticator{ public: // TODO: Declare a pure virtual function for authentication virtual bool authenticate(const string& username, const string& password) const = 0; @@ -27,7 +27,7 @@ class Authenticator { // TODO: Decide whether to mark the following class as final or not -class BasicAuthenticator : public Authenticator { +class BasicAuthenticator final : public Authenticator{ public: BasicAuthenticator(const string& validUsername, const string& validPassword) : validUsername_(validUsername), validPassword_(validPassword) {} @@ -44,13 +44,18 @@ class BasicAuthenticator : public Authenticator { // TODO: Create a derived class (you can name it CustomAuthenticator) that attempts to extend BasicAuthenticator // Uncommenting the following lines should result in a compilation error if BasicAuthenticator is marked as final -/* - class CustomAuthenticator : public BasicAuthenticator { + + /*class CustomAuthenticator : public BasicAuthenticator { public: CustomAuthenticator(const string& validUsername, const string& validPassword) : BasicAuthenticator(validUsername, validPassword) {} - }; -*/ + };*/ + + /*BasicAuthenticator bu sinifin qarsisina final acar sozu yazilanda ondan inherit etmek mumkun olmur.ona gore de yeni yazilan CustomAuthenticator + klassi da xeta verecek.Main hissede yaazilmis obyektde xeta verecek cunki hemin obyekt BasicAuthenticatordan inherit etmeye calisir.Amma final class + olmasa ondan inherit etmek mumkun olan main hissede yazdigimiz obyektde mumkun olar ve her sey problemsiz isleyer.*/ + + int main() { @@ -66,15 +71,15 @@ int main() { // TODO: Create an instance of CustomAuthenticator (if allowed) and attempt authentication - /* - CustomAuthenticator customAuth("user", "pass"); + + /*CustomAuthenticator customAuth("user", "pass"); if (customAuth.authenticate("user", "pass")) { cout << "Authentication successful!" << endl; } else { cout << "Authentication failed!" << endl; } - */ + */ return 0; } From d959226d453f4b56e7f8beea3a2cbe704724044a Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 17:00:47 +0400 Subject: [PATCH 34/38] Update homework-13-final-keyword-database-connection-factory.cpp --- ...al-keyword-database-connection-factory.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-13-final-keyword-database-connection-factory.cpp b/3-POLYMORPHISM/homework/homework-13-final-keyword-database-connection-factory.cpp index 59ec22d..840e935 100644 --- a/3-POLYMORPHISM/homework/homework-13-final-keyword-database-connection-factory.cpp +++ b/3-POLYMORPHISM/homework/homework-13-final-keyword-database-connection-factory.cpp @@ -18,12 +18,13 @@ using namespace std; // Base class representing a database connection class DatabaseConnection { public: + virtual ~DatabaseConnection() = default; // Establishes a connection to the database virtual void connect() const = 0; }; // TODO: Decide whether to mark the following class as final or not -class MySqlConnection : public DatabaseConnection { +class MySqlConnection final : public DatabaseConnection { public: void connect() const override { cout << "Connecting to MySQL database..." << endl; @@ -32,7 +33,7 @@ class MySqlConnection : public DatabaseConnection { }; // TODO: Decide whether to mark the following class as final or not -class PostgresConnection : public DatabaseConnection { +class PostgresConnection final : public DatabaseConnection { public: void connect() const override { cout << "Connecting to PostgreSQL database..." << endl; @@ -45,15 +46,16 @@ class ConnectionFactory { public: // TODO: Decide whether to mark the following methods as static or not // Factory method to create a MySQL connection - DatabaseConnection* createMySQLConnection() { + static DatabaseConnection* createMySQLConnection() { return new MySqlConnection(); } // Factory method to create a PostgreSQL connection - DatabaseConnection* createPostgresConnection() { + static DatabaseConnection* createPostgresConnection() { return new PostgresConnection(); } -}; +}; // Bu methodlari static etmek mentiqlidir cunki hem main hissede kodu sadelesdirmek olar obyekt yaratmamis bir basa cagirmaq mumkun olar.Hemde onun meberi yoxdu +// sadece PostgreConnection() ve ya MySqlConnection() baglantisini qaytaran bir nov servis funksiyasidir. int main() { @@ -62,10 +64,13 @@ int main() { ConnectionFactory factory; DatabaseConnection* mysqlConnection = factory.createMySQLConnection(); DatabaseConnection* postgresConnection = factory.createPostgresConnection(); + DatabaseConnection* postgresConnection1 = factory.createMySQLConnection(); + ConnectionFactory::createMySQLConnection(); // bele de cagirmaq olar meselen daha sade // TODO: Decide whether to uncomment the following lines to delete instances - // delete mysqlConnection; - // delete postgresConnection; + delete mysqlConnection; + delete postgresConnection; + delete postgresConnection1; return 0; } From 2c5ae9b6aa8da953240fc79ebab745093f48cd10 Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 18:06:04 +0400 Subject: [PATCH 35/38] Update homework-14-abstract-data-storage-provider.cpp --- ...work-14-abstract-data-storage-provider.cpp | 75 +++++-------------- 1 file changed, 20 insertions(+), 55 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-14-abstract-data-storage-provider.cpp b/3-POLYMORPHISM/homework/homework-14-abstract-data-storage-provider.cpp index fe30b97..30ead6f 100644 --- a/3-POLYMORPHISM/homework/homework-14-abstract-data-storage-provider.cpp +++ b/3-POLYMORPHISM/homework/homework-14-abstract-data-storage-provider.cpp @@ -2,73 +2,38 @@ #include using namespace std; - -/* - Polymorphism - - 14. Pure virtual functions and Abstract classes -*/ - - -/* - Problem Statement: - You are tasked with designing a system that can store data using different data storage mechanisms in a web backend. - Create a C++ program that demonstrates the use of an abstract class to model different types of data storage providers. - - 1. Create an abstract class DataStorageProvider with the following features: - A pure virtual function storeData that takes a string parameter representing the data to be stored. - 2. Implement two concrete subclasses of DataStorageProvider: - RelationalDatabaseStorage: Implement the storeData function to display a message indicating that the data is being stored in a relational database. - CloudNoSQLStorage: Implement the storeData function to display a message indicating that the data is being stored in a cloud-based NoSQL database. - 3. Implement a common functionality in the abstract class DataStorageProvider: - Add a function logStorageAttempt that takes a string parameter representing - the data and displays a message indicating that a storage attempt for the given data has been logged. - 4. In the main function, create instances of both RelationalDatabaseStorage and CloudNoSQLStorage. - Use these instances to demonstrate: - Logging storage attempts for different data. - Storing data using each storage provider. -*/ - - -// Abstract class representing a data storage provider class DataStorageProvider { public: - // TODO: Add a pure virtual function to store data - - // TODO: Add a common function to log storage attempts + int attemp = 0; + virtual void storeData(string name) const = 0; + void logStorageAttempt(string name){ + cout << "Storage attempt for data: " << name << " logged." << endl; + } }; - -// Concrete subclass for storing data in a relational database class RelationalDatabaseStorage : public DataStorageProvider { public: - // TODO: Implement the storeData function + void storeData(string name) const override{ + cout << "Storing data in a relational database: " << name < Date: Wed, 9 Sep 2026 19:53:56 +0400 Subject: [PATCH 36/38] Update homework-15-abstract-payment-provider.cpp --- .../homework-15-abstract-payment-provider.cpp | 86 ++++++------------- 1 file changed, 25 insertions(+), 61 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-15-abstract-payment-provider.cpp b/3-POLYMORPHISM/homework/homework-15-abstract-payment-provider.cpp index d513093..a120901 100644 --- a/3-POLYMORPHISM/homework/homework-15-abstract-payment-provider.cpp +++ b/3-POLYMORPHISM/homework/homework-15-abstract-payment-provider.cpp @@ -1,72 +1,36 @@ -#include -#include - +#include using namespace std; - -/* - Polymorphism - - 14. Pure virtual functions and Abstract classes -*/ - - -/* - Problem Statement: - You are tasked with designing a system that can process payments using different payment methods in a web backend. - Create a C++ program that demonstrates the use of an abstract class to model different types of payment providers. - - Requirements: - - 1. Create an abstract class PaymentMethod with the following features: - Payment Processing Method: Include a method processPayment with a double parameter representing the amount to be processed. - - 2. Implement two concrete subclasses of PaymentMethod: - CreditCardPayment: Implement the processPayment function to display a message indicating that the payment is being processed using a credit card. - PayPalPayment: Implement the processPayment function to display a message indicating that the payment is being processed using PayPal. - - 3. Extend the PaymentMethod abstract class by adding the following common functionality: - Payment Attempt Logging: Implement a method logPaymentAttempt that takes a double parameter representing the payment amount and displays a message indicating that a payment attempt for the given amount has been logged. - - 4. In the main function, create instances of both CreditCardPayment and PayPalPayment. - Use these instances to demonstrate: - Logging payment attempts for different amounts. - Processing payments using each payment method. - - Note: - Consider which methods should be pure virtual functions based on the commonality and variability among payment methods. - Think about the common functionality that can be shared among different payment methods. -*/ - - - -// Abstract class representing a payment method -class PaymentMethod { +class PaymentMethod{ public: - // TODO: Add a pure virtual function to process payment + virtual void ProcessPayment(double payment) = 0; + virtual ~PaymentMethod(){} + void logPaymentAttempt(double payment){ + cout << "Payment attempt logged for amount: " << payment << endl; + } - // TODO: Add a common function to log payment attempts }; - -// Concrete subclass for processing credit card payments -class CreditCardPayment : public PaymentMethod { +class CreditCardPayment : public PaymentMethod{ public: - // TODO: Implement the processPayment function -}; + void ProcessPayment(double amount)override{ + cout << "Payment with credit card: " << amount << endl; + } -// Concrete subclass for processing PayPal payments -class PayPalPayment : public PaymentMethod { - public: - // TODO: Implement the processPayment function }; +class PayPalPayment : public PaymentMethod{ + public: + void ProcessPayment(double amount)override{ + cout << "Payment with paypal: " << amount << endl; + } +}; +int main(){ + CreditCardPayment credit1; + PayPalPayment paypal1; + credit1.logPaymentAttempt(100); + credit1.ProcessPayment(100); + cout << "------------" < Date: Wed, 9 Sep 2026 20:20:52 +0400 Subject: [PATCH 37/38] Update homework-16-backend-storage-interface.cpp --- .../homework-16-backend-storage-interface.cpp | 75 +++++++------------ 1 file changed, 28 insertions(+), 47 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-16-backend-storage-interface.cpp b/3-POLYMORPHISM/homework/homework-16-backend-storage-interface.cpp index 6272dcd..ae9a6ea 100644 --- a/3-POLYMORPHISM/homework/homework-16-backend-storage-interface.cpp +++ b/3-POLYMORPHISM/homework/homework-16-backend-storage-interface.cpp @@ -1,72 +1,53 @@ -#include -#include - +#include +#include using namespace std; -/* - Polymorphism - - 15. Abstract Classes as Interfaces -*/ - -/* - Exercise: Backend Data Storage Interface - - Instructions: - - 1. Define an abstract interface named DataStorage with the following pure virtual functions: - void storeData(const string& data): This function should represent storing data. - string retrieveData(): This function should represent retrieving data. - Implement two concrete classes that inherit from the DataStorage interface: - - 2. FileStorage: Implement the functions to store and retrieve data using a file. - DatabaseStorage: Implement the functions to store and retrieve data using a database. - In the main function: - - 3. Create an instance of FileStorage, store and retrieve some data. - 4. Create an instance of DatabaseStorage, store and retrieve some data. -*/ - - -// Abstract interface for data storage class DataStorage { - // TODO: Declare pure virtual functions for storing and retrieving data - virtual ~DataStorage() {} // Virtual destructor + public: + virtual ~DataStorage() {} + virtual void storeData(string data) = 0; + virtual string retrieveData() = 0; }; - -// Concrete class implementing data storage using a file class FileStorage : public DataStorage { - // TODO: Implement functions to store and retrieve data using a file - - // Virtual destructor + private: + string fileData; + + public: + void storeData(string data) override { + fileData = data; + cout << "using file: " << data << endl; + } + string retrieveData() override { + return fileData; + } ~FileStorage() { cout << "FileStorage Destructor" << endl; } }; - -// Concrete class implementing data storage using a database class DatabaseStorage : public DataStorage { - // TODO: Implement functions to store and retrieve data using a database - - // Virtual destructor + private: + string dbData; + + public: + void storeData(string data) override { + dbData = data; + cout << "using database: " << data << endl; + } + string retrieveData() override { + return dbData; + } ~DatabaseStorage() { cout << "DatabaseStorage Destructor" << endl; } }; - int main() { - - // Example usage of the DataStorage interface - - // Using FileStorage FileStorage fileStorage; fileStorage.storeData("FileStorage Data"); cout << "FileStorage: " << fileStorage.retrieveData() << endl; - // Using DatabaseStorage DatabaseStorage databaseStorage; databaseStorage.storeData("DatabaseStorage Data"); cout << "DatabaseStorage: " << databaseStorage.retrieveData() << endl; From ca63910dacd9bba1b2315bae18082f3c102af7cb Mon Sep 17 00:00:00 2001 From: samxalpolad66 Date: Wed, 9 Sep 2026 21:11:33 +0400 Subject: [PATCH 38/38] Update homework-17-abstract-shape-interface.cpp --- .../homework-17-abstract-shape-interface.cpp | 103 +++++++++--------- 1 file changed, 53 insertions(+), 50 deletions(-) diff --git a/3-POLYMORPHISM/homework/homework-17-abstract-shape-interface.cpp b/3-POLYMORPHISM/homework/homework-17-abstract-shape-interface.cpp index 02462c3..3986d0c 100644 --- a/3-POLYMORPHISM/homework/homework-17-abstract-shape-interface.cpp +++ b/3-POLYMORPHISM/homework/homework-17-abstract-shape-interface.cpp @@ -2,55 +2,59 @@ #include using namespace std; - -/* - Polymorphism - - 15. Abstract Classes as Interfaces -*/ - - -/* - Exercise: Shape Hierarchy Design - - Instructions: - - 1. Identify Common Functionality: - Analyze the scenario involving shapes, drawing, and resizing. - Identify functionalities common to all shapes. These will go into the Shape interface. - 2. Consider Partial Implementation: - Determine if there are functionalities common to all drawable shapes that can be partially implemented. - If yes, create an abstract class named DrawableShape that extends the Shape interface and provides a partial implementation. - 3. Implement Concrete Classes: - Implement concrete classes (e.g., Circle and Square) that inherit from either the Shape interface or the DrawableShape abstract class. - 4. Virtual Destructors: - Ensure proper cleanup by adding virtual destructors where necessary. - 5. Demonstrate Usage: - In the main function, create instances of concrete classes and demonstrate the use of the interface or abstract class methods. - - Tips: - Tip 1: Think about functionalities that are common among all shapes and should be defined in an interface. - Tip 2: Consider functionalities that can have a partial implementation common to all drawable shapes; create an abstract class if necessary. - Tip 3: Implement concrete classes based on your design, ensuring they inherit from the appropriate interface or abstract class. - Tip 4: Use virtual destructors where necessary for proper cleanup. - Tip 5: In the main function, create instances of concrete classes and demonstrate the use of the interface or abstract class methods. - - Note: - The goal is to reinforce the understanding of when to use interfaces and abstract classes in a class hierarchy representing shapes and their behaviors. -*/ - - -// Starter Code: - -// TODO: Identify common functionalities for the Shape interface - - -// TODO: Consider partial implementation in an abstract class named DrawableShape - - -// TODO: Implement concrete classes (e.g., Circle and Square) inheriting from the interface or abstract class - - +class Shape{ + public: + virtual void draw() = 0; + virtual double calculateArea() = 0; + virtual void resize(double val) = 0; + +}; +class DrawableShape : public Shape{ + public: + void draw()override{ + cout << "Drawing: "; + } +}; +class Square : public DrawableShape{ + private: + double side; + public: + void resize(double val)override{ + side = side * val; + } + void draw()override{ + DrawableShape::draw(); + cout << " square" << endl; + } + Square(double side){ + this -> side = side; + } + virtual ~Square(){} + double calculateArea()override{ + return side*side; + } +}; +class Circle : public DrawableShape{ + private: + double radius; + public: + void resize(double val)override{ + radius = radius * val; + } + void draw()override{ + DrawableShape::draw(); + cout << " circle" <radius = radius; + } + const double pi = 3.14; + virtual ~Circle(){} + double calculateArea()override{ + return pi*radius*radius; + } + +}; int main() { // Tip 4: Demonstrate the use of the interface or abstract class @@ -71,4 +75,3 @@ int main() { return 0; } -