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

Week 3 Lab Program

The document discusses sample code for 6 programming assignments involving classes in C++. The assignments cover creating classes for array sorting, mathematical operations, bank accounts, students, employees, and product details. Methods and functions are implemented to demonstrate class concepts like encapsulation, abstraction and polymorphism.

Uploaded by

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

Week 3 Lab Program

The document discusses sample code for 6 programming assignments involving classes in C++. The assignments cover creating classes for array sorting, mathematical operations, bank accounts, students, employees, and product details. Methods and functions are implemented to demonstrate class concepts like encapsulation, abstraction and polymorphism.

Uploaded by

vinith gomez
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

HARRIS RAGAVENDRA.

S
RA2311003011087
OODP – WEEK(2) ASSINGNMENT
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

ANSWER :
#include<iostream>
using namespace std;

void acceptArray(int arr[], int size) {


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

void displayArray(int arr[], int size) {


cout << "Array elements are: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void insertionSort(int arr[], int size) {
int key, j;
for (int i = 1; i < size; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

void selectionSort(int arr[], int size) {


int i, j, min_idx;
for (i = 0; i < size-1; i++) {
min_idx = i;
for (j = i+1; j < size; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

swap(arr[min_idx], arr[i]);
}
}

void bubbleSort(int arr[], int size) {


int i, j;
for (i = 0; i < size-1; i++)
for (j = 0; j < size-i-1; j++)
if (arr[j] > arr[j+1])
swap(arr[j], arr[j+1]);
}

int main() {
int choice, size;
cout << "Enter the size of the array: ";
cin >> size;
int arr[size];

while (true) {
cout << "\nMenu:\n";
cout << "1. Accept elements of the array\n";
cout << "2. Display elements of the array\n";
cout << "3. Sort the array using insertion sort method\n";
cout << "4. Sort the array using selection sort method\n";
cout << "5. Sort the array using bubble sort method\n";
cout << "6. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
acceptArray(arr, size);
break;
case 2:
displayArray(arr, size);
break;
case 3:
insertionSort(arr, size);
cout << "Array sorted using insertion sort.\n";
break;
case 4:
selectionSort(arr, size);
cout << "Array sorted using selection sort.\n";
break;
case 5:
bubbleSort(arr, size);
cout << "Array sorted using bubble sort.\n";
break;
case 6:
cout << "Exiting program.\n";
return 0;
default:
cout << "Invalid choice. Please enter a valid option.\n";
}
}

return 0;
}

2 ) Write a C++ program to add two numbers using the concept of data abstraction

ANSWER :

#include<iostream>
using namespace std;
// Class to demonstrate data abstraction
class Addition {
private:
// Private attributes to hold the values to add
int a, b;

public:
// Constructor to initialize the numbers to add
Addition(int num1, int num2) {
a = num1;
b = num2;
}

// Public method to perform the addition and return the result


int add() {
return a + b; // Returns the sum of a and b
}
};

int main() {
int num1, num2;

// Asking for user input


cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;

// Creating an object of the Addition class


Addition myAddition(num1, num2);

// Using the public method 'add' to perform the addition and display the result
cout << "The sum of " << num1 << " and " << num2 << " is " << myAddition.add() << 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.

ANSWER :

#include <iostream>
using namespace std;

class BankAccount {
private:
double balance; // Private variable to store the account balance

public:
// Constructor to initialize the account with a balance. Default is 0 if no amount is
specified.
BankAccount(double initialBalance = 0) {
balance = initialBalance;
}

// Method to deposit money into the account


void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << "\n";
} else {
cout << "Amount to deposit should be positive.\n";
}
}

// Method to withdraw money from the account


void withdraw(double amount) {
if (amount > 0) {

if (amount <= balance) {


balance -= amount;
cout << "Withdrawn: $" << amount << "\n";
} else {
cout << "Insufficient funds. Transaction declined.\n";
}
} else {
cout << "Amount to withdraw should be positive.\n";
}
}

// Method to get the current account balance


double getBalance() const {
return balance;
}
};
int main() {
BankAccount myAccount(100); // Create a BankAccount object with an initial balance of
$100

cout << "Initial balance is $" << myAccount.getBalance() << "\n";

myAccount.deposit(50); // Deposit $50


cout << "Balance after deposit is $" << myAccount.getBalance() << "\n";

myAccount.withdraw(20); // Withdraw $20


cout << "Balance after withdrawal is $" << myAccount.getBalance() << "\n";

myAccount.withdraw(200); // Attempt to withdraw $200, which should fail due to


insufficient funds

return 0;
}

4 ) Create a class to represent a student in a grading system. Include attributes for the
student's name, ID,
and an array to store grades. Implement methods to calculate the average grade, display the
student's
information, and add a new grade.

ANSWER :

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Student {
private:
string name;
int id;
vector<double> grades; // Using vector to store grades dynamically

public:
// Constructor to initialize the student with a name and ID. Grades are initially empty.
Student(string studentName, int studentId) : name(studentName), id(studentId) {}

// Method to add a new grade to the student's record


void addGrade(double grade) {
if (grade >= 0 && grade <= 100) { // Ensuring the grade is within a valid range
grades.push_back(grade);
} else {
cout << "Invalid grade. Please enter a value between 0 and 100.\n";
}
}

// Method to calculate and return the average grade


double calculateAverage() const {
if (grades.empty()) {
return 0; // Return 0 if there are no grades
}
double sum = 0;
for (double grade : grades) {
sum += grade;
}
return sum / grades.size();
}

// Method to display the student's information and average grade


void displayInformation() const {
cout << "Student Name: " << name << "\n";
cout << "Student ID: " << id << "\n";
cout << "Grades: ";
for (double grade : grades) {
cout << grade << " ";
}
cout << "\nAverage Grade: " << calculateAverage() << "\n";
}
};

int main() {
// Example usage:
Student student1("John Doe", 1234);
student1.addGrade(88.5);
student1.addGrade(92.3);
student1.addGrade(76.0);
student1.addGrade(85.4);

student1.displayInformation();

return 0;
}

5 ) Develop a class to represent an employee in a payroll system. Include attributes for the
employee's name, ID, hourly wage, and hours worked. Implement methods to calculate the
weekly salary and display the employee's information.
ANSWER :

#include <iostream>
#include <iomanip> // For std::setprecision
using namespace std;

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

public:
// Constructor to initialize the employee with their details
Employee(string employeeName, int employeeId, double wage, double hours)
: name(employeeName), id(employeeId), hourlyWage(wage), hoursWorked(hours) {}

// Method to calculate the weekly salary


double calculateWeeklySalary() const {
return hourlyWage * hoursWorked;
}

// Method to display the employee's information and weekly salary


void displayInformation() const {
cout << "Employee Name: " << name << "\n";
cout << "Employee ID: " << id << "\n";
cout << "Hourly Wage: $" << fixed << setprecision(2) << hourlyWage << "\n";
cout << "Hours Worked: " << hoursWorked << "\n";
cout << "Weekly Salary: $" << calculateWeeklySalary() << "\n";
}
};

int main() {
// Example usage:
Employee employee1("Jane Doe", 101, 25.50, 40); // Employee with $25.50 hourly wage
and 40 hours of work
Employee employee2("John Smith", 102, 30.00, 45); // Includes 5 hours of overtime, if
applicable

employee1.displayInformation();
cout << "\n"; // Just adding a newline for better readability
employee2.displayInformation();

return 0;
}

6 ) Write a C++ program to display product detail using classes.

ANSWER :

#include <iostream>
#include <string>
using namespace std;

class Product {
private:
int id;
string name;
double price;

public:
// Default constructor
Product() : id(0), name(""), price(0.0) {}

// Parameterized constructor to initialize product details


Product(int productId, string productName, double productPrice)
: id(productId), name(productName), price(productPrice) {}

// Method to set product details


void setDetails(int productId, string productName, double productPrice) {
id = productId;
name = productName;
price = productPrice;
}

// Method to display product details


void displayDetails() const {
cout << "Product ID: " << id << endl;
cout << "Product Name: " << name << endl;
cout << "Product Price: $" << price << endl;
}
};

int main() {
// Creating an object of Product with details
Product product1(101, "Laptop", 1200.99);
// Displaying product details
cout << "Displaying product details:" << endl;
product1.displayDetails();

// Creating another product object and setting its details


Product product2;
product2.setDetails(102, "Smartphone", 799.49);

// Displaying the second product's details


cout << "\nDisplaying another product details:" << endl;
product2.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.

ANSWER :

#include <iostream>
#include <algorithm> // For std::reverse

using namespace std;

// Function to merge two arrays A and B into C


void mergeArrays(int A[], int M, int B[], int N, int C[]) {
// Reverse array B to make it in ascending order
std::reverse(B, B + N);

int i = 0, j = 0, k = 0;

// Merge arrays A and B into C


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

// Store remaining elements of A


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

// Store remaining elements of B


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

// Function to print an array


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

int main() {
// Example arrays
int A[] = {1, 3, 5, 7};
int M = sizeof(A) / sizeof(A[0]);
int B[] = {8, 6, 4, 2};
int N = sizeof(B) / sizeof(B[0]);
int C[M + N]; // Array to hold the result

// Merge A and B into C


mergeArrays(A, M, B, N, C);

// Print the merged array


cout << "Merged array in ascending order: ";
printArray(C, M + N);

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 < 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.

ANSWER :

#include <iostream>
#include <vector>
using namespace std;

const int MOD = 1000000007;

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

// Initialize 4D array dp
vector<vector<vector<vector<int>>>> dp(n + 1,
vector<vector<vector<int>>>(a + 1,
vector<vector<int>>(b + 1,
vector<int>(c + 1, 0))));

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

// Iterate over each possible amount of liters


for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= a; ++j) {
for (int k = 0; k <= b; ++k) {
for (int l = 0; l <= c; ++l) {
if (i + j / 2 + k + 2 * l <= n) {
// Update dp using dynamic programming
dp[i + j / 2 + k + 2 * l][j][k][l] =
(dp[i + j / 2 + k + 2 * l][j][k][l] +
dp[i][j][k][l]) % MOD;
}
}
}
}
}

// Print the result


cout << dp[n][a][b][c] << 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< roll ≤100
100 ≤ bcode< 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.

ANSWER :

#include <iostream>
#include <string>

using namespace std;

class Student {
private:
int roll_number;
string name;

public:
Student(int roll, string student_name) : roll_number(roll), name(student_name) {}

void printDetails() {
cout << "Roll Number: " << roll_number << endl;
cout << "Name: " << name << endl;
}
};

class Book {
private:
int book_code;

public:
Book(int code) : book_code(code) {}

void printDetails() {
cout << "Book Code: " << book_code << endl;
}
};

int main() {
int roll_number, book_code;
string name;

// Reading input
cin >> roll_number >> name >> book_code;

// Checking constraints
if (!(roll_number > 1 && roll_number <= 100 && book_code >= 100 && book_code < 999))
{
cout << "Invalid input! Please ensure roll number is between 1 and 100, and book code
is between 100 and 998." << endl;
} else {
// Creating objects
Student student(roll_number, name);
Book book(book_code);

// Printing details
student.printDetails();
book.printDetails();
}

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<500
1< no room< 10
1≤ length < 50
1< breadth < 50
1≤ height < 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.

ANSWER :

#include <iostream>
#include <string>

using namespace std;

class House {
private:
string house_name;
int house_number;
string city;
string state;
int num_rooms;
double total_area;

public:
House(string name, int number, string c, string s, int rooms) : house_name(name),
house_number(number), city(c), state(s), num_rooms(rooms), total_area(0) {}

void addRoom(double length, double breadth, double height) {


total_area += length * breadth * height;
}
void printDetails() {
cout << "House Name: " << house_name << endl;
cout << "House Number: " << house_number << endl;
cout << "City: " << city << endl;
cout << "State: " << state << endl;
cout << "Number of Rooms: " << num_rooms << endl;
cout << "Total Area: " << total_area << " square units" << endl;
}
};

int main() {
string house_name, city, state;
int house_number, num_rooms;
double length, breadth, height;

// Reading input
getline(cin, house_name);
cin >> house_number >> city >> state;
cin >> num_rooms;

// Creating house object


House house(house_name, house_number, city, state, num_rooms);

// Adding rooms and calculating total area


for (int i = 0; i < num_rooms; ++i) {
cin >> length >> breadth >> height;
house.addRoom(length, breadth, height);
}
// Printing details
house.printDetails();

return 0;
}

You might also like