Week 3

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

1.

Write a menu driven C++ program with following option


a. Accept elements of an array
b. Display elements of an array
c. Sort the array using insertion sort method
d. Sort the array using selection sort method
e. Sort the array using bubble sort method
#include <iostream>

using namespace std;

// Function to accept elements of an array


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

// Function to display elements of an array


void displayArray(const int arr[], int size) {
cout << "Array Elements:" << endl;
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}

// Function to perform insertion sort on the array


void insertionSort(int arr[], int size) {
for (int i = 1; i < size; ++i) {
int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j--;
}

arr[j + 1] = key;
}
}

// Function to perform selection sort on the array


void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
int minIndex = i;

for (int j = i + 1; j < size; ++j) {


if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap the found minimum element with the first element


swap(arr[i], arr[minIndex]);
}
}
// Function to perform bubble sort on the array
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// Swap the adjacent elements if they are in the wrong order
swap(arr[j], arr[j + 1]);
}
}
}
}

int main() {
const int MAX_SIZE = 100;
int arr[MAX_SIZE];
int size;

char choice;
do {
cout << "\nMenu:\n";
cout << "a. Accept elements of an array\n";
cout << "b. Display elements of an array\n";
cout << "c. Sort the array using insertion sort method\n";
cout << "d. Sort the array using selection sort method\n";
cout << "e. Sort the array using bubble sort method\n";
cout << "x. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 'a':
cout << "Enter the size of the array: ";
cin >> size;
acceptArray(arr, size);
break;

case 'b':
displayArray(arr, size);
break;

case 'c':
insertionSort(arr, size);
cout << "Array sorted using insertion sort." << endl;
break;

case 'd':
selectionSort(arr, size);
cout << "Array sorted using selection sort." << endl;
break;

case 'e':
bubbleSort(arr, size);
cout << "Array sorted using bubble sort." << endl;
break;

case 'x':
cout << "Exiting program. Goodbye!" << endl;
break;

default:
cout << "Invalid choice. Please enter a valid option." << endl;
}

} while (choice != 'x');

return 0;
}

2. Write a C++ program to add two numbers using the concept of data abstraction
#include<iostream>

// Class declaration with private data members and public member functions
class Adder {
private:
int num1;
int num2;
public:
// Constructor to initialize data members
Adder() : num1(0), num2(0) {}

// Setter functions to set values for private data members


void setNum1(int n) {
num1 = n;
}

void setNum2(int n) {
num2 = n;
}

// Getter functions to retrieve values of private data members


int getNum1() const {
return num1;
}

int getNum2() const {


return num2;
}

// Function to add two numbers


int addNumbers() const {
return num1 + num2;
}
};

int main() {
// Creating an object of the Adder class
Adder adderObj;

// Accepting user input for two numbers


int inputNum1, inputNum2;
std::cout << "Enter the first number: ";
std::cin >> inputNum1;
adderObj.setNum1(inputNum1);

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


std::cin >> inputNum2;
adderObj.setNum2(inputNum2);

// Displaying the sum of two numbers


std::cout << "Sum of " << adderObj.getNum1() << " and " << adderObj.getNum2() << " is:
" << adderObj.addNumbers() << std::endl;

return 0;
}

3. Develop a class to represent a bank account. Include methods to deposit money,


withdraw money, and
check the account balance. Ensure that the withdrawal method checks for sufficient funds.
#include<iostream>
using namespace std;

class BankAccount {
private:
string accountHolderName;
string accountNumber;
double balance;

public:
// Constructor to initialize the account
BankAccount(string holderName, string accNumber, double initialBalance)
: accountHolderName(holderName), accountNumber(accNumber),
balance(initialBalance) {}

// Method to deposit money into the account


void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposit of $" << amount << " successful. New balance: $" << balance <<
endl;
} else {
cout << "Invalid deposit amount. Amount must be greater than zero." << endl;
}
}

// Method to withdraw money from the account with a check for sufficient funds
void withdraw(double amount) {
if (amount > 0) {
if (amount <= balance) {
balance -= amount;
cout << "Withdrawal of $" << amount << " successful. New balance: $" << balance
<< endl;
} else {
cout << "Insufficient funds. Cannot withdraw $" << amount << ". Current balance:
$" << balance << endl;
}
} else {
cout << "Invalid withdrawal amount. Amount must be greater than zero." << endl;
}
}

// Method to check the account balance


double checkBalance() const {
return balance;
}
};

int main() {
// Creating a BankAccount object
BankAccount myAccount("John Doe", "123456789", 1000.00);

// Performing operations on the account


cout << "Initial Balance: $" << myAccount.checkBalance() << endl;

myAccount.deposit(500.0);
myAccount.withdraw(200.0);
myAccount.withdraw(1500.0); // Attempting to withdraw more than the current
balance
cout << "Final Balance: $" << myAccount.checkBalance() << endl;

return 0;
}

4. Create a class to represent a student in a grading system. Include attributes for the
student&#39;s name, ID,
and an array to store grades. Implement methods to calculate the average grade, display the
student&#39;s
information, and add a new grade.
#include<iostream>
#include<string>
using namespace std;

class Student {
private:
string name;
string studentID;
double grades[100]; // Assuming a maximum of 100 grades

public:
// Constructor to initialize the student's attributes
Student(string studentName, string id) : name(studentName), studentID(id) {
// Initialize grades array to zeros
for (int i = 0; i < 100; ++i) {
grades[i] = 0.0;
}
}

// Method to calculate the average grade


double calculateAverage() const {
double sum = 0.0;
int count = 0;

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


if (grades[i] != 0.0) {
sum += grades[i];
++count;
}
}

return (count > 0) ? (sum / count) : 0.0;


}

// Method to display student information


void displayInfo() const {
cout << "Student Name: " << name << endl;
cout << "Student ID: " << studentID << endl;
cout << "Grades: ";

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


if (grades[i] != 0.0) {
cout << grades[i] << " ";
}
}

cout << endl;


cout << "Average Grade: " << calculateAverage() << endl;
}

// Method to add a new grade


void addGrade(double newGrade) {
for (int i = 0; i < 100; ++i) {
if (grades[i] == 0.0) {
grades[i] = newGrade;
cout << "New grade added: " << newGrade << endl;
return;
}
}

cout << "Cannot add more grades. Maximum limit reached." << endl;
}
};

int main() {
// Creating a Student object
Student student1("John Doe", "123456");

// Adding grades and displaying information


student1.addGrade(85.5);
student1.addGrade(90.0);
student1.addGrade(78.5);

// Displaying student information


student1.displayInfo();

return 0;
}

5. Develop a class to represent an employee in a payroll system. Include attributes for the
employee&#39;s
name, ID, hourly wage, and hours worked. Implement methods to calculate the weekly
salary and
display the employee&#39;s information.
#include <iostream>
#include <string>

class Employee {
private:
std::string name;
int id;
double hourlyWage;
double hoursWorked;

public:
// Constructor to initialize the employee
Employee(std::string empName, int empId, double empHourlyWage, double
empHoursWorked)
: name(empName), id(empId), hourlyWage(empHourlyWage),
hoursWorked(empHoursWorked) {}

// Method to calculate the weekly salary


double calculateWeeklySalary() const {
// Assuming standard working hours are 40 per week
const double standardWeeklyHours = 40.0;

if (hoursWorked <= standardWeeklyHours) {


// Regular pay if worked hours are within or equal to standard weekly hours
return hoursWorked * hourlyWage;
} else {
// Regular pay plus overtime pay for hours worked beyond standard weekly hours
const double overtimePayRate = 1.5;
return (standardWeeklyHours * hourlyWage) + ((hoursWorked -
standardWeeklyHours) * overtimePayRate * hourlyWage);
}
}

// Method to display employee information


void displayEmployeeInfo() const {
std::cout << "Employee Information:" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "ID: " << id << std::endl;
std::cout << "Hourly Wage: $" << hourlyWage << std::endl;
std::cout << "Hours Worked: " << hoursWorked << " hours" << std::endl;
std::cout << "Weekly Salary: $" << calculateWeeklySalary() << std::endl;
}

// Function to set employee information based on user input


void setEmployeeInfo() {
std::cout << "Enter Employee Name: ";
std::getline(std::cin >> std::ws, name); // Allowing spaces in the name

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


std::cin >> id;

std::cout << "Enter Hourly Wage: $";


std::cin >> hourlyWage;

std::cout << "Enter Hours Worked: ";


std::cin >> hoursWorked;
}
};

int main() {
// Example usage of the Employee class
Employee emp1("", 0, 0.0, 0.0); // Initializing with default values
emp1.setEmployeeInfo(); // Take input from the user
emp1.displayEmployeeInfo(); // Display the employee's information

return 0;
}
6. Write a C++ program to display product detail using classes.
#include<iostream>
#include<string>
using namespace std;

// Class declaration for Product


class Product {
private:
string productName;
int productId;
double productPrice;

public:
// Constructor to initialize product details
Product(string name = "", int id = 0, double price = 0.0)
: productName(name), productId(id), productPrice(price) {}

// Method to display product details


void displayDetails() const {
cout << "Product ID: " << productId << endl;
cout << "Product Name: " << productName << endl;
cout << "Product Price: $" << productPrice << endl;
}

// Function to set product details based on user input


void setProductDetails() {
cout << "Enter Product Name: ";
getline(cin >> ws, productName); // Allowing spaces in the product name

cout << "Enter Product ID: ";


cin >> productId;

cout << "Enter Product Price: $";


cin >> productPrice;
}
};

int main() {
// Creating a Product object
Product laptop;

// Taking input for product details


laptop.setProductDetails();

// Displaying product details


cout << "Product Details:\n";
laptop.displayDetails();

return 0;
}

7. Suppose A, B, C are arrays of integers of size M, N, and M + N respectively. The numbers in


array A
appear in ascending order while the numbers in array B appear in descending order. Write a
user
defined function in C++ to produce third array C by merging arrays A and B in ascending
order. Use A,
B and C as arguments in the function.
#include<iostream>
using namespace std;

// Function to merge arrays A and B into C in ascending order


void mergeArrays(int A[], int M, int B[], int N, int C[]) {
int i = 0, j = 0, k = 0;

// Merge until elements are present in both arrays A and B


while (i < M && j < N) {
if (A[i] < B[j]) {
C[k++] = A[i++];
} else {
C[k++] = B[j++];
}
}

// Copy the remaining elements from array A, if any


while (i < M) {
C[k++] = A[i++];
}

// Copy the remaining elements from array B, if any


while (j < N) {
C[k++] = B[j++];
}
}

int main() {
const int MAX_SIZE_A = 5;
const int MAX_SIZE_B = 4;
const int MAX_SIZE_C = MAX_SIZE_A + MAX_SIZE_B;

int A[MAX_SIZE_A] = {1, 3, 5, 7, 9};


int B[MAX_SIZE_B] = {10, 8, 6, 4};
int C[MAX_SIZE_C];

// Displaying arrays A and B


cout << "Array A: ";
for (int i = 0; i < MAX_SIZE_A; ++i) {
cout << A[i] << " ";
}
cout << endl;
cout << "Array B: ";
for (int i = 0; i < MAX_SIZE_B; ++i) {
cout << B[i] << " ";
}
cout << endl;

// Calling the function to merge arrays A and B into C


mergeArrays(A, MAX_SIZE_A, B, MAX_SIZE_B, C);

// Displaying the merged array C


cout << "Merged Array C: ";
for (int i = 0; i < MAX_SIZE_C; ++i) {
cout << C[i] << " ";
}
cout << endl;

return 0;
}

8. To celebrate the Reunion of 96 Batch of the Famous School the Ram and Jannu the
organizers of the
event decided to liters of Fruit Drinks. However, an unexpected difficulty occurred in the
shop: it
turned out that Fruit Drinks is sold in bottles 0.5, 1 and 2 li volume. At that, there are exactly
0.5
bottles in volume, bone-liter bottles and c of two-liter ones. The organizers have enough
money to buy
any amount of Fruit Drinks. What did cause the heated arguments was how many bottles of
every kind
to buy, as this question is pivotal for the of Fruit Drinks among the Friends. Your task is to
count the
number of all the possible ways to buy exactly n liters of Fruit Drinks and persuade the organ
this
number is too large .All the bottles of Fruit Drinks are considered indistinguishable, i.e. two
variants of
buying are different from each other they differ in the number of bottles of at least one kind.
Constraints:
1≤n≤ 10000
0≤ a, b, c &lt; 5000
Input Format:
The first line contains four integers representing, a, b, c respectively.
Output Format:
Print the unique number representing the solution to the problem.
If it is impossible to buy exactly n liters of Fruit Drinks, print 0.
#include<iostream>
#include<vector>
using namespace std;

const int MOD = 1000000007;

int countWays(int n, int a, int b, int c) {


vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(a + 1, vector<int>(b + 1, 0)));

// Initialize base case


dp[0][0][0] = 1;

// Dynamic programming
for (int i = 0; i <= n; ++i) {
for (int x = 0; x <= a; ++x) {
for (int y = 0; y <= b; ++y) {
for (int z = 0; z <= c; ++z) {
if (i + 0.5 * x + y + 2 * z <= n) {
dp[i + static_cast<int>(0.5 * x + y + 2 * z)][x][y] = (dp[i + static_cast<int>(0.5 *
x + y + 2 * z)][x][y] + dp[i][x][y]) % MOD;
}
}
}
}
}

// Calculate the result


int result = 0;
for (int x = 0; x <= a; ++x) {
for (int y = 0; y <= b; ++y) {
for (int z = 0; z <= c; ++z) {
if (n - static_cast<int>(0.5 * x + y + 2 * z) == 0) {
result = (result + dp[n][x][y]) % MOD;
}
}
}
}

return result;
}
int main() {
int a, b, c, n;
cin >> a >> b >> c >> n;

int result = countWays(n, a, b, c);

cout << result << endl;

return 0;
}

9. Tamilnadu Educational Minister has ordered the Director of Higher education to make the
Libraries in
Government schools advanced. So they are planning to create a software which keeps track
of the
books availability and respond to students request for books. Can you help the government
to do this?
Functional Description:
Input values need to be passed to the Parameterized constructor and to output need to be
printed by accessing i t.
Constraints:
1&lt; roll ≤100
100 ≤ bcode&lt; 999
Input Format:
First and Second Line of Input has 3 values of type integer, String and Integer separated by a
space representing
Roll Number,
Name and Book code respectively.
Output Format:
Print the Details of Student and Book in the expected format.
#include <iostream>
#include <string>

class LibrarySystem {
private:
int rollNumber;
std::string studentName;
int bookCode;

public:
// Parameterized constructor to initialize student details and book code
LibrarySystem(int roll, std::string name, int code)
: rollNumber(roll), studentName(name), bookCode(code) {}

// Method to display student and book details


void displayDetails() const {
std::cout << "Student Details:" << std::endl;
std::cout << "Roll Number: " << rollNumber << std::endl;
std::cout << "Name: " << studentName << std::endl;
std::cout << "Book Code: " << bookCode << std::endl;
}
};

int main() {
int roll, bcode;
std::string name;
// Input values for Roll Number, Name, and Book Code
std::cout << "Enter Roll Number, Name, and Book Code (separated by space): ";
std::cin >> roll >> name >> bcode;

// Creating a LibrarySystem object with the provided input


LibrarySystem student(roll, name, bcode);

// Displaying student and book details


student.displayDetails();

return 0;
}

10. Tamilnadu land registration authority is panning to keep track of the native addresses
and total area of
the flats people have across the state. Since the total population and area need to be
monitored is huge.
Government is looking for the software which does this task. Can you help them with proper
programming logic for implementing the same?
Constraints:
1≤ hno&lt;500
1&lt; no room&lt; 10
1≤ length &lt; 50
1&lt; breadth &lt; 50
1≤ height &lt; 50
Input Format:
The first line of the input contain a single string denoting the house name.
The second line of the input contain three values of type Integer String and String separated
by a space representing house number, city and state respectively.
The third line of the input has a single Integer representing the number of rooms.
The subsequent lines of input must have length, breadth and height of each room
Output Format:
Print the details of the house in the expected format.
#include <iostream>
#include <string>
using namespace std;

class Room {
private:
int length;
int breadth;
int height;

public:
// Parameterized constructor
Room(int len, int br, int ht)
: length(len), breadth(br), height(ht) {}

// Method to calculate and return the area of the room


int calculateArea() const {
return length * breadth;
}
};

class House {
private:
string houseName;
int houseNumber;
string city;
string state;
int numRooms;
int totalArea;

public:
// Parameterized constructor
House(const string& name, int hno, const string& ct, const string& st)
: houseName(name), houseNumber(hno), city(ct), state(st), numRooms(0),
totalArea(0) {}

// Method to add a room to the house


void addRoom(const Room& room) {
numRooms++;
totalArea += room.calculateArea();
}

// Method to display the details of the house


void displayHouseDetails() const {
cout << "House Details:\n";
cout << "House Name: " << houseName << "\n";
cout << "House Number: " << houseNumber << "\n";
cout << "City: " << city << "\n";
cout << "State: " << state << "\n";
cout << "Number of Rooms: " << numRooms << "\n";
cout << "Total Area: " << totalArea << " square units\n";
}
};

int main() {
// Input values
string houseName, city, state;
int houseNumber, numRooms;

// Reading input values


cin.ignore(); // Ignore newline from previous input
getline(cin, houseName);
cin >> houseNumber >> city >> state >> numRooms;

// Creating a House object


House house(houseName, houseNumber, city, state);

// Reading room details and adding them to the house


for (int i = 0; i < numRooms; ++i) {
int length, breadth, height;
cin >> length >> breadth >> height;

Room room(length, breadth, height);


house.addRoom(room);
}

// Displaying details of the house


house.displayHouseDetails();

return 0;
}

You might also like