Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

CppLabAssignmentsSem4_Solution

The document contains multiple C++ programming assignments covering various topics such as generating multiplication tables, Fibonacci series, patterns, and class structures. It includes solutions for programs that utilize inline functions, dynamic memory allocation, friend functions, and copy constructors. Each assignment is structured in sets with specific tasks and corresponding code implementations.

Uploaded by

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

CppLabAssignmentsSem4_Solution

The document contains multiple C++ programming assignments covering various topics such as generating multiplication tables, Fibonacci series, patterns, and class structures. It includes solutions for programs that utilize inline functions, dynamic memory allocation, friend functions, and copy constructors. Each assignment is structured in sets with specific tasks and corresponding code implementations.

Uploaded by

shraddhavinod1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Assignment-1

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;
}

2. Write a C++ program to display first ‘n’ numbers of Fibonacci series.


solution:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int a=0,b=1;
int c=0,n;

cout<<"enter number for fibbonacci series:";


cin>>n;
cout<<a<<endl<<b<<endl;
for(int i=2;i<=n;i++)
{
c=a+b;
cout<<c<<endl;
a=b;
b=c;
}
return 0;
}
SET B:
1. WriteaC++program to print the following pattern.
A
BC
DEF
GHIJ
Solution:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i,j;
char ch = 'A';
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
cout<<ch++;
}
cout<<endl;
}

return 0;
}

2. Write a C++ program to print the followingpattern


*
**
***
****
solution:
#include<iostream>
#include<conio.h>
int main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=4;j++)
{
if(j<=4-i)
std:: cout<<' ';
else
std::cout<<'*';
}
std::cout<<endl;
}
return 0; }
Set C:
1. Write a C++ program to print the followingpattern
*
**
***
****
*****
solution:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i,j;
int n = 5;
for(i=1;i<=n;i++)
{
for(j=n;j>=1;j--)
{
if(i>=j)
cout<<"* ";
else
cout<<" ";
}
cout<<endl;
}
return 0;
}
ASSIGNMENT-2

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 power(int x,int y=2) {


int res = x;
for(int i=1;i<y;i++)
{
res*= x;
}
return res;
}

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;

void modify(int numbers[]){


for(int i=0;i<5;i++)
{
numbers[i] = numbers[i]*2;
}
return;
}
int main()
{
int Nums[5] = {1,2,3,4,5};
cout<<"before:";
for(int i=0;i<5;i++)
{
cout<<Nums[i]<<endl;
}

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;

case 2: cout<<"enter book Title: ";


cin>>bookTitle;
for(int i=0;i<5;i++)
{
if(b[i].title == bookTitle)
{ isStock=b[i].stock;
if(isStock>0)
{
cout<<"number of copies to sell:";
cin>>copies;
b[i].stock=b[i].stock-copies;
cout<<"copies sold";
}
else
{
cout<<"Stock is empty!Purchase books now:";
cout<<"number of copies to purchase:";
cin>>copies;
b[i].stock = b[i].stock+copies;
cout<<"copies purchased";
}
}
}
break;
case 3: cout<<"enter book Title";
cin>>bookTitle;
for(int i=0;i<5;i++)
{
if(b[i].title == bookTitle)
isStock=b[i].stock;
}
cout<<"\n stock availble:";
cout<<isStock;
break;
case 4:exit(0);
}
}
return 0;
}
Assignment No. 3:
SET A:
1. Write a C++ program to create a class Student with data members Roll_No,
Student_Name, Class. Write member functions to accept and display Student information .(Use
Static data member and Static member function).
solution:
#include<iostream>
#include<string.h>
using namespace std;
class Student {
private: int roll_no;
private: string name;
private: int std;
public:static int count;

public: void accept()

{
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";
}

Distance add(Distance obj1, Distance obj2)


{
Distance obj3;
obj3.feet = obj1.feet + obj2.feet;
obj3.inches = obj1.inches + obj2.inches;
return obj3;
}
};

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;
}

friend class B; //making B class, a friend class of Aclass


};
class B
{ int num2 = 3;
public:
void display(A &a)
{
cout<<"Value of multiplcation is : "<<a.num * num2;
}
};
int main()
{
A a_obj;
a_obj.setvalue(10);
B b_obj;
b_obj.display(a_obj);
return 0;
}
Assignment No. 4:
Set A:
1. Write a C++ program to create a class ‘MyNumber’ with three data members of type
integer. Create and initialize the object using default constructor, parameterized
constructor and parameterized constructor with default value. Write a member function to
display average of given three numbers for all objects.
Solution:
#include <iostream>

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;

MyNumber obj2(10, 20, 30);


MyNumber obj3(5, 15);

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;

std::cout << "Odd 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;

MyMatrix matrixObj(m, n);

cout << "Enter the elements of the matrix:" << endl;


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> matrixObj.matrix[i][j];
}
}

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];
}

double percentage = static_cast<double>(totalMarks) / NumSubjects;


std::cout << "Roll No: " << Rollno << std::endl;
std::cout << "Name: " << Name << std::endl;
std::cout << "Percentage: " << percentage << "%" << std::endl;

if (percentage >= 75) {


std::cout << "Class: Distinction" << std::endl;
} else if (percentage >= 60) {
std::cout << "Class: First Class" << std::endl;
} else if (percentage >= 50) {
std::cout << "Class: Second Class" << std::endl;
} else {
std::cout << "Class: Pass Class" << std::endl;
}
}

~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)
{}

double CalculateTotalPrice(int quantity) {


return Price * quantity;
}
};

class Discount : public Product {


protected:
double Discount_In_Percentage;

public:
Discount(int id, std::string name, double price, double discount) : Product(id, name, price),
Discount_In_Percentage(discount) {}

double CalculateTotalDiscount(int quantity) {


return (Price * Discount_In_Percentage / 100) * quantity;
}
};

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

double total_price = product1.CalculateTotalPrice(n) + product2.CalculateTotalPrice(n) +


product3.CalculateTotalPrice(n);
double total_discount = product1.CalculateTotalDiscount(n) + product2.CalculateTotalDiscount(n) +
product3.CalculateTotalDiscount(n);

std::cout << "Total Price: $" << total_price << std::endl;


std::cout << "Total Discount: $" << total_discount << std::endl;

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;
};

class BioData : public Personnel, public Academic {


public:
void displayBioData() {
std::cout << "Name: " << name << std::endl;
std::cout << "Address: " << address << std::endl;
std::cout << "Email ID: " << email_id << std::endl;
std::cout << "Birth Date: " << birth_date << std::endl;
std::cout << "Marks in Tenth: " << marks_in_tenth << std::endl;
std::cout << "Marks in Twelfth: " << marks_in_twelfth << std::endl;
std::cout << "Class Obtained: " << class_obtained << std::endl;
}
};

int main() {
BioData student;

student.name = "John Doe";


student.address = "123 Main Street";
student.email_id = "john.doe@example.com";
student.birth_date = "01/01/2000";
student.marks_in_tenth = 95;
student.marks_in_twelfth = 98;
student.class_obtained = "A+";

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;
}
};

class Academic_Marks : virtual public Student {


protected:
int Mark1, Mark2, Mark3;
public:
void input_marks() {
cout << "Enter Academic Marks (Mark1 Mark2 Mark3): ";
cin >> Mark1 >> Mark2 >> Mark3;
}
};

class Extra_Activities_Marks : virtual public Student {


protected:
int Marks;
public:
void input_extra_marks() {
cout << "Enter Extra Activities Marks: ";
cin >> Marks;
}
};

class Result : public Academic_Marks, public Extra_Activities_Marks {


protected:
int Total_Marks;
char Grade;
public:
void calculate_result() {
Total_Marks = Mark1 + Mark2 + Mark3 + Marks;
if (Total_Marks >= 80)
Grade = 'A';
else if (Total_Marks >= 60)
Grade = 'B';
else if (Total_Marks >= 40)
Grade = 'C';
else
Grade = 'F';
}

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;
};

class Internal_Marks : virtual public Student {


public:
int IntM1, IntM2, IntM3, IntM4, IntM5;
};

class External_Marks : virtual public Student {


public:
int ExtM1, ExtM2, ExtM3, ExtM4, ExtM5;
};

class Result : public Internal_Marks, public External_Marks {


public:
int T1, T2, T3, T4, T5;
};
int main() {
Result studentResult;

std::cout << "Enter Roll No: ";


std::cin >> studentResult.Roll_No;
std::cin.ignore();

std::cout << "Enter Name: ";


std::getline(std::cin, studentResult.Name);

std::cout << "Enter Class: ";


std::getline(std::cin, studentResult.Class);

studentResult.T1 = studentResult.IntM1 + studentResult.ExtM1;


studentResult.T2 = studentResult.IntM2 + studentResult.ExtM2;
studentResult.T3 = studentResult.IntM3 + studentResult.ExtM3;
studentResult.T4 = studentResult.IntM4 + studentResult.ExtM4;
studentResult.T5 = studentResult.IntM5 + studentResult.ExtM5;

std::cout << "Subject-wise Total Marks Obtained:" << std::endl;


std::cout << "Subject 1: " << studentResult.T1 << std::endl;
std::cout << "Subject 2: " << studentResult.T2 << std::endl;
std::cout << "Subject 3: " << studentResult.T3 << std::endl;
std::cout << "Subject 4: " << studentResult.T4 << std::endl;
std::cout << "Subject 5: " << studentResult.T5 << std::endl;

// Check if the student has passed in each subject


if (studentResult.T1 >= 40)
std::cout << "Student has passed in Subject 1." << std::endl;
else
std::cout << "Student has failed in Subject 1." << std::endl;

// Repeat the above check for each subject

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

// Function to calculate the area of a cone


double calculateArea(double radius, double height) {
return PI * radius * (radius + sqrt(height*height + radius*radius));
}

// Function to calculate the area of a sphere


double calculateArea(double radius) {

return 4 * PI * radius * radius;


}

// Function to calculate the area of a circle


double calculateArea(int radius) {
return PI * radius * radius;
}

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);
};

istream& operator>>(istream& input, Date& date) {


input >> date.dd >> date.mm >> date.yyyy;
return input;
}

ostream& operator<<(ostream& output, const Date& date) {


output << date.dd << "/" << date.mm << "/" << date.yyyy;
return output;
}

int main() {
Date d;

cout << "Enter date (dd mm yyyy): ";


cin >> d;
cout << "Date is: " << d;
return 0;
}

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) {}

float calculateArea() override {


return 3.14159 * radius * radius;
}
};

class Rectangle : public Shape {


private:
float length;
float width;

public:
Rectangle(float l, float w) : length(l), width(w) {}

float calculateArea() override {


return length * width;
}
};

class Triangle : public Shape {


private:
float base;
float height;

public:
Triangle(float b, float h) : base(b), height(h) {}

float calculateArea() override {


return 0.5 * base * height;
}
};

int main() {
Circle c(5);
Rectangle r(4, 6);
Triangle t(3, 8);

std::cout << "Area of Circle: " << c.calculateArea() << std::endl;


std::cout << "Area of Rectangle: " << r.calculateArea() << std::endl;
std::cout << "Area of Triangle: " << t.calculateArea() << std::endl;

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;
}

char operator[](int index) {


if (index >= 0 && index < strlen(str)) {
return str[index];
} else {
return '\0';
}
}

void print() {
std::cout << str << std::endl;
}
};

int main() {
MyString myStr("Hello, World!");

std::cout << "Original String: ";


myStr.print();

std::cout << "String after ! operator: ";


(!myStr).print();

std::cout << "Character at index 4: " << myStr[4] << std::endl;

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];

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


std::cout << "Enter details for Teacher " << i + 1 << std::endl;
teachers[i].acceptTeacherInfo();
}

std::cout << "\nTeacher Information:\n";


for (int i = 0; i < 5; ++i) {
std::cout << "Teacher " << i + 1 << ":\n";
teachers[i].displayTeacherInfo();
std::cout << std::endl;
}

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();

std::cout << "Enter Train Name: ";


std::getline(std::cin, Train_Name);

std::cout << "Enter Number of Seats: ";


std::cin >> No_of_Seats;
std::cin.ignore();

std::cout << "Enter Source Station: ";


std::getline(std::cin, Source_Station);

std::cout << "Enter Destination Station: ";


std::getline(std::cin, Destination_Station);
}

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;
}

void Train::DisplayTrainDetailsByStations(const std::string& startStation, const std::string&


endStation) {
if (startStation == Source_Station && endStation == Destination_Station) {
DisplayAllTrainDetails();
}
}

int main() {
int n;
std::cout << "Enter the number of trains: ";
std::cin >> n;

std::vector<Train> trains(n);

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


std::cout << "\nEnter details for Train " << i + 1 << ":" << std::endl;
trains[i].AcceptDetails();
}

std::cout << "\nAll Train Details:" << std::endl;


for (int i = 0; i < n; ++i) {
std::cout << "\nTrain " << i + 1 << " Details:" << std::endl;
trains[i].DisplayAllTrainDetails();
}

std::string start, end;


std::cout << "\nEnter the starting station: ";
std::cin >> start;
std::cout << "Enter the ending station: ";
std::cin >> end;

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;
}

void Manager::DisplayInAscendingOrder(Manager arr[], int n) {


// Sort managers based on salary in ascending order
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].Salary > arr[j + 1].Salary)
{
Manager temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
std::cout << "Manager Details in Ascending Order of Salary:\n";
std::cout << std::setw(10) << "ID" << std::setw(20) << "Name" << std::setw(15) << "Mobile No."
<< std::setw(10) << "Salary\n";
for (int i = 0; i < n; i++) {
std::cout << std::setw(10) << arr[i].Manager_Id << std::setw(20) << arr[i].Manager_Name <<
std::setw(15) << arr[i].Mobile_No << std::setw(10) << arr[i].Salary << "\n";
}
}

void Manager::DisplayManagerDetails(int id, Manager arr[], int n) {


// Find and display details of a particular manager by ID
for (int i = 0; i < n; i++) {
if (arr[i].Manager_Id == id) {
std::cout << "Manager Details for ID " << id << ":\n";
std::cout << std::setw(10) << "ID" << std::setw(20) << "Name" << std::setw(15) << "Mobile
No." << std::setw(10) << "Salary\n";
std::cout << std::setw(10) << arr[i].Manager_Id << std::setw(20) << arr[i].Manager_Name <<
std::setw(15) << arr[i].Mobile_No << std::setw(10) << arr[i].Salary << "\n";
return;
}
}
std::cout << "Manager with ID " << id << " not found.\n";
}

int main() {
int n;
std::cout << "Enter the number of managers: ";
std::cin >> n;

Manager managers[n];

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


std::cout << "\nEnter details for Manager " << i + 1 << ":\n";
managers[i].AcceptDetails();
}

// Display manager details in ascending order of salary


managers[0].DisplayInAscendingOrder(managers, n);

// Display details of a particular manager


int managerId;
std::cout << "\nEnter the Manager ID to display details: ";
std::cin >> managerId;
managers[0].DisplayManagerDetails(managerId, 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>

using namespace std;

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);

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


cout << "Enter Subject Name " << i + 1 << ": ";
getline(cin, Subject_Name[i]);
cout << "Enter Internal Marks for " << Subject_Name[i] << ": ";
cin >> Int_Marks[i];
cout << "Enter External Marks for " << Subject_Name[i] << ": ";
cin >> Ext_Marks[i];
}
}
void Marksheet::calculateMarksheet() {
Grand_Total = 0;
for (int i = 0; i < 4; ++i) {
Total[i] = Int_Marks[i] + Ext_Marks[i];
Grand_Total += Total[i];
}
Percentage = static_cast<float>(Grand_Total) / 4;
if (Percentage >= 90)
Grade = 'A';
else if (Percentage >= 80)
Grade = 'B';
else if (Percentage >= 70)
Grade = 'C';
else if (Percentage >= 60)
Grade = 'D';
else
Grade = 'F';
}

void Marksheet::displayMarksheet() {
cout << "\n----- Marksheet -----\n";
cout << "Seat Number: " << Seat_No << endl;
cout << "Student Name: " << Student_Name << endl;
cout << "Class: " << Class << endl;

cout << "\nSubject-wise Marks:\n";


for (int i = 0; i < 4; ++i) {
cout << Subject_Name[i] << " - Total Marks: " << Total[i] << 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>

int main(int argc, char* argv[]) {


if (argc < 2) {
std::cout << "Usage: " << argv[0] << " <number1> <number2> ... <numberN>\n";
return 1;
}

std::ofstream positiveFile("positive.txt");
std::ofstream negativeFile("negative.txt");

for (int i = 1; i < argc; ++i) {


int num = std::stoi(argv[i]);
if (num >= 0) {
positiveFile << num << "\n";
} else {
negativeFile << num << "\n";
}
}

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();
}

void Employee::UpdateRecord(int empNo) {


std::fstream file("Emp.dat");
std::fstream temp("temp.dat", std::ios::out);
while (file >> Emp_No >> Emp_Name >> Emp_Marks) {
if (Emp_No == empNo) {
std::cout << "Enter New Employee Name: ";
std::cin >> Emp_Name;
std::cout << "Enter New Employee Marks: ";
std::cin >> Emp_Marks;
}
temp << Emp_No << " " << Emp_Name << " " << Emp_Marks << std::endl;
}
file.close();
temp.close();
remove("Emp.dat");
rename("temp.dat", "Emp.dat");

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;

std::ofstream file("Newspaper.txt", std::ios::app);


file << Name << " " << Publisher << " " << Cost << std::endl;
file.close();
}

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::cout << "Enter the number


of Newspapers: ";

std::cin >> n;

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


Newspaper newspaper;
newspaper.AcceptDetails();
}

std::cout << "\nNewspaper Details:\n";


Newspaper().DisplayDetails();

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];

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


std::cout << "Enter city name: ";
std::cin >> cities[i].name;
std::cout << "Enter STD code for " << cities[i].name << ": ";
std::cin >> cities[i].stdCode;
}
std::ofstream file("cities.txt");
if (file.is_open()) {
for (int i = 0; i < n; ++i) {
file << cities[i].name << " " << cities[i].stdCode << std::endl;
}
file.close();
}

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>

template <typename T, size_t N>


void reverseArray(T (&arr)[N]) {
for (size_t i = 0; i < N / 2; ++i) {
T temp = arr[i];
arr[i] = arr[N - i - 1];
arr[N - i - 1] = temp;
}
}

int main() {
int intArray[] = {1, 2, 3, 4, 5};
char charArray[] = {'a', 'b', 'c', 'd', 'e'};

reverseArray(intArray);
reverseArray(charArray);

for (const auto &elem : intArray) {


std::cout << elem << " ";
}
std::cout << std::endl;

for (const auto &elem : charArray) {


std::cout << elem << " ";
}
std::cout << std::endl;

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>

template <typename T>


T findMax(T a, T b) {
return (a > b) ? a : b;
}

template <typename T>


T findMin(T a, T b) {
return (a < b) ? a : b;
}

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>

template <class T>


class SquareCalculator {
public:
T calculateSquare(T num) {
return num * num;
}
};

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;
}

template <typename T>


T calculateRectangleArea(T length, T width) {
return length * width;
}

int main() {
int intRadius = 5;
float floatRadius = 3.5;
double doubleRadius = 7.2;

int intLength = 4;
int intWidth = 6;

float floatLength = 3.5;


float floatWidth = 2.5;

double doubleLength = 7.2;


double doubleWidth = 5.4;

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");
}

bool empty() const {


return elements.empty();
}
size_t size() const {
return elements.size();
}
};

int main() {
Stack<int> stack;
stack.push(1);
stack.push(2);
stack.push(3);

std::cout << "Stack size: " << stack.size() << std::endl;


while (!stack.empty()) {
std::cout << "Top element: " << stack.top() <<
std::endl;
stack.pop(); }
return 0;
}

You might also like