CppLabAssignmentsSem4_Solution
CppLabAssignmentsSem4_Solution
Set A:
1. Write a C++ program to generate multiplication table
solution:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i,n,res=0;
cout<<"enter a number:";
cin>>n;
for(i=1;i<=10;i++)
{
res=n*i;
cout<<n<<'x'<<i<<'='<<res<<endl;
}
return 0;
}
return 0;
}
Set A:
1. Write a C++ program to accept length and width of a rectangle. Calculate and display
perimeter as well as area of a rectangle by using Inlinefunction.
Solution:
#include<iostream>
#include<conio.h>
using namespace std;
inline void area(int l,int w) {
cout<<"area"<<l*w;
}
inline void perimeter(int l,int w) {
cout<<"perimeter"<<2*(l+w);
}
int main()
{
int length = 10, width = 5;
area(length,width);
perimeter(length,width);
return 0;
}
2)Write a C++ program to define power function to calculate x^y. (Use default value as 2 for y).
solution:
#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
int main()
{
int result = power(7);
cout<<"Result:"<<result;
return 0;
}
Set B:
1. Write a C++ program to accept ‘n’ float numbers, store them in an array and print the
alternate elements of an array. (Use dynamic memoryallocation)
soluiton:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int n;
cout<<"enter n:";
cin>>n;
float *ptr;
ptr = new float[n];
cout<<"eneter numbers:";
for(int i=0;i<=n;i++)
{
cin>>ptr[i];
}
cout<<"eneter numbers:";
for(int i=0;i<=n;i++)
{
if(i%2==0)
continue;
cout<<ptr[i]<<endl;
}
return 0;
}
2. WriteaC++programtomodifycontentsofanintegerarray.(UseCall byreference).
solution:
#include<iostream>
#include<conio.h>
using namespace std;
modify(Nums);
cout<<endl<<"after:";
for(int i=0;i<5;i++)
{
cout<<Nums[i]<<endl;
}
return 0;
}
Set C:
1. Create a C++ program to maintain inventory of a book having details Title, Authors[],
Price, Publisher and Stock. Book can be sold, if stock is available, otherwise purchase will be
made. Write a menu driven program to perform following operation:
• Accept book details.
• Sale a book. (Sale contains number of copies to besold.)
• Purchase a book. (Purchase contains number of copies to be purchased)
(Use dynamic memory allocation while accepting author details).
solution:
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
struct book {
string title;
string *Authors;
float price;
string publisher;
int stock;
}b[10];
int main()
{
int n,i;
int no_of_authors;
int choice;
string bookTitle;
int isStock,copies;
while(1)
{
cout<<"___MENU___\n";
cout<<"1.Enter Book Details\n2.Sale Book\n3.view stock\n4.exit\n";
cin>>choice;
switch(choice)
{
case 1: cout<<"How many books you want:";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter Title:";
cin>>b[i].title;
cout<<"Number of Authors";
cin>>no_of_authors;
b[i].Authors = new string[no_of_authors];
for(int j=0;j<no_of_authors;j++)
{
cout<<"Enter author name:";
cin>>b[i].Authors[j];
}
cout<<"Enter price:";
cin>>b[i].price;
cout<<"Enter stock:";
cin>>b[i].stock;
}
break;
{
cout<<"Enter roll";cin>>roll_no;
cout<<"Enter Name";cin>>name;
cout<<"Enter Grade";cin>>std;
}
public: void display()
{ cout<<"Details";
cout<<"Roll:-"<<roll_no<<endl;
cout<<"Name:-"<<name<<endl;
cout<<"Grade:-"<<std<<endl;
}
};
int Student::count = 0;
int main(){
int n;
Student s[10];
cout<<"Enter number of student:"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
s[i].accept();
Student::count++;
}
cout<<endl<<"details:";
for(int i=0;i<n;i++)
{
s[i].display();
}
cout<<"Total students:"<<Student::count;
return 0;
}
2)Write a C++ program to calculate maximum and minimum of two integer numbers of two
different classes.(Use friendfunction)
Solution:
#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
class xyz;
class abc
{
int n1;
public:
abc()
{cout<<"\nEnter no : ";
cin>>n1;
}
void display()
{
cout<<"\nNo1 = "<<n1;
}
friend void max(abc,xyz);
};
class xyz
{
int n2;
public:
xyz()
{
cout<<"\nEnter no";
cin>>n2;
}
void display()
{
cout<<"\nNo2 = "<<n2;
}
friend void max(abc,xyz);
};
void max(abc ob1,xyz ob2)
{
if(ob1.n1>ob2.n2)
cout<<"\nmax = "<<ob1.n1;
else
cout<<"\nmax = "<<ob2.n2;
}
int main()
{
abc a;
xyz z;
a.display();
z.display();
max(a,z);
return 0;
}
SET B :
1)Write a C++ program using class to accept and display ‘n’ Products information, also
display information of a product having maximum price. (Use array of objects and
dynamic memoryallocation)
Solution:
#include<iostream>
#include<string.h>
using namespace std;
class Product
{
public:
int pcode;
string pname;
float price;
public:
void accept()
{
cout<<"enter product code: ";cin>>pcode;
cout<<"enter product name: ";cin>>pname;
cout<<"enter product price: ";cin>>price;
}
void display()
{
cout<<"code: "<<pcode<<endl;
cout<<"name: "<<pname<<endl;
cout<<"price: "<<price<<endl;
}
void max(Product p[], int n)
{
int max=p[0].price;
for(int i=1;i<n;i++)
{
if(p[i].price>max)
max=p[i].price;
}
cout<<"max: "<<max;
}
};
int main()
{
int n;
Product *p;
cout<<"Enter no of product:";
cin>>n;
p = new Product[n];
for(int i=0;i<n;i++)
{
p[i].accept();
}
for(int i=0;i<n;i++)
{
p[i].display();
}
p[0].max(p,n);
return 0;
}
2. Write a C++ program to create a class Distance with data members feet and inches. Write
member functions for the following:
a. To acceptdistance
b. To displaydistance
c. To add two distanceobjects
(Use object as a function argument and function returning object)
Solution:
#include<iostream>
#include<string.h>
using namespace std;
class Distance
{
public:
float feet;
float inches;
public:
void accept()
{
cout<<"Enter feet: ";cin>>feet;
cout<<"Enter inches: "<<endl;cin>>inches;
}
void display()
{
cout<<"Distance = "<<feet<<" feets";
cout<<" and "<<inches<<" inches";
}
int main()
{
Distance obj, obj1, obj2;
obj1.accept();
obj1.display();
obj2.accept();
obj2.display();
obj = obj.add(obj1,obj2);
cout<<"addition=";
obj.display();
return 0;
}
SET C:
1. Write a C++ program to calculate multiplication of two integer numbers of two different
classes. (Use friend class).
Solution:
#include<iostream>
#include<string.h>
using namespace std;
class A
{
int num;
public:
void setvalue(int i)
{
num=i;
}
class MyNumber {
private:
int num1;
int num2;
int num3;
public:
MyNumber() : num1(0), num2(0), num3(0) {}
MyNumber(int n1, int n2, int n3) : num1(n1), num2(n2), num3(n3) {}
MyNumber(int n1, int n2, float n3 = 0) : num1(n1), num2(n2), num3(n3) {}
void displayAverage() {
double average = (num1 + num2 + num3) / 3.0;
std::cout << "Average of the three numbers: " << average << std::endl;
}
};
int main() {
MyNumber obj1;
obj1.displayAverage();
obj2.displayAverage();
obj3.displayAverage();
return 0;
}
2)WriteaC++programto create a class‘MyPoint’ with two integer data members as x & y. Define
copy constructor to copy one object to another. (Use Default and parameterized
constructor to initialize the appropriate objects) Write a C++ program to illustrate the use
of above class.
solution:
#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
class point
{
int x,y;
public:
point()
{
}
point(int a,int b)
{
x=a;
y=b;
}
point(point &ob2)
{
x=ob2.x;
y=ob2.y;
}
void display()
{
cout<<"\nx = ";
cout<<x;
cout<<"\t y = ";
cout<<y;
}
};
int main()
{
point ob1(100,200);
int n,m;
ob1.display();
point ob2(ob1);
cout<<"\nAfter copy comstructor .\n";
ob2.display();
cout<<"\nEnter number : ";
cin>>n;
cout<<"\nEnter number : ";
cin>>m;
point ob3(n,m);
ob3.display();
ob2=ob3;
cout<<"\nAfter copy comstructor .\n";
ob2.display();
return 0;
}
Set B:
1. Write a C++ program to create a class ‘MyArray’ which contains single dimensional
integer array of given size. Write a member function to display even and odd numbers
from a given array. (Use Dynamic Constructor to allocate and Destructor to free memory
of anobject)
Soloution:
#include <iostream>
class MyArray {
private:
int *arr;
int size;
public:
MyArray(int s) {
size = s;
arr = new int[size];
for(int i=0;i<size;i++)
{
std::cout<<"enter a number: ";
std::cin>>arr[i];
}
}
~MyArray() {
delete[] arr;
}
void displayEvenOdd() {
std::cout << "Even numbers: ";
for (int i = 0; i < size; ++i) {
if (arr[i] % 2 == 0) {
std::cout << arr[i] << " ";
}
}
std::cout << std::endl;
int main() {
MyArray myArr(5);
myArr.displayEvenOdd();
return 0;
}
2)Write a C++ program to create a class ‘MyMatrix’ which contains two dimensional
integer array of size mXn. Write a member function to display sum of all elements of
entered matrix. (Use Dynamic Constructor for allocating memory and Destructor to free
memory of anobject)
Soloution:
#include <iostream>
using namespace std;
class MyMatrix {
public:
int **matrix;
int rows, cols;
public:
MyMatrix(int m, int n) {
rows = m;
cols = n;
matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
}
~MyMatrix() {
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
}
void displaySum() {
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum += matrix[i][j];
}
}
cout << "Sum of all elements in the matrix: " << sum << endl;
}
};
int main() {
int m, n;
cout << "Enter the number of rows and columns for the matrix: ";
cin >> m >> n;
matrixObj.displaySum();
return 0;
}
SET C:
1. Create a C++ class ‘Student’ with data members Rollno, Name,Number of subjects, Marks
of each subject (Number of subjects varies for each student). Writea parameterized
constructor which initializes rollno, name & Number of subjects and creates the array of
marksdynamically.Displaythedetailsofallstudentswithpercentageandclassobtained
Solution:
#include <iostream>
#include <string>
class Student {
private:
int Rollno;
std::string Name;
int NumSubjects;
int* Marks;
public:
Student(int rollno, const std::string& name, int numSubjects) : Rollno(rollno), Name(name),
NumSubjects(numSubjects) {
Marks = new int[numSubjects];
}
void displayDetails() {
int totalMarks = 0;
for (int i = 0; i < NumSubjects; ++i) {
std::cout << "Enter marks for subject " << i + 1 << ": ";
std::cin >> Marks[i];
totalMarks += Marks[i];
}
~Student() {
delete[] Marks;
}
};
int main() {
Student student1(1, "Alice", 3);
student1.displayDetails();
return 0;
}
Assignment No. 5:
SET A:
1. DesignabaseclassProduct(Product_Id,Product_Name,Price).DeriveaclassDiscount
(Discount_In_Percentage) from Product. A customer buys ‘n’ products. Write a C++
program to calculate total price, totaldiscount.
Solution:
#include <iostream>
#include <string>
class Product {
protected:
int Product_Id;
std::string Product_Name;
double Price;
public:
Product(int id, std::string name, double price) : Product_Id(id), Product_Name(name), Price(price)
{}
public:
Discount(int id, std::string name, double price, double discount) : Product(id, name, price),
Discount_In_Percentage(discount) {}
int main() {
int n = 3; // Number of products bought
Discount product1(1, "Product A", 10.0, 20.0); // Product with 20% discount
Discount product2(2, "Product B", 15.0, 15.0); // Product with 15% discount
Discount product3(3, "Product C", 20.0, 10.0); // Product with 10% discount
return 0;
}
Set B:
1. Design two base classes Personnel (name, address, email-id, birth date) and Academic
(marksintenth,marksintwelth,classobtained).DeriveaclassBio-data fromboththese
classes. Write a C++ program to prepare a bio-data of a student having Personnel and
Academicinformation.
Solution:
#include <iostream>
#include <string>
class Personnel {
public:
std::string name;
std::string address;
std::string email_id;
std::string birth_date;
};
class Academic {
public:
int marks_in_tenth;
int marks_in_twelfth;
std::string class_obtained;
};
int main() {
BioData student;
student.displayBioData();
return 0;
}
2)reate a base class Student(Roll_No, Name) which derives two classes Academic_Marks(Mark1,
Mark2, Mark3) and Extra_Activities_Marks(Marks). Class Result(Total_Marks, Grade) inherits
both Academic_Marks and Extra_Activities_Marks classes. (Use Virtual BaseClass)
Write a C++ menu driven program to perform the following functions:
i. Build a mastertable.
ii. Calculate Total_marks and grade
Solution:
#include <iostream>
#include <string>
using namespace std;
class Student {
protected:
int Roll_No;
string Name;
public:
void input() {
cout << "Enter Roll Number: ";
cin >> Roll_No;
cout << "Enter Name: ";
cin >> Name;
}
};
void display_result() {
cout << "\nStudent Details:\nRoll Number: " << Roll_No << "\nName: " << Name;
cout << "\nTotal Marks: " << Total_Marks << "\nGrade: " << Grade << endl;
}
};
int main() {
Result R;
R.input();
R.input_marks();
R.input_extra_marks();
R.calculate_result();
R.display_result();
return 0;
}
Set C:
1. Create a base class Student(Roll_No, Name, Class) which derives two classes
Internal_Marks(IntM1, IntM2, IntM3, IntM4, IntM5) and External_Marks(ExtM1 ExtM2,
ExtM3, ExtM4, ExtM5). Class Result(T1, T2, T3, T4, T5) inherits both Internal_Marks
and External_Marks classes. (Use Virtual BaseClass)
Write a C++ menu driven program to perform the following functions:
i. To Accept and display studentdetails
ii. Calculate Subject wise total marksobtained.
iii.Check whether student has passed in Internal and External Exam of each subject.
Also check whether he has passed in respective subject or not and display result
accordingly
Solution:
#include <iostream>
#include <string>
class Student {
public:
int Roll_No;
std::string Name;
std::string Class;
};
return 0;
}
Assignment No. 6:
SET A
1)Write a C++ program to calculate area of cone, sphere and circle by using function
overloading.
soluiton:
#include <iostream>
#include<math.h>
using namespace std;
#define PI 3.14159
int main() {
double coneRadius = 3.0, coneHeight = 4.0;
double sphereRadius = 2.0;
int circleRadius = 5;
std::cout << "Area of Cone: " << calculateArea(coneRadius, coneHeight) << std::endl;
std::cout << "Area of Sphere: " << calculateArea(sphereRadius) << std::endl;
std::cout << "Area of Circle: " << calculateArea(circleRadius) << std::endl;
return 0;
}
2)Create a base class Conversion. Derive three different classes Weight (Gram, Kilogram),
Volume(Milliliter, Liter), Currency(Rupees, Paise) from Conversion class. Write a C++
programtoperformread,convertanddisplayoperations.(UsePurevirtualfunction).
soluiton:
#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
class conversion
{ public:
virtual void accept1()=0;
virtual void accept2()=0;
virtual void convert1()=0;
virtual void convert2()=0;
};
class weight:public conversion
{ public:
float gm,kgm;
void accept1()
{cout<<"Enter grams to convert : ";cin>>gm;}
void accept2()
{cout<<"Enter kilograms to convert : ";cin>>kgm;}
void convert1()
{cout<<"After conversion gm = "<<gm/1000<<" kgm\n";}
void convert2()
{cout<<"After conversion kgm = "<<kgm*1000<<" gm\n";}
};
class volume:public conversion
{ public:
float ml,ltr;
void accept1()
{cout<<"\n Enter mililiter to convert : ";
cin>>ml;}
void accept2()
{cout<<"\n Enter liter to convert : ";
cin>>ltr;}
void convert1()
{cout<<"After conversion ml = "<<ml/1000<<" ltr\n";}
void convert2()
{cout<<"After conversion ltr = "<<ltr*1000<<" ml\n";}
};
class currency:public conversion
{
public:
float ps,rs;
void accept1()
{
cout<<"Enter paise to convert :";
cin>>ps;
}
void accept2()
{
cout<<"Enter rupees to convert : ";
cin>>rs;
}
void convert1()
{
cout<<"After conversion ps = "<<ps/100<<" rs\n";
}
void convert2()
{
cout<<"After conversion rs = "<<rs*100<<" ps\n";
}
};
int main()
{
int ch;
weight w;
volume v;
currency c;
do
{
cout<<"\nEnter your choice\n";
cout<<"1.weight\t2.volume\t3.currency\t4.exit\n";
cin>>ch;
switch(ch)
{
case 1: int ch1;
cout<<"Enter your choice to convert weight\n";
cout<<"1.gm to kgm\t2.kgm to gm \n";
cin>>ch1;
if(ch1==1)
{
w.accept1();
w.convert1();
break;
}
else if(ch1==2)
{
w.accept2();
w.convert2();
break;}
else
{cout<<"wrong choice";
break;}
case 2: int ch2;
cout<<"Enter choice to convert to volume\n";
cout<<"1.ml to ltr\t2.ltr to ml \n";cin>>ch2;
if(ch2==1)
{v.accept1();
v.convert1();
break;}
else if(ch2==2)
{v.accept2();
v.convert2();
break;}
else
{cout<<"wrong choice";
break;}
case 3:int ch3;
cout<<"Enter choice to convert currency";
cout<<"\n1psp to rp\t2.rp to ps \n";cin>>ch3;
if(ch3==1)
{c.accept1();
c.convert1();
break;}
else if(ch3==2)
{c.accept2();
c.convert2();
break;}
else
{cout<<"wrong choice"; break;}
case 4:break;
default: cout<<"Enter valid choice";
break;
}
}while(ch!=4);
return 0;
}
SET B:
1)Create a class Date with members as dd, mm, yyyy. Write a C++ program for overloading
operators >> and <<to accept and display aDate.
Solution:
#include <iostream>
using namespace std;
class Date {
int dd, mm, yyyy;
public:
friend istream& operator>>(istream& input, Date& date);
friend ostream& operator<<(ostream& output, const Date& date);
};
int main() {
Date d;
2)Create a base class Shape. Derive three different classes Circle, Rectangle and Triangle
from Shape class. Write a C++ program to calculate area of Circle, Rectangle and
Triangle. (Use pure virtual function).
Solution:
#include <iostream>
class Shape {
public:
virtual float calculateArea() = 0;
};
class Circle : public Shape {
private:
float radius;
public:
Circle(float r) : radius(r) {}
public:
Rectangle(float l, float w) : length(l), width(w) {}
public:
Triangle(float b, float h) : base(b), height(h) {}
int main() {
Circle c(5);
Rectangle r(4, 6);
Triangle t(3, 8);
return 0;
}
SET C:
1)Create a class MyString which contains a character pointer (Use new and delete
operator).Write a C++ program to overload followingoperators:
i. ! To change the case of each alphabet from givenstring
ii. [] To print a character present at specified index
Solution:
#include <iostream>
#include <cstring>
class MyString {
private:
char* str;
public:
MyString(const char* s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
~MyString() {
delete[] str;
}
MyString operator!() {
char* temp = new char[strlen(str) + 1];
strcpy(temp, str);
for (size_t i = 0; i < strlen(temp); ++i) {
if (isalpha(temp[i])) {
if (islower(temp[i])) {
temp[i] = toupper(temp[i]);
} else {
temp[i] = tolower(temp[i]);
}
}
}
MyString result(temp);
delete[] temp;
return result;
}
void print() {
std::cout << str << std::endl;
}
};
int main() {
MyString myStr("Hello, World!");
return 0;
}
Assignment No. 7:
SET A:
1)1. Write a C++ program to create a class Employee which contains data members as
Emp_Id, Emp_Name, Basic_Salary, HRA, DA, Gross_Salary. Write member functions to
accept Employee information.Calculate and displayGross salary of an employee.62(DA=25% of
Basic salary and HRA=40%ofBasic salary)(Useappropriatemanipulators to display employee
information in given format:-Emp_IdandEmp_Name should be left justified and Basic_Salary,
HRA, DA, Gross salary Right justified with a precision of three digits)
Solution:
#include <iostream>
#include <iomanip>
class Employee {
private:
int Emp_Id;
std::string Emp_Name;
double Basic_Salary;
double HRA;
double DA;
double Gross_Salary;
public:
void acceptEmployeeInformation() {
std::cout << "Enter Employee ID: ";
std::cin >> Emp_Id;
std::cout << "Enter Employee Name: ";
std::cin.ignore();
std::getline(std::cin, Emp_Name);
std::cout << "Enter Basic Salary: ";
std::cin >> Basic_Salary;
}
void calculateGrossSalary() {
HRA = 0.4 * Basic_Salary;
DA = 0.25 * Basic_Salary;
Gross_Salary = Basic_Salary + HRA + DA;
}
void displayEmployeeInformation() {
std::cout << std::left << std::setw(15) << "Emp ID: " << std::left << std::setw(15) << Emp_Id <<
std::right << std::setw(15) << std::fixed << std::setprecision(3) << "Basic Salary: " << Basic_Salary <<
std::endl;
std::cout << std::left << std::setw(15) << "Emp Name: " << std::left << std::setw(15) <<
Emp_Name << std::right << std::setw(15) << std::fixed << std::setprecision(3) << "HRA: " << HRA
<< std::endl;
std::cout << std::left << std::setw(15) << "DA: " << std::left << std::setw(15) << DA << std::right
<< std::setw(15) << std::fixed << std::setprecision(3) << "Gross Salary: " << Gross_Salary <<
std::endl;
}
};
int main() {
Employee emp;
emp.acceptEmployeeInformation();
emp.calculateGrossSalary();
emp.displayEmployeeInformation();
return 0;
}
2)Write a C++ program to create a class Teacher which contains data members as
Teacher_Name, Teacher_City, Teacher_Contact_Number. Write member functions to
accept and display five teachers information. Design User defined Manipulator to print
Teacher_Contact_Number.(ForContactNumbersetrightjustification,maximumwidthto 10
and fill remaining spaces with‘*’)
Solution:
#include <iostream>
#include <iomanip>
#include <string>
class Teacher {
private:
std::string Teacher_Name;
std::string Teacher_City;
std::string Teacher_Contact_Number;
public:
void acceptTeacherInfo() {
std::cout << "Enter Teacher Name: ";
std::cin >> Teacher_Name;
std::cout << "Enter Teacher City: ";
std::cin >> Teacher_City;
std::cout << "Enter Teacher Contact Number: ";
std::cin >> Teacher_Contact_Number;
}
void displayTeacherInfo() {
std::cout << "Teacher Name: " << Teacher_Name << std::endl;
std::cout << "Teacher City: " << Teacher_City << std::endl;
std::cout << "Teacher Contact Number: " << std::setw(10) << std::right <<
Teacher_Contact_Number << std::endl;
}
};
int main() {
Teacher teachers[3];
return 0;
}
SET B:
1. Create a C++ class Train with data members as Train_No,Train_Name,No_of
Seats,Source_Station,Destination_Station. Write necessary member functions for the following:
i. Accept details of n trains.
ii. Display all train details.
iii. Display details of train from specified starting station and ending station by user
Solution:
#include <iostream>
#include <vector>
#include <string>
class Train {
private:
int Train_No;
std::string Train_Name;
int No_of_Seats;
std::string Source_Station;
std::string Destination_Station;
public:
void AcceptDetails();
void DisplayAllTrainDetails();
void DisplayTrainDetailsByStations(const std::string& startStation, const std::string& endStation);
};
void Train::AcceptDetails() {
std::cout << "Enter Train Number: ";
std::cin >> Train_No;
std::cin.ignore();
void Train::DisplayAllTrainDetails() {
std::cout << "Train Number: " << Train_No << std::endl;
std::cout << "Train Name: " << Train_Name << std::endl;
std::cout << "Number of Seats: " << No_of_Seats << std::endl;
std::cout << "Source Station: " << Source_Station << std::endl;
std::cout << "Destination Station: " << Destination_Station << std::endl;
}
int main() {
int n;
std::cout << "Enter the number of trains: ";
std::cin >> n;
std::vector<Train> trains(n);
std::cout << "\nTrain Details from " << start << " to " << end << ":" << std::endl;
for (int i = 0; i < n; ++i) {
trains[i].DisplayTrainDetailsByStations(start, end);
}
return 0;
}
2)Create a C++ class Manager with data members Manager_Id, Manager_Name,
Mobile_No., Salary. Write necessary member functions for the following:
i. Accept details of n managers
ii. Display manager details in ascending order of theirsalary.
iii. Display details of a particular manager. (Use Array of object and Use appropriate
manipulators.)
Solution
#include <iostream>
#include <iomanip>
class Manager {
private:
int Manager_Id;
std::string Manager_Name;
long Mobile_No;
double Salary;
public:
void AcceptDetails();
void DisplayInAscendingOrder(Manager arr[], int n);
void DisplayManagerDetails(int id, Manager arr[], int n);
};
void Manager::AcceptDetails() {
std::cout << "Enter Manager ID: ";
std::cin >> Manager_Id;
std::cout << "Enter Manager Name: ";
std::cin >> Manager_Name;
std::cout << "Enter Mobile Number: ";
std::cin >> Mobile_No;
std::cout << "Enter Salary: ";
std::cin >> Salary;
}
int main() {
int n;
std::cout << "Enter the number of managers: ";
std::cin >> n;
Manager managers[n];
return 0;
}
Set C
1)Create a C++ class Marksheet with data members Seat_No., Student_Name, Class,
Subject_Name, Int_Marks, Ext_Marks, Total, Grand_Total, Percentage, Grade. Write
member function to accept Student information for 4 subjects. Calculate Total,
Grand_Total, Percentage, Grade and display Marksheet. (Use user defined manipulator)
Solution:
#include <iostream>
#include <iomanip>
#include <string>
class Marksheet {
private:
int Seat_No;
string Student_Name;
string Class;
string Subject_Name[4];
int Int_Marks[4];
int Ext_Marks[4];
int Total[4];
int Grand_Total;
float Percentage;
char Grade;
public:
void acceptStudentInfo();
void calculateMarksheet();
void displayMarksheet();
};
void Marksheet::acceptStudentInfo() {
cout << "Enter Seat Number: ";
cin >> Seat_No;
cout << "Enter Student Name: ";
cin.ignore();
getline(cin, Student_Name);
cout << "Enter Class: ";
getline(cin, Class);
void Marksheet::displayMarksheet() {
cout << "\n----- Marksheet -----\n";
cout << "Seat Number: " << Seat_No << endl;
cout << "Student Name: " << Student_Name << endl;
cout << "Class: " << Class << endl;
cout << "\nGrand Total Marks: " << Grand_Total << endl;
cout << "Percentage: " << fixed << setprecision(2) << Percentage << "%" << endl;
cout << "Grade: " << Grade << endl;
}
int main() {
Marksheet student;
student.acceptStudentInfo();
student.calculateMarksheet();
student.displayMarksheet();
return 0;
}
Assignment No. 8
SET A:
1. Write a C++ program to accept ‘n’ numbers from user through Command LineArgument.
Store all positive and negative numbers in file “Positive.txt” and “Negative.txt”
respectively.
Solution:
#include <iostream>
#include <fstream>
std::ofstream positiveFile("positive.txt");
std::ofstream negativeFile("negative.txt");
positiveFile.close();
negativeFile.close();
std::cout << "Positive and negative numbers stored in 'positive.txt' and 'negative.txt'
respectively.\n";
return 0;
}
2)Create a C++ class Employee with data members Emp_No, Emp_Name, Emp_Marks.
Write necessary member functions for thefollowing:
i. Accept the details and store it into the file“Emp.dat”
ii. Read the details from file and displayit.
iii. Update a given record into thefile.
Solution:
#include <iostream>
#include <fstream>
#include <string>
class Employee {
private:
int Emp_No;
std::string Emp_Name;
float Emp_Marks;
public:
void AcceptDetails();
void DisplayDetails();
void UpdateRecord(int empNo);
};
void Employee::AcceptDetails() {
std::ofstream file("Emp.dat", std::ios::app);
std::cout << "Enter Employee Number: ";
std::cin >> Emp_No;
std::cout << "Enter Employee Name: ";
std::cin >> Emp_Name;
std::cout << "Enter Employee Marks: ";
std::cin >> Emp_Marks;
file << Emp_No << " " << Emp_Name << " " << Emp_Marks << std::endl;
file.close();
}
void Employee::DisplayDetails() {
std::ifstream file("Emp.dat");
while (file >> Emp_No >> Emp_Name >> Emp_Marks) {
std::cout << "Employee Number: " << Emp_No << ", Name: " << Emp_Name << ", Marks: " <<
Emp_Marks << std::endl;
}
file.close();
}
int main() {
Employee emp;
emp.AcceptDetails();
emp.DisplayDetails();
int empNoToUpdate;
std::cout << "Enter Employee Number to Update: ";
std::cin >> empNoToUpdate;
emp.UpdateRecord(empNoToUpdate);
emp.DisplayDetails();
return 0;
}
SET B:
1)Write a C++ program to create a class Newspaper with data members Name, publisher,
cost. Write necessary member functions for thefollowing:
i. Accept details for ‘n’ Newspapers from user and store it in a file
“Newspaper.txt”.
ii. Display details of Newspapers from a file.
iii. Count the number of objects stored in afile
SOLUTION:
#include <iostream>
#include <fstream>
class Newspaper {
public:
std::string Name;
std::string Publisher;
double Cost;
void AcceptDetails();
void DisplayDetails();
static int CountObjects();
};
void Newspaper::AcceptDetails() {
std::cout << "Enter Name: ";
std::cin >> Name;
std::cout << "Enter Publisher: ";
std::cin >> Publisher;
std::cout << "Enter Cost: ";
std::cin >> Cost;
void Newspaper::DisplayDetails() {
std::ifstream file("Newspaper.txt");
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
}
int Newspaper::CountObjects() {
std::ifstream file("Newspaper.txt");
int count = 0;
std::string line;
while (std::getline(file, line)) {
count++;
}
file.close();
return count;
int main() {
int n;
std::cin >> n;
std::cout << "\nNumber of Newspapers stored: " << Newspaper::CountObjects() << std::endl;
return 0;
}
2)Create a C++ class ‘city’ with data members name and STD code. Accept ‘n’ cities with
STD codes from user. Store this data in the file ‘cities.txt’. Write a program that reads the
data from file cities.txt display the list of city with STD codes from afile
SOLUTION:
#include <iostream>
#include <fstream>
#include <string>
class City {
public:
std::string name;
int stdCode;
};
int main() {
int n;
std::cout << "Enter the number of cities: ";
std::cin >> n;
City cities[n];
std::ifstream readFile("cities.txt");
if (readFile.is_open()) {
std::string line;
while (getline(readFile, line)) {
std::cout << line << std::endl;
}
readFile.close();
}
return 0;
}
Assignment No. 9:
Set A:
1. Write a C++ template program to accept array elements of type integers & characters. Reverse
an array of both types.
Solution:
#include <iostream>
int main() {
int intArray[] = {1, 2, 3, 4, 5};
char charArray[] = {'a', 'b', 'c', 'd', 'e'};
reverseArray(intArray);
reverseArray(charArray);
return 0;
}
2. Write a C++ program to find maximum & minimum of two integer numbers and twofloat
numbers by using function template
Soluiton:
#include <iostream>
int main() {
int intNum1 = 10, intNum2 = 20;
float floatNum1 = 10.5, floatNum2 = 20.5;
std::cout << "Maximum of two integers: " << findMax(intNum1, intNum2) << std::endl;
std::cout << "Minimum of two integers: " << findMin(intNum1, intNum2) << std::endl;
std::cout << "Maximum of two floats: " << findMax(floatNum1, floatNum2) << std::endl;
std::cout << "Minimum of two floats: " << findMin(floatNum1, floatNum2) << std::endl;
return 0;
}
Set B:
1. Write a C++ program to define class template for calculating the square of givennumbers with
different data types .
#include <iostream>
int main() {
SquareCalculator<int> intSquare;
SquareCalculator<float> floatSquare;
int numInt = 5;
float numFloat = 3.5;
std::cout << "Square of " << numInt << " is: " << intSquare.calculateSquare(numInt) << std::endl;
std::cout << "Square of " << numFloat << " is: " << floatSquare.calculateSquare(numFloat) <<
std::endl;
return 0;
}
2. Write C++ template program to find the area of circle & rectangle with different data types
Solution:
#include <iostream>
template <typename T>
T calculateCircleArea(T radius) {
return 3.14159 * radius * radius;
}
int main() {
int intRadius = 5;
float floatRadius = 3.5;
double doubleRadius = 7.2;
int intLength = 4;
int intWidth = 6;
std::cout << "Area of Circle with int radius: " << calculateCircleArea(intRadius) << std::endl;
std::cout << "Area of Circle with float radius: " << calculateCircleArea(floatRadius) << std::endl;
std::cout << "Area of Circle with double radius: " << calculateCircleArea(doubleRadius) <std::endl;
std::cout << "Area of Rectangle with int dimensions: " << calculateRectangleArea(intLength,
intWidth) << std::endl;
std::cout << "Area of Rectangle with float dimensions: " << calculateRectangleArea(floatLength,
floatWidth) << std::endl;
std::cout << "Area of Rectangle with double dimensions: " <<
calculateRectangleArea(doubleLength, doubleWidth) << std::endl;
return 0;
}
Set C:
1. Write C++ template program to implement stack & its operations like push & pop.
Solution:
#include <iostream>
#include <vector>
template <typename T>
class Stack {
private:
std::vector<T> elements;
public:
void push(const T& element) {
elements.push_back(element);
}
void pop() {
if (!elements.empty()) {
elements.pop_back();
}
}
T top() const {
if (!elements.empty()) {
return elements.back();
}
throw std::out_of_range("Stack<>::top(): empty stack");
}
int main() {
Stack<int> stack;
stack.push(1);
stack.push(2);
stack.push(3);