Assignmentcpp 1
Assignmentcpp 1
int main() {
double radius;
cout << "The volume of the sphere is: " << volume << endl;
return 0;
}
int main() {
int num1, num2;
swapNumbers(num1, num2);
return 0;
}
3. Write a program in C++ to display various type or arithmetic operation using mixed data type
#include <iostream>
int main() {
int num1 = 10;
float num2 = 5.5;
double num3 = 7.8;
// Addition
float addition = num1 + num2 + num3;
cout << "Addition: " << addition << endl;
// Subtraction
double subtraction = num3 - num2 - num1;
cout << "Subtraction: " << subtraction << endl;
// Multiplication
double multiplication = num1 * num2 * num3;
cout << "Multiplication: " << multiplication << endl;
// Division
double division = num3 / num2 / num1;
cout << "Division: " << division << endl;
// Modulus
int modulus = num1 % 3;
cout << "Modulus: " << modulus << endl;
return 0;
}
int main() {
float length, width;
return 0;
}
SET B
1. Write a program in C++ to find the area and circumference of a circle
#include <iostream>
using namespace std;
int main() {
float radius;
return 0;
}
2.Program to build simple calculator using switch case.
#include <iostream>
using namespace std;
int main() {
int num1, num2;
char operation;
// Read the first number, operation, and second number from the user
cout << "Enter the first number: ";
cin >> num1;
return 0;
}
int main() {
double fahrenheit, celsius;
return 0;
}
int main() {
int number;
return 0;
}
Set C
1 Write a C++ program to display the current date and time
#include <iostream>
#include <ctime>
int main() {
// Get the current time
std::time_t currentTime = std::time(nullptr);
return 0;
}
2.Write a program in C++ that takes a number as input and prints its multiplication table upto 10.
#include <iostream>
int main() {
int number;
return 0;
}
int main() {
float principal, time, rate, simpleInterest;
return 0;
}
Exersice 2
Functions in C++
SET A
1. Write a program using function which accept two integers as an argument and return its sum.
Call this function from main( ) and print the results in main( ).
#include <iostream>
int main() {
int a, b;
int result;
return 0;
}
2. Write a function to calculate the factorial value of any integer as an argument. Call this
function from main( ) and print the results in main( ).
#include <iostream>
int main() {
int num;
int result;
return 0;
}
3. Write a function that receives two numbers as an argument and display all prime numbers
between these two numbers. Call this function from main( ).
#include <iostream>
int main() {
int num1, num2;
return 0;
}
SET B
1. Write a function that receives two numbers as an argument and display all prime numbers
between these two numbers. Call this function from main( ).
#include <iostream>
int main() {
int num1, num2;
return 0;
}
2. Raising a number to a power p is the same as multiplying n by itself p times. Write a function
called power that takes two arguments, a double value for n and an int value for p, and return
the result as double value. Use default argument of 2 for p, so that if this argument is omitted
the number will be squared. Write the main function that gets value from the user to test power
function.
#include <iostream>
// Function to calculate the power of a number
double power(double n, int p = 2) {
double result = 1.0;
for (int i = 0; i < p; ++i) {
result *= n;
}
return result;
}
int main() {
double number;
int exponent;
return 0;
}
SET C
1. Write a program that lets the user perform arithmetic operations on two numbers. Your
program must be menu driven, allowing the user to select the operation (+, -, *, or /) and input the
numbers. Furthermore, your program must consist of following functions: 1. Function
showChoice: This function shows the options to the user and explains how to enter data. 2.
Function add: This function accepts two number as arguments and returns sum. 3. Function
subtract: This function accepts two number as arguments and returns their difference.
4. Function multiply: This function accepts two number as arguments and returns product. 5.
Function divide: This function accepts two number as arguments and returns quotient.
#include <iostream>
int main() {
int choice;
double num1, num2;
return 0;
}
Assignment 3:
1. Define a class student with the following specification Private members of class
student admno integer sname 20 character eng. math, science float total float
ctotal() a function to calculate eng + math + science with float return type. Public
member function of class student Takedata() Function to accept values for admno,
sname, eng, science and invoke ctotal() to calculate total. Showdata() Function to
display all the data members on the screen
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int admno;
string sname;
float eng, math, science;
float total;
float ctotal() {
return eng + math + science;
}
public:
void Takedata() {
cout << "Enter Admission Number: ";
cin >> admno;
cout << "Enter Student Name: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, sname);
cout << "Enter marks for English: ";
cin >> eng;
cout << "Enter marks for Math: ";
cin >> math;
cout << "Enter marks for Science: ";
cin >> science;
void Showdata() {
cout << "Admission Number: " << admno << endl;
cout << "Student Name: " << sname << endl;
cout << "English Marks: " << eng << endl;
cout << "Math Marks: " << math << endl;
cout << "Science Marks: " << science << endl;
cout << "Total Marks: " << total << endl;
}
};
int main() {
Student student;
student.Takedata();
cout << "\nStudent Information:\n";
student.Showdata();
return 0;
}
2. Define a class batsman with the following specifications: Private members: bcode
4 digits code number bname 20 characters innings, notout, runs integer type
batavg it is calculated according to the formula – batavg =runs/(innings-notout)
calcavg() Function to compute batavg Public members: readdata() Function to
accept value from bcode, name, innings, notout and invoke the function calcavg()
displaydata() Function to display the data members on the screen.
#include <iostream>
#include <string>
using namespace std;
class Batsman {
private:
int bcode;
string bname;
int innings, notout, runs;
float batavg;
void calcavg() {
batavg = static_cast<float>(runs) / (innings - notout);
}
public:
void readdata() {
cout << "Enter Batsman Code: ";
cin >> bcode;
cout << "Enter Batsman Name: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, bname);
cout << "Enter Innings: ";
cin >> innings;
cout << "Enter Not Out: ";
cin >> notout;
cout << "Enter Runs: ";
cin >> runs;
void displaydata() {
cout << "Batsman Code: " << bcode << endl;
cout << "Batsman Name: " << bname << endl;
cout << "Innings: " << innings << endl;
cout << "Not Out: " << notout << endl;
cout << "Runs: " << runs << endl;
cout << "Batting Average: " << batavg << endl;
}
};
int main() {
Batsman batsman;
batsman.readdata();
cout << "\nBatsman Information:\n";
batsman.displaydata();
return 0;
}
3. Define a class TEST in C++ with following description: Private Members TestCode
of type integer Description of type string , NoCandidate of type integer CenterReqd
(number of centers required) of type integer A member function CALCNTR() to
calculate and return the number of centers as (NoCandidates/100+1) Public
Members - A function SCHEDULE() to allow user to enter values for TestCode,
Description, NoCandidate & call function CALCNTR() to calculate the number of
Centres - A function DISPTEST() to allow user to view the content of all the data
members
#include <iostream>
#include <string>
using namespace std;
class TEST {
private:
int TestCode;
string Description;
int NoCandidate;
int CenterReqd;
int CALCNTR() {
return (NoCandidate / 100) + 1;
}
public:
void SCHEDULE() {
cout << "Enter Test Code: ";
cin >> TestCode;
cout << "Enter Description: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, Description);
cout << "Enter Number of Candidates: ";
cin >> NoCandidate;
void DISPTEST() {
cout << "Test Code: " << TestCode << endl;
cout << "Description: " << Description << endl;
cout << "Number of Candidates: " << NoCandidate << endl;
cout << "Number of Centers Required: " << CenterReqd << endl;
}
};
int main() {
TEST test;
test.SCHEDULE();
cout << "\nTest Information:\n";
test.DISPTEST();
return 0;
}
4. Define a class in C++ with following description: Private Members A data member
Flight number of type integer A data member Destination of type string A data
member Distance of type float A data member Fuel of type float A member function
CALFUEL() to calculate the value of Fuel as per the following criteria Distance Fuel
<=1000 500 more than 1000 and <=2000 1100 more than 2000 2200 Public
Members A function FEEDINFO() to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel A
function SHOWINFO() to allow user to view the content of all the data members.
#include <iostream>
#include <string>
using namespace std;
class Flight {
private:
int FlightNumber;
string Destination;
float Distance;
float Fuel;
void CALFUEL() {
if (Distance <= 1000)
Fuel = 500;
else if (Distance <= 2000)
Fuel = 1100;
else
Fuel = 2200;
}
public:
void FEEDINFO() {
cout << "Enter Flight Number: ";
cin >> FlightNumber;
cout << "Enter Destination: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, Destination);
cout << "Enter Distance: ";
cin >> Distance;
int main() {
Flight flight;
flight.FEEDINFO();
cout << "\nFlight Information:\n";
flight.SHOWINFO();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class BOOK {
private:
int BOOK_NO;
string BOOKTITLE;
float PRICE;
public:
void INPUT() {
cout << "Enter Book Number: ";
cin >> BOOK_NO;
cout << "Enter Book Title: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, BOOKTITLE);
cout << "Enter Price: ";
cin >> PRICE;
}
void PURCHASE() {
int numCopies;
cout << "Enter the number of copies to be purchased: ";
cin >> numCopies;
int main() {
BOOK book;
book.INPUT();
book.PURCHASE();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class REPORT {
private:
int adno;
string name;
float marks[5];
float average;
void GETAVG() {
float sum = 0;
for (int i = 0; i < 5; i++) {
sum += marks[i];
}
average = sum / 5;
}
public:
void READINFO() {
cout << "Enter Admission Number: ";
cin >> adno;
cout << "Enter Name: ";
cin.ignore(); // Ignore newline character left in the input stream
getline(cin, name);
cout << "Enter Marks for 5 Subjects:\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << (i + 1) << ": ";
cin >> marks[i];
}
void DISPLAYINFO() {
cout << "Admission Number: " << adno << endl;
cout << "Name: " << name << endl;
cout << "Marks: ";
for (int i = 0; i < 5; i++) {
cout << marks[i] << " ";
}
cout << endl;
cout << "Average Marks: " << average << endl;
}
};
int main() {
REPORT report;
report.READINFO();
cout << "\nReport Information:\n";
report.DISPLAYINFO();
return 0;
}
SET C
1. Write the definition for a class called Rectangle that has floating point data
members length and width. The class has the following member functions:
void setlength(float) to set the length data member
void setwidth(float) to set the width data member
float perimeter() to calculate and return the perimeter of the rectangle
float area() to calculate and return the area of the rectangle
#include <iostream>
using namespace std;
class Rectangle {
private:
float length;
float width;
public:
void setlength(float len) {
length = len;
}
float perimeter() {
return 2 * (length + width);
}
float area() {
return length * width;
}
};
int main() {
Rectangle rect;
float len, wid;
cout << "Perimeter of the rectangle: " << rect.perimeter() << endl;
cout << "Area of the rectangle: " << rect.area() << endl;
return 0;
}
Exercise 4
Constructors & Destructors
SET A
1.Write a program to display student details(Rolllno,name,class,percent) using
constructor and destructor
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int RollNo;
string Name;
string Class;
float Percentage;
public:
Student(int rollNo, const string& name, const string& className, float
percent)
: RollNo(rollNo), Name(name), Class(className), Percentage(percent) {
cout << "Constructor called for Roll No: " << RollNo << endl;
}
~Student() {
cout << "Destructor called for Roll No: " << RollNo << endl;
}
void DisplayDetails() {
cout << "Roll No: " << RollNo << endl;
cout << "Name: " << Name << endl;
cout << "Class: " << Class << endl;
cout << "Percentage: " << Percentage << "%" << endl;
}
};
int main() {
Student student(1234, "John Doe", "10th Grade", 87.5);
student.DisplayDetails();
return 0;
}
#include <iostream>
using namespace std;
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int num = 0, int den = 1) {
numerator = num;
denominator = den;
}
void Display() {
cout << numerator << "/" << denominator << endl;
}
};
int main() {
Fraction fraction1(3, 4);
Fraction fraction2(2, 5);
return 0;
}
SET B
1. Write a c++ program to read the information like plant_name, plant_code,
plant_type, price. Construct the database with suitable member functions for
initializing and for destroying the data, viz. constructor, copy constructor,
destructor.
#include <iostream>
#include <string>
using namespace std;
class Plant {
private:
string plant_name;
int plant_code;
string plant_type;
float price;
public:
Plant() {
cout << "Default constructor called" << endl;
}
~Plant() {
cout << "Destructor called for plant: " << plant_name << endl;
}
void Display() {
cout << "Plant Name: " << plant_name << endl;
cout << "Plant Code: " << plant_code << endl;
cout << "Plant Type: " << plant_type << endl;
cout << "Price: " << price << endl;
cout << endl;
}
};
int main() {
Plant plant1("Rose", 1, "Flowering", 10.99);
Plant plant2 = plant1;
Plant plant3;
plant1.Display();
plant2.Display();
plant3.Display();
return 0;
}
In this program, the `Plant` class represents a plant with private data members
`plant_name` (string), `plant_code` (integer), `plant_type` (string), and `price`
(float). The class defines a default constructor, a parameterized constructor, a
copy constructor, and a destructor.
In the `main()` function, we create three `Plant` objects: `plant1` using the
parameterized constructor, `plant2` using the copy constructor with `plant1` as
an argument, and `plant3` using the default constructor. The `Display()`
member function is called on each object to display the plant information.
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Constructor called" << endl;
}
~MyClass() {
cout << "Destructor called" << endl;
}
};
int main() {
MyClass obj1; // Creating an object of MyClass
return 0;
}
In this program, the `MyClass` class has a constructor and a destructor. The
constructor is called when an object of `MyClass` is created, and the destructor is
called when an object is destroyed or goes out of scope.
When `obj1` is created, the constructor is called and displays the message
"Constructor called". When `obj2` is created using `new`, the constructor is called,
and the message is displayed.
When `delete obj2` is called, it deallocates the memory occupied by `obj2`, and
before that, the destructor is called, displaying the message "Destructor called".
Constructor called
Constructor called
Destructor called
SET C
1. A common place to buy candy is from a machine. The machine sells candies,
chips, gum, and cookies. You have been asked to write a program for this candy
machine. The program should do the following:
1. Show the customer the different products sold by the candy machine.
2. Let the customer make the selection.
3. Show the customer the cost of the item selected.
4. Accept money from the customer.
5. Release the item.
#include <iostream>
using namespace std;
class CandyMachine {
private:
string product;
float cost;
public:
void showProducts() {
cout << "Products available in the candy machine:" << endl;
cout << "1. Candies" << endl;
cout << "2. Chips" << endl;
cout << "3. Gum" << endl;
cout << "4. Cookies" << endl;
cout << endl;
}
int main() {
CandyMachine candyMachine;
candyMachine.showProducts();
int selection;
cout << "Enter your selection (1-4): ";
cin >> selection;
candyMachine.makeSelection(selection);
float amount;
cout << "Enter the amount: $";
cin >> amount;
candyMachine.acceptMoney(amount);
return 0;
}
Then, the customer enters the amount of money they want to insert, and the
`acceptMoney()` function is called to check if the amount is sufficient. If the
amount is enough, a message is displayed thanking the customer and providing
change if applicable. If the amount is insufficient, a message is displayed asking
the customer to insert more money.
#include <iostream>
using namespace std;
class cashRegister {
private:
int cashOnHand;
public:
cashRegister() {
cashOnHand = 500;
}
cashRegister(int cash) {
cashOnHand = cash;
}
int getCurrentBalance() {
return cashOnHand;
}
int main() {
cashRegister register1;
cout << "Current balance: $" << register1.getCurrentBalance() << endl;
register1.acceptAmount(100);
cout << "Current balance: $" << register1.getCurrentBalance() << endl;
cashRegister register2(1000);
cout << "Current balance: $" << register2.getCurrentBalance() << endl;
register2.acceptAmount(200);
cout << "Current balance: $" << register2.getCurrentBalance() << endl;
return 0;
}
Exercise 5
Operator Overloading
SET A
1. Write a C++ program to overload ! operator to find factorial of an INTEGER
object.
#include <iostream>
using namespace std;
class INTEGER {
private:
int value;
public:
INTEGER(int val) {
value = val;
}
int operator!() {
int factorial = 1;
for (int i = 1; i <= value; i++) {
factorial *= i;
}
return factorial;
}
};
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
INTEGER obj(num);
int result = !obj;
cout << "Factorial of " << num << " is: " << result << endl;
return 0;
}
class Rational {
private:
int numerator;
int denominator;
public:
Rational(int num = 0, int den = 1) {
numerator = num;
denominator = den;
simplify();
}
void simplify() {
int gcd = calculateGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
if (denominator < 0) {
numerator *= -1;
denominator *= -1;
}
}
void display() {
cout << numerator << "/" << denominator;
}
};
int main() {
Rational r1(3, 4);
Rational r2(2, 5);
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
class String {
private:
char* str;
int length;
public:
String(const char* s = "") {
length = strlen(s);
str = new char[length + 1];
strcpy(str, s);
}
~String() {
delete[] str;
}
int main() {
String s1("Hello");
String s2("World");
return 0;
}
SET B
1. Define a class Date. Overload the operators << and >> for this class to shift a
date by specific number of days.
#include <iostream>
using namespace std;
class Date {
private:
int day;
int month;
int year;
public:
Date(int d = 0, int m = 0, int y = 0) {
day = d;
month = m;
year = y;
}
bool isLeapYear(int y) {
// Returns true if the year is a leap year, false otherwise
if (y % 4 == 0) {
if (y % 100 == 0) {
if (y % 400 == 0) {
return true;
}
return false;
}
return true;
}
return false;
}
int main() {
Date date;
int numDays;
cout << "Enter the number of days to shift the date: ";
cin >> numDays;
date.shiftDate(numDays);
return 0;
}
2. Create a class matrix which stores a matrix of integers of given size. Write a
necessary member functions. Overload the following operators
+ Adds two matrices and stores in the third.
== Returns 1 if the two matrices are same otherwise 0. (Use dynamic memory
allocation)
#include <iostream>
using namespace std;
class Matrix {
private:
int rows;
int columns;
int** data;
public:
Matrix(int r, int c) {
rows = r;
columns = c;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[columns];
}
}
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
return result;
}
return true;
}
};
int main() {
Matrix matrix1(2, 2);
matrix1.setElement(0, 0, 1);
matrix1.setElement(0, 1, 2);
matrix1.setElement(1, 0, 3);
matrix1.setElement(1, 1, 4);
if (matrix1 == matrix3) {
cout << "Matrix 1 is equal to Matrix 3" << endl;
} else {
cout << "Matrix 1 is not equal to Matrix 3" << endl;
}
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int num = 0, int denom = 1) : numerator(num), denominator(denom)
{}
void reduce() {
int gcd = computeGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
int main() {
int n;
cout << "Enter the number of fractions: ";
cin >> n;
vector<Fraction> fractions(n);
cout << "Enter " << n << " fractions in the format
'numerator/denominator':\n";
for (int i = 0; i < n; i++) {
cout << "Fraction " << i + 1 << ": ";
cin >> fractions[i];
}
sort(fractions.begin(), fractions.end());
return 0;
}
In this program, the `Fraction` class represents a fraction with a numerator and
denominator. The class overloads the `<<` operator for insertion, allowing
fractions to be printed in the "numerator/denominator" format. It also overloads
the `>>` operator for extraction, enabling fractions to be read from input in the
same format and automatically reduced to their simplest form.
The `<` operator is overloaded to compare two fractions based on their decimal
values. The `reduce()` function is used to reduce the fraction to its simplest
form by dividing both the numerator and denominator by their greatest
common divisor (GCD).
In the `main()` function, the user is prompted to enter the number of fractions
and then input each fraction. The fractions are stored in a vector and sorted in
ascending order using the `<` operator. Finally, the sorted fractions are
displayed on the console.
You can run this program and provide the desired number of fractions to see
them sorted in ascending order.
SET C
1. Write a program to overload the new and delete operator
Certainly! Here's an example of how you can overload the `new` and `delete`
operators in C++:
#include <iostream>
using namespace std;
class MyClass {
public:
int data;
MyClass() : data(0) {
cout << "Default constructor called." << endl;
}
int main() {
MyClass* obj = new MyClass(42);
cout << "Data: " << obj->data << endl;
delete obj;
return 0;
}
In this program, the `MyClass` class overloads the `new` and `delete` operators.
The `new` operator is overloaded with the `operator new` function, which is a
static member function of the class. Inside this function, you can customize the
memory allocation behavior. In this example, it prints a message indicating the
size of the allocated memory and then uses the global `new` operator to allocate
memory for the object. The `delete` operator is overloaded with the `operator
delete` function, which is also a static member function of the class. Inside this
function, you can customize the memory deallocation behavior. In this example,
it prints a message and uses the global `delete` operator to deallocate the
memory.
When you run this program, you will see the customized messages printed
when the overloaded `new` and `delete` operators are called. The output may
vary depending on the compiler and system you are using.
#include <iostream>
using namespace std;
class SparseMatrix {
private:
struct Node {
int row;
int col;
int value;
Node* next;
int numRows;
int numCols;
Node* head;
public:
SparseMatrix(int rows, int cols) : numRows(rows), numCols(cols), head(nullptr) {}
curr = other.head;
while (curr != nullptr) {
int existingValue = result.getElement(curr->row, curr->col);
result.insertElement(curr->row, curr->col, existingValue + curr->value);
curr = curr->next;
}
return result;
}
curr = other.head;
while (curr != nullptr) {
int existingValue = result.getElement(curr->row, curr->col);
result.insertElement(curr->row, curr->col, existingValue - curr->value);
curr = curr->next;
}
return result;
}
return result;
}
void displayMatrix() {
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols;
j++) {
int element = getElement(i, j);
cout << element << " ";
}
cout << endl;
}
}
};
int main() {
SparseMatrix matrixA(3, 3);
matrixA.insertElement(0, 0, 1);
matrixA.insertElement(0, 2, 2);
matrixA.insertElement(1, 1, 3);
matrixA.insertElement(2, 0, 4);
matrixA.insertElement(2, 2, 5);
return 0;
}
In this program, the `SparseMatrix` class represents a sparse matrix using a linked
list to store only nonzero elements. The class has a private `Node` struct to
represent each nonzero element, which contains the row, column, value, and a
pointer to the next element. The `SparseMatrix` class itself has a pointer to the
head of the linked list.
The `insertElement()` function inserts a new element into the linked list at the
beginning. The `getElement()` function retrieves the value of an element given its
row and column. The `displayMatrix()` function displays the matrix by iterating
through each element and printing its value.
The class overloads the +, -, and * operators for matrix operations. These operators
take two `SparseMatrix` objects and perform the corresponding matrix operations.
The result is stored in a new `SparseMatrix` object and returned.
In the `main()` function, two `SparseMatrix` objects (`matrixA` and `matrixB`) are
created and populated with elements using the `insertElement()` function. The
matrices are then displayed using the `displayMatrix()` function.
Exercise 6
Inheritance
Set A
1. Create base class called shape. Use this class to store two double type values
that could be used to compute the area of figures. Derive three specific classes
called triangle, circle and rectangle from the base shape. Add to the base class,
a member function get_data() to initialize base class data members and
display_area() to compute and display area. Make display_area() as a virtual
function.(Hint: **use default value for one parameter while accepting values for
shape circle.)
#include <iostream>
#include <cmath>
class Shape {
protected:
double dimension1;
double dimension2;
public:
void get_data(double d1, double d2) {
dimension1 = d1;
dimension2 = d2;
}
int main() {
Triangle triangle;
triangle.get_data(5.0, 10.0);
triangle.display_area();
Circle circle;
circle.get_data(5.0, 0.0);
circle.display_area();
Rectangle rectangle;
rectangle.get_data(5.0, 10.0);
rectangle.display_area();
return 0;
}
In this program, the `Shape` class is the base class that stores two double
values representing dimensions. It provides a member function `get_data()` to
initialize these dimensions and a virtual member function `display_area()` to
compute and display the area. The `display_area()` function is made virtual to
enable dynamic polymorphism.
The `Triangle`, `Circle`, and `Rectangle` classes are derived from the `Shape`
base class. They inherit the `dimension1` and `dimension2` members from the
base class and override the `display_area()` function to compute and display the
specific areas for each shape.
In the `main()` function, objects of the derived classes (`Triangle`, `Circle`, and
`Rectangle`) are created. The `get_data()` function is called to initialize the
dimensions of each shape, and the `display_area()` function is called to compute
and display the respective areas for each shape.
2. Write a program in C++ to read the following information from the keyboard
in which the base class consists of employee name, code and designation. The
derived class Manager which contains the data members namely, year of
experience and salary. Display the whole information on the screen
#include <iostream>
#include <string>
class Employee {
protected:
string name;
int code;
string designation;
public:
void get_data() {
cout << "Enter employee name: ";
getline(cin, name);
void display_data() {
cout << "Employee Name: " << name << endl;
cout << "Employee Code: " << code << endl;
cout << "Employee Designation: " << designation << endl;
}
};
public:
void get_data() {
Employee::get_data();
void display_data() {
Employee::display_data();
cout << "Years of Experience: " << experience << endl;
cout << "Salary: $" << salary << endl;
}
};
int main() {
Manager manager;
return 0;
}
In this program, the base class `Employee` contains the data members `name`,
`code`, and `designation`. It provides member functions `get_data()` to read
employee information from the keyboard and `display_data()` to display the
employee information on the screen.
The derived class `Manager` inherits from the base class `Employee` and adds the
additional data members `experience` and `salary`. It overrides the `get_data()` and
`display_data()` functions to include the manager-specific information.
In the `main()` function, an object of the `Manager` class is created. The `get_data()`
function is called to read the manager's information from the keyboard, and the
`display_data()` function is called to display the manager's information on the
screen.
-----------------------------------------------------------------------------------------------------
-------------------------
Set B
1. Design a base class person(name,address,phone_no).Derive a class
employee(e_no,ename) from person.Derive a class
manager(designation,department,basic_salary) from employee. Write a menu
driven program to
Accept all details of ‘n’ manager.
Display manager having highest salary. (Use private inheritance)
#include <iostream>
#include <string>
#include <vector>
class Person {
protected:
string name;
string address;
string phone_no;
public:
void get_details() {
cout << "Enter name: ";
getline(cin, name);
public:
void get_employee_details() {
get_details();
public:
void get_manager_details() {
get_employee_details();
cout << "Enter designation: ";
getline(cin, designation);
int main() {
int n;
cout << "Enter the number of managers: ";
cin >> n;
cin.ignore(); // Ignore the newline character after reading the number of
managers
vector<Manager> managers(n);
double max_salary = 0;
int max_salary_index = -1;
if (max_salary_index != -1) {
cout << "Manager with the highest salary: " << endl;
managers[max_salary_index].display_details();
} else {
cout << "No managers found." << endl;
}
return 0;
}
In this program, the `Person` class serves as the base class that contains
common attributes like name, address, and phone number. The `Employee`
class is derived from `Person` and adds employee-specific attributes like
employee number and employee name. Finally, the `Manager` class is derived
from `Employee` and adds manager-specific attributes like designation,
department, and basic salary.
The program prompts the user to enter the number of managers and then
accepts the details for each manager using the `get_manager_details()` function
. After that, it finds the manager with the highest salary and displays their
details using the `display_details()` function.
#include <iostream>
#include <string>
#include <vector>
class Publication {
protected:
string title;
float price;
public:
Publication(const string& _title, float _price) : title(_title), price(_price) {}
virtual void display() const {
cout << "Title: " << title << endl;
cout << "Price: $" << price << endl;
}
};
public:
Book(const string& _title, float _price, int _pageCount) : Publication(_title,
_price), pageCount(_pageCount) {}
public:
Tape(const string& _title, float _price, int _playingTime) : Publication(_title,
_price), playingTime(_playingTime) {}
int main() {
vector<Publication*> publications;
int choice;
while (true) {
cout << "Menu:" << endl;
cout << "1. Display all books" << endl;
cout << "2. Display all tapes" << endl;
cout << "3. Filter books with page count greater than a value" << endl;
cout << "4. Filter tapes with playing time greater than or equal to a value"
<< endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // Ignore the newline character after reading the choice
if (choice == 1) {
cout << "All Books:" << endl;
for (const auto& publication : publications) {
Book* book = dynamic_cast<Book*>(publication);
if (book)
book->display();
}
} else if (choice == 2) {
cout << "All Tapes:" << endl;
for (const auto& publication : publications) {
Tape* tape = dynamic_cast<Tape*>(publication);
if (tape)
tape->display();
}
} else if (choice == 3) {
int pageCount;
cout << "Enter the minimum page count: ";
cin >> pageCount;
cout << "Books with page count greater than " << pageCount << ":" <<
endl;
for (const auto& publication : publications) {
Book* book = dynamic_cast<Book*>(publication);
if (book && book->getPageCount() > pageCount)
book->display();
}
} else if (choice == 4) {
int playingTime;
cout << "Enter the minimum playing time (in minutes): ";
cin >> playingTime;
cout << "Tapes with playing time greater than or equal to " <<
playingTime << " minutes
return 0;
}
In this program, the `Publication` class is the base class, and `Book` and `Tape`
are derived classes that add specific features. The `Publication` class has a
virtual `display()` function that is overridden in the derived classes to display
additional information.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class Student {
protected:
int rollNo;
string name;
string className;
public:
Student(int _rollNo, const string& _name, const string& _className)
: rollNo(_rollNo), name(_name), className(_className) {}
public:
Marks(float m1, float m2, float m3) {
marks[0] = m1;
marks[1] = m2;
marks[2] = m3;
}
public:
Result(int rollNo, const string& name, const string& className, float m1, float
m2, float m3)
: Student(rollNo, name, className), Marks(m1, m2, m3) {
calculatePercentage();
calculateGrade();
}
void calculatePercentage() {
percentage = (marks[0] + marks[1] + marks[2]) / 3.0;
}
void calculateGrade() {
if (percentage >= 90) {
grade = "A+";
} else if (percentage >= 80) {
grade = "A";
} else if (percentage >= 70) {
grade = "B";
} else if (percentage >= 60) {
grade = "C";
} else {
grade = "F";
}
}
int main() {
vector<Result*> results;
int choice;
while (true) {
cout << "Menu:" << endl;
cout << "1. Add student details with marks" << endl;
cout << "2. Display results of all students in descending order of percentage"
<< endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // Ignore the newline character after reading the choice
if (choice == 1) {
int rollNo;
string name, className;
float marks[3];
return 0;
}
In this program, the base class `Student` represents the basic information of a
student, the base class `Marks` represents the marks of a student, and the derived
class `Result` combines both the student details and marks to calculate the
percentage and grade. The program provides a menu-driven interface to add
student details with marks and display the results of all students in descending
order of percentage. The results are stored in a vector of `Result` pointers, allowing
dynamic addition and sorting of student results. The `display()` function is
overridden in the derived class to display all relevant information.
#include <iostream>
#include <vector>
#include <string>
class Person {
protected:
int id;
string name;
public:
void accept() {
cout << "Enter ID: ";
cin >> id;
cin.ignore(); // Ignore the newline character after reading the ID
public:
void accept() {
Person::accept();
public:
void accept() {
Person::accept();
int main() {
int n;
cout << "Enter the number of instructors: ";
cin >> n;
cin.ignore(); // Ignore the newline character after reading the number
vector<Instructor> instructors(n);
return 0;
}
In this updated program, the base class `Person` represents the common attributes
of a person, such as ID and name. The derived class `Teaching` inherits from
`Person` and adds an additional attribute called `subject`. The derived class
`NonTeaching` also inherits from `Person` and adds an additional attribute called
`department`. The derived class `Instructor` directly inherits from `Person` without
any additional attributes.
The program allows the user to input the number of instructors and their details.
The instructors are stored in a vector of `Instructor` objects. The `accept()` and
`display()` functions are overridden in the appropriate derived classes to handle
their specific attributes. Finally, the program displays the details of all the
instructors by iterating through the vector and calling the `display()` function for
each object.
Exercise 7
File I/O
Set A
1. Write a program to count the number of characters, number of words and
number of lines in a file.
#include <iostream>
#include <fstream>
#include <string>
int main() {
string filename;
cout << "Enter the filename: ";
getline(cin, filename);
ifstream file(filename);
if (!file) {
cout << "Error opening file." << endl;
return 1;
}
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
string line;
// Count characters
charCount += line.length();
// Count words
size_t pos = 0;
while (pos != string::npos) {
pos = line.find_first_not_of(" \t\n", pos); // Skip leading whitespace
if (pos != string::npos) {
pos = line.find_first_of(" \t\n", pos); // Find the next word
wordCount++;
}
}
}
file.close();
return 0;
}
In this program, we first prompt the user to enter the filename. Then, we open
the file using an `ifstream` object. If the file fails to open, we display an error
message and return from the program.
For each line, we count the number of characters by adding the length of the
line to `charCount`.
To count the words, we use a loop and the `find_first_not_of` and `find_first_of`
functions. We start by skipping any leading whitespace using `find_first_not_of`.
Then, we continue finding the next occurrence of whitespace or newline using
`find_first_of`, incrementing the word count each time.
Finally, we close the file and display the counts of characters, words, and lines.
-------------------------------------------------------------------------------------------------
------------
2. write a single file handling program in c++ to reading and writing data on a file.
#include <iostream>
#include <fstream>
#include <string>
int main() {
string filename = "data.txt";
if (!outputFile) {
cout << "Error creating file." << endl;
return 1;
}
outputFile.close();
cout << "Data written to the file successfully." << endl;
if (!inputFile) {
cout << "Error opening file." << endl;
return 1;
}
string line;
while (getline(inputFile, line)) {
cout << line << endl;
}
inputFile.close();
return 0;
}
In this program, we first define a `filename` variable to store the name of the file we
want to read from and write to (in this example, "data.txt").
To write data to the file, we create an `ofstream` object named `outputFile` and
open the file using that object. We check if the file was successfully created and if
not, display an error message and return from the program. We then use the `<<`
operator to write data to the file. In this example, we write three lines of text to the
file. Finally, we close the output file.
To read data from the file, we create an `ifstream` object named `inputFile` and
open the file using that object. We check if the file was successfully opened and if
not, display an error message and return from the program. We then use the
`getline` function to read each line from the file and display it on the console.
Finally, we close the input file.
Note: This program assumes that the file "data.txt" exists in the same directory as
the program. Make sure to create the file beforehand or modify the `filename`
variable to point to an existing file.
3. Write a user-defined function in C++ to read the content from a text file
OUT.TXT, count and display the number of alphabets, words and lines present
in it.
#include <iostream>
#include <fstream>
#include <cctype>
if (!inputFile) {
cout << "Error opening file." << endl;
return;
}
char ch;
int alphabetCount = 0;
int wordCount = 0;
int lineCount = 0;
bool isWord = false;
while (inputFile.get(ch)) {
if (isalpha(ch)) {
alphabetCount++;
}
if (ch == '\n') {
lineCount++;
isWord = false;
}
}
inputFile.close();
int main() {
string filename = "OUT.txt";
countAlphabetsWordsLines(filename);
return 0;
}
We declare variables to keep track of the alphabet count, word count, line count,
and a boolean flag to check if a word is encountered. We iterate through each
character in the file using the `get` function. If the character is an alphabet, we
increment the `alphabetCount`. If the character is not a space and `isWord` is false,
we set `isWord` to true and increment the `wordCount`. If the character is a newline
character (`\n`), we increment the `lineCount` and set `isWord` to false.
After counting the alphabets, words, and lines, we close the input file and display
the results.
-----------------------------------------------------------------------------------------------------
-----------------------------
Set B
1. Assuming that a text file named FIRST.TXT contains some text written into it,
write a function named copyupper(), that reads the file FIRST.TXT and creates a
new file named SECOND.TXT contains all words from the file FIRST.TXT in
uppercase.
#include <iostream>
#include <fstream>
#include <cctype>
void copyUpper() {
ifstream inputFile("FIRST.TXT");
ofstream outputFile("SECOND.TXT");
if (!inputFile) {
cout << "Error opening input file." << endl;
return;
}
if (!outputFile) {
cout << "Error creating output file." << endl;
inputFile.close();
return;
}
string word;
inputFile.close();
outputFile.close();
int main() {
copyUpper();
return 0;
}
In this program, we define a function `copyUpper()` that reads the input file
"FIRST.TXT" and creates an output file "SECOND.TXT". Inside the function, we
create an `ifstream` object named `inputFile` and open the input file. We also
create an `ofstream` object named `outputFile` and open the output file. If there
are any errors opening the files, we display an error message, close the files,
and return from the function.
We then use a `while` loop to read each word from the input file using the `>>`
operator. For each word, we iterate through each character and convert it to
uppercase using the `toupper()` function from the `<cctype>` library. We write
the uppercase word followed by a space into the output file.
After processing all the words, we close both the input and output files and
display a success message.
{
fstream in_out; public:
myfiile(char * fname);
void display() // reads the files
void append(); // append a character to a file void fileclose(); // close the file
}
Write a menu driven program with the following options
Dislay
Append
Exit
#include <iostream>
#include <fstream>
#include <cstring>
class myFile {
fstream in_out;
public:
myFile(char* fname);
void display();
void append();
void fileclose();
};
myFile::myFile(char* fname) {
in_out.open(fname, ios::in | ios::out | ios::app);
}
void myFile::display() {
char ch;
in_out.seekg(0, ios::beg);
while (in_out.get(ch)) {
cout << ch;
}
}
void myFile::append() {
char ch;
cin.ignore();
cout << "Enter a character to append to the file: ";
cin.get(ch);
in_out.seekp(0, ios::end);
in_out.put(ch);
}
void myFile::fileclose() {
in_out.close();
}
int main() {
char filename[100];
char choice;
bool exitProgram = false;
myFile file(filename);
while (!exitProgram) {
cout << "\nMenu:" << endl;
cout << "1. Display" << endl;
cout << "2. Append" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case '1':
file.display();
break;
case '2':
file.append();
break;
case '3':
file.fileclose();
exitProgram = true;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
}
return 0;
}
In this program, the `myFile` class is defined with a constructor that takes a
filename as an argument and opens the file in both input and output modes.
The `display()` member function reads the contents of the file and displays them on
the console. It uses the `seekg()` function to set the get position to the beginning of
the file, and then reads each character using `get()`.
The `append()` member function prompts the user to enter a character and
appends it to the end of the file. It uses `seekp()` to set the put position to the end
of the file, and then uses `put()` to write the character.
The program continues to display the menu and accept user input until the user
chooses to exit by selecting the "Exit" option.
#include <iostream>
#include <fstream>
#include <vector>
class Employee {
public:
int emp_id;
string emp_name;
double emp_sal;
void readData() {
cout << "Enter Employee ID: ";
cin >> emp_id;
cin.ignore();
void displayData() {
cout << "Employee ID: " << emp_id << endl;
cout << "Employee Name: " << emp_name << endl;
cout << "Employee Salary: " << emp_sal << endl;
cout << "-------------------------------" << endl;
}
};
outFile << employee.emp_id << "," << employee.emp_name << "," <<
employee.emp_sal << endl;
outFile.close();
}
if (!inFile) {
cout << "Error opening the file." << endl;
return employees;
}
Employee employee;
string line;
employees.push_back(employee);
}
inFile.close();
return employees;
}
cout << "Employee with ID " << empId << " not found." << endl;
}
cout << "Employee with ID " << empId << " not found." << endl;
}
int main() {
string filename = "employee.txt";
vector<Employee> employees = readFromFile(filename);
int choice;
bool exitProgram = false;
while (!exitProgram) {
cout << "Menu:" << endl;
cout << "1. Append Employee" << endl;
cout << "2. Modify Employee" << endl;
cout << "3. Delete Employee" <<
endl;
cout << "4. Display Employees" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1: {
Employee employee;
employee.readData();
appendToFile(filename, employee);
break;
}
case 2: {
int empId;
cout << "Enter the Employee ID to modify: ";
cin >> empId;
modifyEmployee(employees, empId);
break;
}
case 3: {
int empId;
cout << "Enter the Employee ID to delete: ";
cin >> empId;
deleteEmployee(employees, empId);
break;
}
case 4:
displayEmployees(employees);
break;
case 5:
exitProgram = true;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
}
return 0;
}
In this program, the `Employee` class represents an employee object with emp_id,
emp_name, and emp_sal as its members. The class provides member functions to
read and display employee data.
The `readFromFile()` function reads data from the specified file and returns a vector
of `Employee` objects. It reads each line from the file, splits it using the comma as a
delimiter, and creates `Employee` objects from the parsed data.
The `deleteEmployee()` function searches for an employee with a specific empId and
removes them from the vector if found.
In the `main()` function, a menu is displayed with five options: "Append Employee",
"Modify Employee", "Delete Employee", "Display Employees", and "Exit". The user
can choose an option, and based on the input, the corresponding function is called.
The program continues to display the menu and accept user input until the user
chooses to exit by selecting the "Exit" option.
-----------------------------------------------------------------------------------------------------
------------------
Set C
1. A file contains a list of telephone numbers in the following form:
Ajay 12345
Vijay 98765
The names contain only one word and the names and telephone numbers are
separated by white spaces. Write a program to read the file and output the list
in two columns. The names should be left-justified and the numbers right-
justified.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
if (!inFile) {
cout << "Error opening the file." << endl;
return;
}
inFile.close();
}
int main() {
string filename = "telephone_numbers.txt";
formatTelephoneNumbers(filename);
return 0;
}
```
The `left` and `right` manipulators are used to set the alignment of the output.
`left` ensures that the names are left-justified, while `right` ensures that the
numbers are right-justified.
2. Write an interactive, menu-driven program that will access the file created in
the above program, and implement the following tasks.
Determine the telephone number of the specified person.
Determine the name if a telephone number is known.
Update the telephone number, whenever there is a change.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
struct Contact {
string name;
string number;
};
void displayMenu() {
cout << "Menu:" << endl;
cout << "1. Determine telephone number of a person" << endl;
cout << "2. Determine name if a telephone number is known" << endl;
cout << "3. Update telephone number" << endl;
cout << "4. Exit" << endl;
}
ifstream inFile(filename);
if (!inFile) {
cout << "Error opening the file." << endl;
return;
}
string line;
bool found = false;
if (!found) {
cout << "Person not found." << endl;
}
inFile.close();
}
ifstream inFile(filename);
if (!inFile) {
cout << "Error opening the file." << endl;
return;
}
string line;
bool found = false;
if (storedNumber == number) {
cout << "Name associated with the telephone number " << number << " is "
<< name << endl;
found = true;
break;
}
}
if (!found) {
cout << "Telephone number not found." << endl;
}
inFile.close();
}
ifstream inFile(filename);
ofstream outFile("temp.txt");
if (!inFile || !outFile) {
cout << "Error opening the file." << endl;
return;
}
string line;
bool found = false;
if (storedName == name) {
cout << "Enter the new telephone number: ";
cin >> number;
transform(number.begin(), number.end(), number.begin(), ::toupper);
outFile << storedName << " " << number << endl;
cout << "Telephone number updated successfully." << endl;
found = true;
} else {
outFile << line << endl;
}
}
if (!found) {
cout << "Person not found." << endl;
}
inFile.close();
outFile.close();
remove(filename.c_str());
rename("temp.txt", filename.c_str());
}
int main() {
string filename = "telephone_numbers.txt";
int choice;
while (true) {
displayMenu();
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
determinePhoneNumber(filename);
break;
case 2:
determineName(filename);
break;
case 3:
updatePhoneNumber(filename);
break;
case 4:
cout << "Exiting the program. Goodbye!" << endl;
return 0;
default:
cout << "Invalid choice. Please try again." << endl;
}
return 0;
}
The program reads and writes to the file specified by the `filename` variable. Make
sure to adjust this variable to match the actual filename or provide a different
filename.
Note: Make sure to include the necessary header files (`<iostream>`, `<fstream>`,
`<string>`, `<sstream>`, `<algorithm>`) and compile the program with a C++
compiler.