Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

Programming FUndamentals

Assignment no 10

Name: Muhammad Ali Afzal

Roll no: 23F-0594

Submitted to: Sir Hanan Farooq


Task 1:
#include <iostream>
#include <string>

using namespace std;

struct Book {
string title;
string author;
int publicationYear;
double price;
};

void sortBooksByPriceDescending(Book books[], int size) {


for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (books[j].price < books[j + 1].price) {

Book temp = books[j];


books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}

void displayBooks(Book books[], int size) {


double totalCost = 0.0;
cout << "Books sorted by price in descending order:\n";
cout << "------------------------------------------\n";
for (int i = 0; i < size; ++i) {
cout << "Title: " << books[i].title << endl;
cout << "Author: " << books[i].author << endl;
cout << "Publication Year: " << books[i].publicationYear << endl;
cout << "Price: $" << books[i].price << endl;
totalCost += books[i].price;
cout << "------------------------------------------\n";
}
cout << "Total cost of all books: $" << totalCost << endl;
}

int main() {
const int MAX_BOOKS = 50;
Book books[MAX_BOOKS];
int numBooks;

cout << "Enter the number of books (up to 50): ";


cin >> numBooks;
if (numBooks > MAX_BOOKS || numBooks < 1) {
cout << "Invalid number of books entered. Exiting...\n";
return 1;
}

cout << "Enter book details (title, author, publication year, price):\n";
for (int i = 0; i < numBooks; ++i) {
cout << "Book " << i + 1 << ":\n";
cout << "Title: ";
cin.ignore();
getline(cin, books[i].title);
cout << "Author: ";
getline(cin, books[i].author);
cout << "Publication Year: ";
cin >> books[i].publicationYear;
cout << "Price: $";
cin >> books[i].price;
}

sortBooksByPriceDescending(books, numBooks);

displayBooks(books, numBooks);

return 0;
}
Output:

Task 2:
#include <iostream>
#include <string>

using namespace std;

struct Employee {
string name;
int age;
string address;
float salary;
};
void calculateTax(Employee& emp) {
float taxRate;

if (emp.salary < 50000) {


taxRate = 0.10f;
}
else if (emp.salary >= 50000 && emp.salary <= 100000) {
taxRate = 0.15f;
}
else {
taxRate = 0.20f;
}

float taxAmount = emp.salary * taxRate;


emp.salary -= taxAmount;
}

void displayEmployeeInfo(const Employee& emp) {


cout << "Employee Information:\n";
cout << "---------------------\n";
cout << "Name: " << emp.name << endl;
cout << "Age: " << emp.age << endl;
cout << "Address: " << emp.address << endl;
cout << "Salary: $" << emp.salary << endl;
}

int main() {
Employee emp;

cout << "Enter employee information:\n";


cout << "Name: ";
getline(cin, emp.name);
cout << "Age: ";
cin >> emp.age;
cin.ignore();
cout << "Address: ";
getline(cin, emp.address);
cout << "Salary: $";
cin >> emp.salary;

calculateTax(emp);

displayEmployeeInfo(emp);

return 0;
}
Output:
Task 3:
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

// Structure for Student


struct Student {
string name;
string CNIC;
char gender;
float CGPA;
};

// Structure for Section


struct Section {
Student students[40];
int numStudents;
string sectionName;
string classTeacherName;
};

// Function to add a student to a section


void addStudentToSection(Section& section, const Student& student) {
if (section.numStudents < 40) {
section.students[section.numStudents++] = student;
}
else {
cout << "Section is full. Cannot add more students.\n";
}
}

// Function to display students of a section


void displaySectionStudents(const Section& section) {
cout << "Students in Section " << section.sectionName << " (Class Teacher: " << section.classTeacherName << "):\n";
cout << "-----------------------------------------------------------\n";
for (int i = 0; i < section.numStudents; ++i) {
cout << "Name: " << section.students[i].name << endl;
cout << "CNIC: " << section.students[i].CNIC << endl;
cout << "Gender: " << section.students[i].gender << endl;
cout << "CGPA: " << section.students[i].CGPA << endl;
cout << "-----------------------------------------------------------\n";
}
}

// Function to sort students in a section based on CGPA


void sortStudentsByCGPA(Section& section) {
sort(section.students, section.students + section.numStudents, [](const Student& a, const Student& b) {
return a.CGPA > b.CGPA;
});
}

// Function to update student's CGPA


void updateStudentCGPA(Section sections[], int numSections, const string& studentName, const string& studentCNIC,
float newCGPA) {
for (int i = 0; i < numSections; ++i) {
for (int j = 0; j < sections[i].numStudents; ++j) {
if (sections[i].students[j].name == studentName && sections[i].students[j].CNIC == studentCNIC) {
sections[i].students[j].CGPA = newCGPA;
cout << "CGPA updated successfully.\n";
return;
}
}
}
cout << "Student not found.\n";
}

int main() {
const int MAX_SECTIONS = 10;
Section sections[MAX_SECTIONS];
int numSections = 0;

int choice;
do {
cout << "Menu:\n";
cout << "1. Add Section\n";
cout << "2. Add Student to Section\n";
cout << "3. Display Students of a Section\n";
cout << "4. Update Student CGPA\n";
cout << "5. Sort Students in a Section by CGPA\n";
cout << "6. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
if (numSections < MAX_SECTIONS) {
cout << "Enter section name: ";
cin >> sections[numSections].sectionName;
cout << "Enter class teacher's name: ";
cin >> sections[numSections].classTeacherName;
sections[numSections].numStudents = 0;
numSections++;
}
else {
cout << "Maximum sections reached.\n";
}
break;
}
case 2: {
int sectionIndex;
cout << "Enter section index (0 to " << numSections - 1 << "): ";
cin >> sectionIndex;
if (sectionIndex >= 0 && sectionIndex < numSections) {
if (sections[sectionIndex].numStudents < 40) {
Student newStudent;
cout << "Enter student name: ";
cin >> newStudent.name;
cout << "Enter student CNIC: ";
cin >> newStudent.CNIC;
cout << "Enter student gender: ";
cin >> newStudent.gender;
cout << "Enter student CGPA: ";
cin >> newStudent.CGPA;
addStudentToSection(sections[sectionIndex], newStudent);
}
else {
cout << "Section is full. Cannot add more students.\n";
}
}
else {
cout << "Invalid section index.\n";
}
break;
}
case 3: {
int sectionIndex;
cout << "Enter section index (0 to " << numSections - 1 << "): ";
cin >> sectionIndex;
if (sectionIndex >= 0 && sectionIndex < numSections) {
displaySectionStudents(sections[sectionIndex]);
}
else {
cout << "Invalid section index.\n";
}
break;
}
case 4: {
string studentName, studentCNIC;
float newCGPA;
cout << "Enter student name: ";
cin >> studentName;
cout << "Enter student CNIC: ";
cin >> studentCNIC;
cout << "Enter new CGPA: ";
cin >> newCGPA;
updateStudentCGPA(sections, numSections, studentName, studentCNIC, newCGPA);
break;
}
case 5: {
int sectionIndex;
cout << "Enter section index (0 to " << numSections - 1 << "): ";
cin >> sectionIndex;
if (sectionIndex >= 0 && sectionIndex < numSections) {
sortStudentsByCGPA(sections[sectionIndex]);
cout << "Students in Section " << sections[sectionIndex].sectionName << " sorted by CGPA.\n";
}
else {
cout << "Invalid section index.\n";
}
break;
}
case 6: {
cout << "Exiting program.\n";
break;
}
default:
cout << "Invalid choice. Please enter a valid option.\n";
}
} while (choice != 6);

return 0;
}
Output:

Task 4:
#include <iostream>
#include <string>

using namespace std;

// Structure for an item


struct Item {
string name;
int price;
};

int main() {
// Define items
Item drinks = { "Drinks", 60 };
Item burgers = { "Burgers", 200 };
Item sweet = { "Sweet", 120 };

// Initialize variables for order


int numDrinks = 0, numBurgers = 0, numSweet = 0;

// Display menu
cout << "Menu:\n";
cout << "1. " << drinks.name << " - " << drinks.price << " PKR\n";
cout << "2. " << burgers.name << " - " << burgers.price << " PKR\n";
cout << "3. " << sweet.name << " - " << sweet.price << " PKR\n";

// Ask user for their order


cout << "Enter your order (e.g., '2 Burgers, 1 Drink'):\n";
string order;
getline(cin, order);

// Parse user's order


size_t pos = 0;
while ((pos = order.find(",")) != string::npos) {
string token = order.substr(0, pos);
int quantity;
string item;
size_t space_pos = token.find_first_of(" ");
quantity = stoi(token.substr(0, space_pos));
item = token.substr(space_pos + 1);

// Update quantities based on item


if (item == "Drinks") {
numDrinks += quantity;
}
else if (item == "Burgers") {
numBurgers += quantity;
}
else if (item == "Sweet") {
numSweet += quantity;
}

order.erase(0, pos + 1);


}

// Process the remaining part of the order (last item)


int quantity;
string item;
size_t space_pos = order.find_first_of(" ");
quantity = stoi(order.substr(0, space_pos));
item = order.substr(space_pos + 1);
if (item == "Drinks") {
numDrinks += quantity;
}
else if (item == "Burgers") {
numBurgers += quantity;
}
else if (item == "Sweet") {
numSweet += quantity;
}

// Calculate total bill


int totalBill = numDrinks * drinks.price + numBurgers * burgers.price + numSweet * sweet.price;

// Display receipt
cout << "Your Order = " << numBurgers << " " << burgers.name << ", " << numDrinks << " " << drinks.name << ", "
<< numSweet << " " << sweet.name << ".\n";
cout << "Total Bill: " << totalBill << " PKR\n";

return 0;
}
Output:

Task 5:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

bool saveDataToFile(string name, int rollNum, int CNIC, string degree, string FileName) {
ofstream outFile(FileName, ios::app);
if (outFile.is_open()) {
outFile << "Name: " << name << endl;
outFile << "Roll Number: " << rollNum << endl;
outFile << "CNIC: " << CNIC << endl;
outFile << "Degree: " << degree << endl;
outFile << "-------------------\n";
outFile.close();
return true;
}
else {
cout << "Error: Unable to open file." << endl;
return false;
}
}

// Function to read and print student data from a file


bool readAndPrintData(string FileName) {
ifstream inFile(FileName);
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
return true;
}
else {
cout << "Error: Unable to open file." << endl;
return false;
}
}

int main() {
string batchName;
cout << "Enter batch name (e.g., batch2023): ";
cin >> batchName;
cin.ignore();

string fileName = batchName + ".txt";

char choice;
do {
string name, degree;
int rollNum, CNIC;

cout << "Enter student name: ";


getline(cin, name);
cout << "Enter roll number: ";
cin >> rollNum;
cout << "Enter CNIC: ";
cin >> CNIC;
cin.ignore();
cout << "Enter degree: ";
getline(cin, degree);

if (saveDataToFile(name, rollNum, CNIC, degree, fileName)) {


cout << "Student data saved successfully." << endl;
}
else {
cout << "Failed to save student data." << endl;
}

cout << "Do you want to enter data for another student? (y/n): ";
cin >> choice;
cin.ignore();
} while (choice == 'y' || choice == 'Y');

system("CLS");

if (readAndPrintData(fileName)) {
cout << "Data printed successfully." << endl;
}
else {
cout << "Failed to print data." << endl;
}

return 0;
}
Output:

Task 6:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {

ifstream file("names.txt");
if (!file.is_open()) {
cout << "Error: Unable to open file." << endl;
return 1;
}

string substring;
cout << "Enter the substring to search for: ";
cin >> substring;
cout << "Names containing \"" << substring << "\":\n";
string name;
while (getline(file, name)) {
if (name.find(substring) != string::npos) {
cout << name << endl;
}
}

file.close();

return 0;
}
Output:

Task 7:
#include <iostream>

using namespace std;

struct Saxon {
double length;
double width;
double height;
double radius;
double depth;
};

double Room(Saxon saxon) {


return saxon.length * saxon.width;
}

double Pool(Saxon saxon) {


const double PI = 3.14159;
return PI * saxon.radius * saxon.radius * saxon.depth;
}

int main() {

Saxon saxon;

cout << "Enter length of the room: ";


cin >> saxon.length;
cout << "Enter width of the room: ";
cin >> saxon.width;

double roomArea = Room(saxon);


cout << "Saxon will clean a room of area: " << roomArea << endl;

cout << "Enter radius of the pool: ";


cin >> saxon.radius;
cout << "Enter depth of the pool: ";
cin >> saxon.depth;

double poolVolume = Pool(saxon);


cout << "Saxon will clean a pool of volume: " << poolVolume << endl;

return 0;
}
Output:
Task 8:
#include <iostream>

using namespace std;

void reverseArray(int* ptr1, int* ptr2, int n) {


for (int i = 0; i < n; ++i) {
*(ptr2 + n - i - 1) = *(ptr1 + i);
}
}

bool isPalindrome(int* ptr1, int* ptr2, int n) {


for (int i = 0; i < n; ++i) {
if (*(ptr1 + i) != *(ptr2 + n - i - 1)) {
return false;
}
}
return true;
}

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

int* ptr1 = new int[n];


int* ptr2 = new int[n];

cout << "Enter " << n << " values for ptr1: ";
for (int i = 0; i < n; ++i) {
cin >> *(ptr1 + i);
}

reverseArray(ptr1, ptr2, n);

bool palindrome = isPalindrome(ptr1, ptr2, n);

cout << "Ptr1: ";


for (int i = 0; i < n; ++i) {
cout << *(ptr1 + i) << " ";
}
cout << endl;

cout << "Ptr2: ";


for (int i = 0; i < n; ++i) {
cout << *(ptr2 + i) << " ";
}
cout << endl;

if (palindrome) {
cout << "Ptr2 is a palindrome." << endl;
}
else {
cout << "Ptr2 is not a palindrome." << endl;
}

delete[] ptr1;
delete[] ptr2;

return 0;
}
Output:

Task 9:
#include <iostream>
#include <string>

using namespace std;

struct Address {
int houseNumber;
int streetNumber;
string cityName;
string provinceName;
};

struct Student {
string name;
Address address;
int age;
float GPA;
};

int main() {
const int MAX_STUDENTS = 100;
Student students[MAX_STUDENTS];
int numStudents = 0;

char choice;
do {
Student newStudent;

cout << "Enter name of student: ";


getline(cin, newStudent.name);

cout << "Enter house number: ";


cin >> newStudent.address.houseNumber;

cout << "Enter street number: ";


cin >> newStudent.address.streetNumber;
cin.ignore();

cout << "Enter city name: ";


getline(cin, newStudent.address.cityName);

cout << "Enter province name: ";


getline(cin, newStudent.address.provinceName);

cout << "Enter age: ";


cin >> newStudent.age;

cout << "Enter GPA: ";


cin >> newStudent.GPA;

students[numStudents++] = newStudent;

cout << "Do you want to enter data for another student? (y/n): ";
cin >> choice;
cin.ignore();
} while (choice == 'y' || choice == 'Y');

cout << "\nStudent Data:\n";


for (int i = 0; i < numStudents; ++i) {
cout << "Name: " << students[i].name << endl;
cout << "Address: " << students[i].address.houseNumber << " " << students[i].address.streetNumber
<< ", " << students[i].address.cityName << ", " << students[i].address.provinceName << endl;
cout << "Age: " << students[i].age << endl;
cout << "GPA: " << students[i].GPA << endl << endl;
}

return 0;
}
Output:
Task 10:
#include <iostream>
#include <string>

using namespace std;

struct Ship {
string name;
string type;
float length;
float width;
float topSpeed;
};

struct ShipStats {
float averageLength;
float averageWidth;
};

ShipStats calculateAverage(const Ship ships[], int numShips) {


ShipStats stats;
float totalLength = 0;
float totalWidth = 0;

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


totalLength += ships[i].length;
totalWidth += ships[i].width;
}

stats.averageLength = totalLength / numShips;


stats.averageWidth = totalWidth / numShips;

return stats;
}

int main() {
const int MAX_SHIPS = 10;
Ship ships[MAX_SHIPS];
int numShips;

cout << "Enter the number of ships (up to 10): ";


cin >> numShips;
cin.ignore();
for (int i = 0; i < numShips; ++i) {
cout << "Enter name of ship " << i + 1 << ": ";
getline(cin, ships[i].name);

cout << "Enter type of ship " << i + 1 << ": ";
getline(cin, ships[i].type);

cout << "Enter length of ship " << i + 1 << ": ";
cin >> ships[i].length;

cout << "Enter width of ship " << i + 1 << ": ";
cin >> ships[i].width;

cout << "Enter top speed of ship " << i + 1 << ": ";
cin >> ships[i].topSpeed;

cin.ignore();
}

ShipStats averageStats = calculateAverage(ships, numShips);

cout << "\nShip Information:\n";


for (int i = 0; i < numShips; ++i) {
cout << "Name: " << ships[i].name << endl;
cout << "Type: " << ships[i].type << endl;
cout << "Length: " << ships[i].length << endl;
cout << "Width: " << ships[i].width << endl;
cout << "Top Speed: " << ships[i].topSpeed << endl;
cout << endl;
}

cout << "Average Length of Ships: " << averageStats.averageLength << endl;
cout << "Average Width of Ships: " << averageStats.averageWidth << endl;

return 0;
}
Output:
Task 11:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct Product {
string name;
float price;
int quantity;
};

void addProduct(const Product& product) {


ofstream outFile("inventory.txt", ios::app);
if (outFile.is_open()) {
outFile << product.name << "," << product.price << "," << product.quantity << endl;
cout << "Product added successfully." << endl;
outFile.close();
}
else {
cout << "Error: Unable to open file." << endl;
}
}

void readProducts() {
ifstream inFile("inventory.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
else {
cout << "Error: Unable to open file." << endl;
}
}

// Function to update product inventory


void updateInventory(const string& productName, int newQuantity) {
ifstream inFile("inventory.txt");
ofstream outFile("temp_inventory.txt");
if (inFile.is_open() && outFile.is_open()) {
string name;
float price;
int quantity;
bool updated = false;
while (inFile >> name >> price >> quantity) {
if (name == productName) {
quantity = newQuantity;
updated = true;
}
outFile << name << " " << price << " " << quantity << endl;
}
inFile.close();
outFile.close();
if (updated) {
remove("inventory.txt");
rename("temp_inventory.txt", "inventory.txt");
cout << "Inventory updated successfully." << endl;
}
else {
cout << "Product not found." << endl;
remove("temp_inventory.txt"); // Remove temporary file
}
}
else {
cout << "Error: Unable to open file." << endl;
}
}

int main() {
int choice;
do {
cout << "\n1. Add new product\n2. Read products\n3. Update inventory\n4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore();

switch (choice) {
case 1: {
Product newProduct;
cout << "Enter product name: ";
getline(cin, newProduct.name);
cout << "Enter product price: ";
cin >> newProduct.price;
cout << "Enter product quantity: ";
cin >> newProduct.quantity;
addProduct(newProduct);
break;
}
case 2: {
cout << "Product details:\n";
readProducts();
break;
}
case 3: {
string productName;
int newQuantity;
cout << "Enter product name to update: ";
cin.ignore();
getline(cin, productName);
cout << "Enter new quantity: ";
cin >> newQuantity;
updateInventory(productName, newQuantity);
break;
}
case 4:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 4);

return 0;
}
Output

Task 12:
#include <iostream>
#include <algorithm>
using namespace std;

void sortAscending(int* arr, int size) {


sort(arr, arr + size / 2);
}

void sortDescending(int* arr, int size) {


sort(arr + size / 2, arr + size, greater<int>());
}
void updateArray(int* arr, int size) {
int last_index = size - 1;

// Update first element


arr[0] *= arr[1] * arr[last_index];

// Update middle elements


for (int i = 1; i < last_index; i++) {
// Calculate indices for adjacent elements
int prev_index = (i == 0) ? last_index : i - 1;
int next_index = (i == last_index) ? 0 : i + 1;

arr[i] *= arr[prev_index] * arr[next_index];


}

// Update last element


arr[last_index] *= arr[0] * arr[last_index - 1];
}

int main() {
int size;

cout << "Enter the size of the array (even number): ";
cin >> size;

if (size % 2 != 0) {
cout << "Please enter an even number." << endl;
return 1;
}

int* arr = new int[size];

cout << "Enter " << size << " elements of the array:" << endl;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

cout << "\nOriginal array:" << endl;


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

sortAscending(arr, size);
sortDescending(arr, size);
cout << "\nSorted array:" << endl;
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

updateArray(arr, size);

cout << "\nUpdated array:" << endl;


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

delete[] arr;

return 0;
}

Task 13:
#include <iostream>
#include <cstring>

using namespace std;

int main() {
// Original line
char originalLine[100];
cout << "Enter the original line: ";
cin.getline(originalLine, sizeof(originalLine));

// Student's roll number


char rollNumber[20];
cout << "Enter your roll number (e.g., 21F-WXYZ): ";
cin.getline(rollNumber, sizeof(rollNumber));
// Calculate codes
int code1 = rollNumber[6] + rollNumber[7] - '0' - '0' + 1; // W + X + 1
int code2 = rollNumber[9] + rollNumber[10] - '0' - '0' + 1; // Y + Z + 1

// Encoded line
char encodedLine[100];
for (int i = 0; i < strlen(originalLine); i++) {
if (originalLine[i] >= 'A' && originalLine[i] <= 'Z') {
encodedLine[i] = ((originalLine[i] - 'A' + code1) % 26) + 'A';
}
else if (originalLine[i] >= 'a' && originalLine[i] <= 'z') {
encodedLine[i] = ((originalLine[i] - 'a' + code2) % 26) + 'a';
}
else {
encodedLine[i] = originalLine[i];
}
}
encodedLine[strlen(originalLine)] = '\0'; // Null-terminate the string

// Decoded line
char decodedLine[100];
for (int i = 0; i < strlen(encodedLine); i++) {
if (encodedLine[i] >= 'A' && encodedLine[i] <= 'Z') {
decodedLine[i] = ((encodedLine[i] - 'A' - code1 + 26) % 26) + 'A';
}
else if (encodedLine[i] >= 'a' && encodedLine[i] <= 'z') {
decodedLine[i] = ((encodedLine[i] - 'a' - code2 + 26) % 26) + 'a';
}
else {
decodedLine[i] = encodedLine[i];
}
}
decodedLine[strlen(encodedLine)] = '\0'; // Null-terminate the string

// Output
cout << "Original Line: " << originalLine << endl;
cout << "Encoded Line: " << encodedLine << endl;
cout << "Decoded Line: " << decodedLine << endl;

return 0;
}
Output:
Task 14:
#include <iostream>
#include <string>

using namespace std;

// Maximum number of tasks


const int MAX_TASKS = 100;

// Structure to represent a task


struct Task {
string description;
string dueDate;
bool completed;
};

// Array to store tasks


Task tasks[MAX_TASKS];

// Current number of tasks


int numTasks = 0;

// Function to add a new task to the task list


void addTask() {
if (numTasks < MAX_TASKS) {
cout << "Enter task description: ";
getline(cin >> ws, tasks[numTasks].description);
cout << "Enter due date (YYYY-MM-DD): ";
cin >> tasks[numTasks].dueDate;
tasks[numTasks].completed = false;
numTasks++;
cout << "Task added successfully!\n";
}
else {
cout << "Task list is full!\n";
}
}

// Function to mark a task as completed


void completeTask() {
int index;
cout << "Enter the index of the task to mark as completed: ";
cin >> index;
if (index >= 0 && index < numTasks) {
tasks[index].completed = true;
cout << "Task marked as completed!\n";
}
else {
cout << "Invalid index!\n";
}
}

// Function to delete a task from the task list


void deleteTask() {
int index;
cout << "Enter the index of the task to delete: ";
cin >> index;
if (index >= 0 && index < numTasks) {
cout << "Are you sure you want to delete this task? (y/n): ";
char choice;
cin >> choice;
if (choice == 'y' || choice == 'Y') {
for (int i = index; i < numTasks - 1; ++i) {
tasks[i] = tasks[i + 1];
}
numTasks--;
cout << "Task deleted successfully!\n";
}
else {
cout << "Task deletion canceled.\n";
}
}
else {
cout << "Invalid index!\n";
}
}

// Function to display all tasks in the task list


void listTasks() {
cout << "Incomplete Tasks:\n";
for (int i = 0; i < numTasks; ++i) {
if (!tasks[i].completed) {
cout << "[" << i << "] " << tasks[i].description << " (Due: " << tasks[i].dueDate << ")\n";
}
}
cout << "Completed Tasks:\n";
for (int i = 0; i < numTasks; ++i) {
if (tasks[i].completed) {
cout << "[" << i << "] " << tasks[i].description << " (Due: " << tasks[i].dueDate << ")\n";
}
}
}
int main() {
char choice;

do {
cout << "\nTask Manager Menu:\n";
cout << "1. Add Task\n";
cout << "2. Mark Task as Completed\n";
cout << "3. Delete Task\n";
cout << "4. List Tasks\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case '1':
cin.ignore(); // Ignore newline character left in the input buffer
addTask();
break;
case '2':
completeTask();
break;
case '3':
deleteTask();
break;
case '4':
listTasks();
break;
case '5':
cout << "Exiting Task Manager. Goodbye!\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
break;
}
} while (choice != '5');

return 0;
}
Output:
Task 15:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Function to display the content of the file


void displayFileContent(const string& filename) {
ifstream file(filename);
if (file.is_open()) {
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
else {
cout << "Unable to open file " << filename << endl;
}
}

// Function to count the number of lines in the file


int countLines(const string& filename) {
ifstream file(filename);
if (file.is_open()) {
int count = 0;
string line;
while (getline(file, line)) {
count++;
}
file.close();
return count;
}
else {
cout << "Unable to open file " << filename << endl;
return -1;
}
}

// Function to count the total number of words in the file


int countWords(const string& filename) {
ifstream file(filename);
if (file.is_open()) {
int count = 0;
string word;
while (file >> word) {
count++;
}
file.close();
return count;
}
else {
cout << "Unable to open file " << filename << endl;
return -1;
}
}

// Function to count the frequency of a specific word in the file


int countWordFrequency(const string& filename, const string& targetWord) {
ifstream file(filename);
if (file.is_open()) {
int count = 0;
string word;
while (file >> word) {
if (word == targetWord) {
count++;
}
}
file.close();
return count;
}
else {
cout << "Unable to open file " << filename << endl;
return -1;
}
}

// Function to delete a specific word from the file


void deleteWordFromFile(const string& filename, const string& targetWord) {
ifstream fin(filename);
ofstream temp("temp.txt");

if (!fin || !temp) {
cout << "Error opening file." << endl;
return;
}

string line;
while (getline(fin, line)) {
size_t pos = line.find(targetWord);
while (pos != string::npos) {
line.erase(pos, targetWord.length());
pos = line.find(targetWord, pos);
}
temp << line << endl;
}

fin.close();
temp.close();

remove(filename.c_str());
rename("temp.txt", filename.c_str());

cout << "Word '" << targetWord << "' deleted from file." << endl;
}

int main() {
const string filename = "poem.txt";

// Display the file content


cout << "File Content:\n";
displayFileContent(filename);

// Count number of lines


cout << "\nNumber of lines in the file: " << countLines(filename) << endl;

// Count number of words


cout << "Total number of words in the file: " << countWords(filename) << endl;

// Input a word and check its frequency


string word;
cout << "Enter a word to check its frequency: ";
cin >> word;
cout << "Frequency of '" << word << "' in the file: " << countWordFrequency(filename, word) << endl;

// Input a word and delete it from the file


cout << "Enter a word to delete from the file: ";
cin >> word;
deleteWordFromFile(filename, word);

return 0;
}
Output:

You might also like