Cpp
Cpp
Q1:
1. Write a C++ program to check maximum and minimum of two integer numbers.
(Use Inline function and Conditional operator) [15 Marks]
1. #include <iostream>
2. class maxmin
3. {
4. public:
5. inline int maximum(int a, int b)
6. {
7. return a > b ? a : b;
8. }
2 .Create a C++ class MyFile with data members file pointer and filename. Write necessary
member functions to accept and display File. Overload the following operators: operator
example purpose + f3=f1+f2 concatenation of file f1 and file f2 ! !f3 changes case of
alternate character of file f3. [25 Marks]
1. #include <iostream>
2. #include <fstream>
3. #include <string>
4. #include <cctype>
5. class MyFile {
6. std::string filename; // Data member to store the filename
7. public:
8. // Constructor to initialize filename
9. MyFile(const std::string& fname) : filename(fname) {}
24. if (inFile1) {
25. outFile << inFile1.rdbuf(); // Write contents of the first file
26. } else {
27. std::cerr << "Error opening file: " << filename << std::endl;
28. }
29. if (inFile2) {
30. outFile << inFile2.rdbuf(); // Write contents of the second file
31. } else {
32. std::cerr << "Error opening file: " << other.filename << std::endl;
33. }
42. if (!inFile) {
43. std::cerr << "Error opening file: " << filename << std::endl;
44. return;
45. }
71. return 0;
72. }
Slip 2 :
Q 1:
1.Write a C++ program to find volume of cylinder, cone and sphere.
(Use function overloading).[15 Marks]
1. 2. #include <iostream>
3. using namespace std;
4. // Function declarations
5. float volume(int, int); // cylinder
6. float volume(float, float); // cone
7. float volume(float); // sphere
8. int main() {
9. float cylinder_h, cylinder_r, cone_h, cone_r;
10. float sphere_r;
12. // Cylinder
13. cout << "1. Cylinder" << endl;
14. cout << "Height: ";
15. cin >> cylinder_h;
16. cout << "Radius: ";
17. cin >> cylinder_r;
18. cout << endl;
19. // Cone
20. cout << "2. Cone" << endl;
21. cout << "Height: ";
22. cin >> cone_h;
23. cout << "Radius: ";
24. cin >> cone_r;
25. cout << endl;
26. // Sphere
27. cout << "3. Sphere" << endl;
28. cout << "Radius: ";
29. cin >> sphere_r;
30. cout << endl;
31. // Display volumes
32. cout << "\nThe Volume of Cylinder is: " << volume(cylinder_r, cylinder_h) << endl;
33. cout << "The Volume of Cone is: " << volume(cone_r, cone_h) << endl;
34. cout << "The Volume of Sphere is: " << volume(sphere_r) << endl;
2.Write a C++ program to create a class Movie with data members M Name, Release Year,
Director Name and Budget. (Use File Handling) Write necessary member functions to: i.
Accept details for ‘n’ Movies from user and store it in a file “Movie.txt . ii.Display Movie
details from a file. iii. Count the number of objects stored in a file. [25 Marks]
1. #include <iostream>
2. #include <fstream>
3. #include <string>
4.
5. using namespace std;
6.
7. class Movie {
8. public:
9. int year;
10. string mname;
11. string dname;
12. int budget;
13.
14. void accept() {
15. cout << "\nEnter Movie Name: ";
16. cin.ignore(); // To ignore any newline character left in the input buffer
17. getline(cin, mname);
18. cout << "Enter Release Year: ";
19. cin >> year;
20. cout << "Enter Director Name: ";
21. cin.ignore(); // To ignore any newline character left in the input buffer
22. getline(cin, dname);
23. cout << "Enter Budget: ";
24. cin >> budget;
25. }
26.
27. void display() const {
28. cout << "\nThe Movie Name: " << mname << endl;
29. cout << "The Release Year: " << year << endl;
30. cout << "The Director Name: " << dname << endl;
31. cout << "The Budget: " << budget << endl;
32. }
33. };
34.
35. void writeMoviesToFile(const string& filename, int n) {
36. ofstream file(filename.c_str(), ios::binary); // Use c_str() to convert to const char*
37. if (!file) {
38. cerr << "Error opening file for writing!" << endl;
39. return;
40. }
41.
42. Movie m;
43. for (int i = 0; i < n; i++) {
44. m.accept();
45. file.write(reinterpret_cast<char*>(&m), sizeof(m));
46. }
47. file.close();
48. }
49.
50. void readMoviesFromFile(const string& filename) {
51. ifstream file(filename.c_str(), ios::binary); // Use c_str() to convert to const char*
52. if (!file) {
53. cerr << "Error opening file for reading!" << endl;
54. return;
55. }
56.
57. Movie m;
58. while (file.read(reinterpret_cast<char*>(&m), sizeof(m))) {
59. m.display();
60. }
61. file.close();
62. }
63.
64. int countMoviesInFile(const string& filename) {
65. ifstream file(filename.c_str(), ios::binary); // Use c_str() to convert to const char*
66. if (!file) {
67. cerr << "Error opening file for counting!" << endl;
68. return 0;
69. }
70.
71. Movie m;
72. int count = 0;
73. while (file.read(reinterpret_cast<char*>(&m), sizeof(m))) {
74. count++;
75. }
76. file.close();
77. return count;
78. }
79.
80. int main() {
81. const string filename = "movie.txt";
82. int n;
83.
84. cout << "Enter the number of records you want to accept: ";
85. cin >> n;
86.
87. writeMoviesToFile(filename, n);
88. cout << "\nDetails of movies from file:\n";
89. readMoviesFromFile(filename);
90.
91. int movieCount = countMoviesInFile(filename);
92. cout << "\nTotal number of movies stored in the file: " << movieCount << endl;
93.
94. return 0;
95. }
Slip 3:
Q 1:
1 .Write a C++ program to interchange values of two integer numbers.
(Use call by reference)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. // Function to swap two integers
5. void swap(int &a, int &b) {
6. int c;
7. c = a;
8. a = b;
9. b = c;
10. cout << "\nInside function after swapping value is : ";
11. cout << "\n\tA = " << a << "\n\tB = " << b << endl;
12. }
13.
14. int main() {
15. int a, b;
16.
17. cout << "Enter value of a: ";
18. cin >> a;
19. cout << "Enter value of b: ";
20. cin >> b;
21.
22. cout << "\nBefore Swapping value is : ";
23. cout << "\n\tA = " << a << "\n\tB = " << b << endl;
24.
25. swap(a, b); // Call the swap function
26.
27. cout << "\nOutside Function after swapping value is : ";
28. cout << "\n\tA = " << a << "\n\tB = " << b << endl;
29.
30. // Pause the console (optional)
31. system("pause");
32. return 0;
33. }
2.Write a C++ program to accept ‘n’ numbers from user through Command Line Argument.
Store all Even and Odd numbers in file “Even.txt” and “Odd.txt” respectively. [25 Marks]
1. #include <iostream>
2. #include <fstream>
3. #include <cstdlib> // For atoi
4. using namespace std;
5.
6. int main(int argc, char* argv[]) {
7. // Check if at least one number is provided
8. if (argc < 2) {
9. cout << "Please provide numbers as command line arguments." << endl;
10. return 1;
11. }
12.
13. ofstream fp1("even.txt");
14. ofstream fp2("odd.txt");
15.
16. // Process each command line argument
17. for (int i = 1; i < argc; i++) {
18. int number = atoi(argv[i]); // Convert argument to integer
19. if (number % 2 == 0) {
20. fp1 << number << endl; // Write to even.txt
21. } else {
22. fp2 << number << endl; // Write to odd.txt
23. }
24. }
25.
26. fp1.close();
27. fp2.close();
28.
29. // Display contents of even.txt
30. ifstream evenFile("even.txt");
31. char ch;
32. cout << "The even file contents are:\n";
33. while (evenFile.get(ch)) {
34. cout << "\t" << ch;
35. }
36. evenFile.close();
37.
38. // Display contents of odd.txt
39. ifstream oddFile("odd.txt");
40. cout << "\n\nThe odd file contents are:\n";
41. while (oddFile.get(ch)) {
42. cout << "\t" << ch;
43. }
44. oddFile.close();
45.
46. return 0;
47. }
Slip 4:
1.Write a C++ program accept Worker information Worker Name, No of Hours worked, Pay
Rate and Salary. Write necessary functions to calculate and display the salary of Worker.
(Use default value for Pay_Rate)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Worker {
5. char wname[20];
6. int hrs;
7. float sal;
8.
9. public:
10. void get(float prate = 40.50); // Default value for pay rate
11. void put();
12. };
13.
14. void Worker::get(float prate) {
15. cout << "Enter Worker Name: ";
16. cin >> wname;
17. cout << "Enter No. of Hours worked: ";
18. cin >> hrs;
19. sal = hrs * prate; // Calculate salary
20. }
21.
22. void Worker::put() {
23. cout << "\nWorker Name: " << wname;
24. cout << "\nNo Of Hours Worked: " << hrs;
25. cout << "\nTotal Salary = " << sal << endl;
26. }
27.
28. int main() {
29. Worker w;
30. w.get(); // Call get function to input worker details
31. w.put(); // Call put function to display worker details
32. return 0;
33. }
2 .Write a C++ program to create a base class Employee (Emp-code, name, salary). Derive
two classes as Fulltime (daily wages, number of days) and Parttime (number of working
hours, hourly wages). Write a menu driven program to perform following functions:
1. Accept the details of ‘n’ employees and calculate the salary.
2.Display the details of ‘n’ employees
3.Display the details of employee having maximum salary for both types of employees. [25
Marks]
1. #include <iostream>
2. #include <vector>
3. using namespace std;
4.
5. class Employee {
6. protected:
7. int empCode;
8. string empName;
9. float salary;
10.
11. public:
12. void getDetails() {
13. cout << "Enter Employee Code: ";
14. cin >> empCode;
15. cout << "Enter Employee Name: ";
16. cin >> empName;
17. }
18.
19. virtual void calculateSalary() = 0; // Pure virtual function
20. virtual void display() const = 0; // Pure virtual function
21.
22. int getEmpCode() const {
23. return empCode;
24. }
25.
26. float getSalary() const {
27. return salary;
28. }
29. };
30.
31. class FullTime : public Employee {
32. private:
33. float dailyWages;
34. int noOfDays;
35.
36. public:
37. void getDetails() {
38. Employee::getDetails();
39. cout << "Enter Daily Wages: ";
40. cin >> dailyWages;
41. cout << "Enter Number of Days Worked: ";
42. cin >> noOfDays;
43. }
44.
45. void calculateSalary() override {
46. salary = dailyWages * noOfDays;
47. }
48.
49. void display() const override {
50. cout << "\nEmployee Code: " << empCode
51. << "\nEmployee Name: " << empName
52. << "\nSalary: " << salary
53. << "\nStatus: Full Time" << endl;
54. }
55. };
56.
57. class PartTime : public Employee {
58. private:
59. float hourlyWages;
60. int workingHours;
61.
62. public:
63. void getDetails() {
64. Employee::getDetails();
65. cout << "Enter Hourly Wages: ";
66. cin >> hourlyWages;
67. cout << "Enter Working Hours: ";
68. cin >> workingHours;
69. }
70.
71. void calculateSalary() override {
72. salary = hourlyWages * workingHours;
73. }
74.
75. void display() const override {
76. cout << "\nEmployee Code: " << empCode
77. << "\nEmployee Name: " << empName
78. << "\nSalary: " << salary
79. << "\nStatus: Part Time" << endl;
80. }
81. };
82.
83. int main() {
84. vector<Employee*> employees;
85. int choice;
86.
87. do {
88. cout << "\n1. Enter Employee Record"
89. << "\n2. Display Employee Records"
90. << "\n3. Display Employee with Maximum Salary"
91. << "\n4. Quit"
92. << "\nEnter Your Choice: ";
93. cin >> choice;
94.
95. switch (choice) {
96. case 1: {
97. int type;
98. cout << "1. Full Time Employee\n2. Part Time Employee\nEnter Choice: ";
99. cin >> type;
100.
101. Employee* emp = NULL; // Use NULL instead of nullptr
102. if (type == 1) {
103. emp = new FullTime();
104. } else if (type == 2) {
105. emp = new PartTime();
106. }
107.
108. if (emp) {
109. emp->getDetails();
110. emp->calculateSalary();
111. employees.push_back(emp);
112. }
113. break;
114. }
115. case 2:
116. for (size_t i = 0; i < employees.size(); ++i) { // Traditional for loop
117. employees[i]->display();
118. }
119. break;
120. case 3: {
121. Employee* maxSalaryEmp = NULL; // Use NULL instead of nullptr
122. for (size_t i = 0; i < employees.size(); ++i) { // Traditional for loop
123. if (!maxSalaryEmp || employees[i]->getSalary() > maxSalaryEmp-
>getSalary()) {
124. maxSalaryEmp = employees[i];
125. }
126. }
127. if (maxSalaryEmp) {
128. cout << "\nEmployee with Maximum Salary:";
129. maxSalaryEmp->display();
130. } else {
131. cout << "\nNo employees found." << endl;
132. }
133. break;
134. }
135. case 4:
136. cout << "Exiting..." << endl;
137. break;
138. default:
139. cout << "Invalid choice. Please try again." << endl;
140. }
141. } while (choice != 4);
142.
143. // Clean up dynamically allocated memory
144. for (size_t i = 0; i < employees.size(); ++i) {
145. delete employees[i];
146. }
147.
148. return 0;
149. }
Slip 5:
1.Consider the following C++ class
class Point
{
int x,y;
public:
void setpoint(int,int); //set values of x and y co-ordinates
void showpoint(); // display co-ordinate in point p in format(x,y)
}[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Point {
5. int x, y;
6.
7. public:
8. void setpoint(int a, int b) {
9. x = a;
10. y = b;
11. }
12.
13. void showpoint() {
14. cout << "(" << x << ", " << y << ")" << endl;
15. }
16. };
17.
18. int main() {
19. int a, b;
20. Point p;
21.
22. cout << "\nEnter Co-Ordinates: ";
23. cout << "\nEnter X: ";
24. cin >> a;
25. cout << "Enter Y: ";
26. cin >> b;
27.
28. p.setpoint(a, b);
29. p.showpoint();
30.
31. return 0;
32. }
2.Create a C++ base class Shape. Derive three different classes Circle,Sphere and Cylinder
from shape class. Write a C++ program to calculate area of Circle, Sphere and Cylinder.
(Use pure virtual function). [25 Marks]
1. #include <iostream>
2. #include <cmath> // For M_PI
3. using namespace std;
4.
5. class Shape {
6. public:
7. virtual void area() = 0; // Pure virtual function
8. };
9.
10. class Circle : public Shape {
11. private:
12. float r;
13.
14. public:
15. void area() override {
16. cout << "Enter Radius of Circle: ";
17. cin >> r;
18. cout << "Area of Circle is: " << (M_PI * r * r) << endl;
19. }
20. };
21.
22. class Sphere : public Shape {
23. private:
24. float r;
25.
26. public:
27. void area() override {
28. cout << "Enter Radius of Sphere: ";
29. cin >> r;
30. cout << "Surface Area of Sphere is: " << (4 * M_PI * r * r) << endl;
31. }
32. };
33.
34. class Cylinder : public Shape {
35. private:
36. float r, h;
37.
38. public:
39. void area() override {
40. cout << "Enter Radius of Cylinder: ";
41. cin >> r;
42. cout << "Enter Height of Cylinder: ";
43. cin >> h;
44. cout << "Surface Area of Cylinder is: " << (2 * M_PI * r * h + 2 * M_PI * r * r) <<
endl;
45. }
46. };
47.
48. int main() {
49. Circle c;
50. c.area();
51.
52. Sphere s;
53. s.area();
54.
55. Cylinder cyli;
56. cyli.area();
57.
58. return 0;
59. }
Slip 6:
1.Write a C++ program create two Classes Square and Rectangle. Compare area of both the
shapes using friend function. Accept appropriate data members for both the classes.[15
Marks]
1. #include <iostream>
2. using namespace std;
3.
4. // Forward declaration of Rectangle class
5. class Rectangle;
6.
7. class Square {
8. public:
9. int side;
10.
11. void getData() {
12. cout << "Enter side of square: ";
13. cin >> side;
14. }
15.
16. int calculateArea() {
17. return (side * side);
18. }
19.
20. friend void compare(Square s, Rectangle r); // Declare friend function
21. };
22.
23. class Rectangle {
24. public:
25. int length, width;
26.
27. void getData() {
28. cout << "Enter Length of Rectangle: ";
29. cin >> length;
30. cout << "Enter Breadth of Rectangle: ";
31. cin >> width;
32. }
33.
34. int calculateArea() {
35. return (length * width);
36. }
37.
38. friend void compare(Square s, Rectangle r); // Declare friend function
39. };
40.
41. void compare(Square s, Rectangle r) {
42. int squareArea = s.calculateArea();
43. int rectangleArea = r.calculateArea();
44.
45. if (squareArea > rectangleArea) {
46. cout << "\nThe area of the square is greater than the area of the rectangle." <<
endl;
47. } else if (squareArea < rectangleArea) {
48. cout << "\nThe area of the rectangle is greater than the area of the square." <<
endl;
49. } else {
50. cout << "\nThe area of the square and rectangle are equal." << endl;
51. }
52. }
53.
54. int main() {
55. Square s;
56. Rectangle r;
57.
58. s.getData();
59. r.getData();
60.
61. cout << "\nArea of Square: " << s.calculateArea() << endl;
62. cout << "Area of Rectangle: " << r.calculateArea() << endl;
63.
64. compare(s, r); // Compare areas
65.
66. return 0;
67. }
1. #include <iostream>
2. using namespace std;
3.
4. class Matrix {
5. int **p; // Pointer to a pointer for dynamic 2D array
6. int r, c; // Rows and columns
7.
8. public:
9. // Constructor
10. Matrix(int x, int y) {
11. r = x;
12. c = y;
13. p = new int*[r]; // Allocate memory for rows
14. for (int i = 0; i < r; i++) {
15. p[i] = new int[c]; // Allocate memory for columns
16. }
17. }
18.
19. // Destructor
20. ~Matrix() {
21. for (int i = 0; i < r; i++) {
22. delete[] p[i]; // Free each row
23. }
24. delete[] p; // Free the row pointers
25. cout << "Destructor invoked" << endl;
26. }
27.
28. // Function to accept matrix elements
29. void accept() {
30. cout << "Enter elements of matrix: " << endl;
31. for (int i = 0; i < r; i++) {
32. for (int j = 0; j < c; j++) {
33. cin >> p[i][j];
34. }
35. }
36. }
37.
38. // Function to display matrix elements
39. void display() {
40. cout << "Elements of matrix are: " << endl;
41. for (int i = 0; i < r; i++) {
42. for (int j = 0; j < c; j++) {
43. cout << p[i][j] << "\t";
44. }
45. cout << endl;
46. }
47. }
48.
49. // Function to calculate transpose of a matrix
50. void transpose() {
51. cout << "\nTranspose of matrix is: " << endl;
52. for (int i = 0; i < c; i++) {
53. for (int j = 0; j < r; j++) {
54. cout << p[j][i] << "\t";
55. }
56. cout << endl;
57. }
58. }
59. };
60.
61. int main() {
62. int m, n;
63. cout << "Enter order of matrix (rows and columns): ";
64. cin >> m >> n;
65.
66. Matrix obj1(m, n); // Create matrix object
67. obj1.accept(); // Accept matrix elements
68. obj1.display(); // Display matrix elements
69. obj1.transpose(); // Display transpose of the matrix
70.
71. return 0;
72. }
Slip 7:
1.Write a C++ program using class with data member char str[50] and function replace (char
chl, char ch2) every occurrence of chl in str should be replaced with ch2 and return number
of replacement it makes use default value for char ch2. (Use ch2 as Default Argument)[15
Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class MyStr {
5. private:
6. char str[50]; // Data member to hold the string
7.
8. public:
9. // Function to replace characters
10. int replace(char c1, char c2 = 'r') {
11. int n = 0; // Count of replacements
12. for (int i = 0; str[i] != '\0'; i++) {
13. if (str[i] == c1) {
14. str[i] = c2; // Replace character
15. n++; // Increment replacement count
16. }
17. }
18. return n; // Return number of replacements
19. }
20.
21. // Function to accept string input
22. void input() {
23. cout << "Enter String: ";
24. cin.getline(str, 50); // Read string with spaces
25. }
26.
27. // Function to display the string
28. void display() {
29. cout << "After Replacement string is: " << str << endl;
30. }
31. };
32.
33. int main() {
34. MyStr m;
35. char c1, c2;
36.
37. m.input(); // Accept string input
38.
39. cout << "Enter character which is to replace: ";
40. cin >> c1; // Character to replace
41.
42. cout << "Enter character to replace with (default is 'r'): ";
43. cin >> c2; // Character to replace with
44.
45. // Call replace function and display results
46. int replacements = m.replace(c1, c2);
47. cout << "\nNumber of Replacements: " << replacements << endl;
48.
49. m.display(); // Display the modified string
50.
51. return 0;
52. }
2.Create a C++ class Vector with data members size & pointer to integer. The size of the
vector varies so the memory should be allocated dynamically.Perform following operations:.
1. accept vector
2.display vector in format(10,20,30,…….,)
3.calculate union of two matrix.
(use parameterized constructor & copy constructor)[25 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Vector {
5. int *data; // Pointer to dynamically allocated array
6. int size; // Size of the vector
7.
8. public:
9. // Parameterized constructor
10. Vector(int s) : size(s) {
11. data = new int[size]; // Allocate memory for the vector
12. }
13.
14. // Copy constructor
15. Vector(const Vector &v) {
16. size = v.size;
17. data = new int[size];
18. for (int i = 0; i < size; i++) {
19. data[i] = v.data[i]; // Copy elements
20. }
21. }
22.
23. // Function to accept vector elements
24. void accept() {
25. cout << "Enter " << size << " elements: ";
26. for (int i = 0; i < size; i++) {
27. cin >> data[i];
28. }
29. }
30.
31. // Function to display vector elements
32. void display() const {
33. cout << "(";
34. for (int i = 0; i < size; i++) {
35. cout << data[i];
36. if (i < size - 1) {
37. cout << ", ";
38. }
39. }
40. cout << ")";
41. }
42.
43. // Function to calculate the union of two vectors
44. void calculateUnion(const Vector &v2) const {
45. int *unionArray = new int[size + v2.size];
46. int unionSize = 0;
47.
48. // Add elements from the first vector
49. for (int i = 0; i < size; i++) {
50. unionArray[unionSize++] = data[i];
51. }
52.
53. // Add elements from the second vector if not already present
54. for (int i = 0; i < v2.size; i++) {
55. bool found = false;
56. for (int j = 0; j < size; j++) {
57. if (v2.data[i] == data[j]) {
58. found = true;
59. break;
60. }
61. }
62. if (!found) {
63. unionArray[unionSize++] = v2.data[i];
64. }
65. }
66.
67. // Display the union of the vectors
68. cout << "\nThe union of the vectors is: (";
69. for (int i = 0; i < unionSize; i++) {
70. cout << unionArray[i];
71. if (i < unionSize - 1) {
72. cout << ", ";
73. }
74. }
75. cout << ")" << endl;
76.
77. delete[] unionArray; // Free allocated memory
78. }
79.
80. // Destructor
81. ~Vector() {
82. delete[] data; // Free allocated memory
83. }
84. };
85.
86. int main() {
87. int size1, size2;
88.
89. cout << "Enter size of first vector: ";
90. cin >> size1;
91. Vector v1(size1); // Create first vector
92. v1.accept(); // Accept elements for first vector
93.
94. cout << "Enter size of second vector: ";
95. cin >> size2;
96. Vector v2(size2); // Create second vector
97. v2.accept(); // Accept elements for second vector
98.
99. // Display vectors
100. cout << "First vector: ";
101. v1.display();
102. cout << "\nSecond vector: ";
103. v2.display();
104.
105. // Calculate and display union
106. v1.calculateUnion(v2);
107.
108. return 0;
109. }
Slip 8:
1.Write a C++ program create a class Number, which contain static data member ‘cnt’ and
member function ‘Display()’. Display() should print number of times display operation is
performed irrespective of the object responsible for calling Display().[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Number {
5. private:
6. static int cnt; // Static data member to count display calls
7.
8. public:
9. void display() {
10. cout << "\nDisplay Function is called " << cnt << " times." << endl;
11. cnt++; // Increment the count
12. }
13. };
14.
15. // Initialize the static member
16. int Number::cnt = 1;
17.
18. int main() {
19. Number n1, n2;
20.
21. n1.display(); // Call display on first object
22. n1.display(); // Call display on first object again
23. n2.display(); // Call display on second object
24. n2.display(); // Call display on second object again
25.
26. return 0;
27. }
2.Create a C++ class Person with data members Person name, Mobile number, Age, City.
Write necessary member functions for the following:
i. Search the mobile number of given person.
ii. Search the person name of given mobile number.
iii. Search all person details of given city.
(Use function overloading)[25 Marks]
1. #include <iostream>
2. #include <string>
3. #include <vector>
4. #include <limits> // Include this header for numeric_limits
5. using namespace std;
6.
7. class Person {
8. private:
9. string name;
10. string city;
11. int mobile;
12.
13. public:
14. // Constructor
15. Person(string n, string c, int m) : name(n), city(c), mobile(m) {}
16.
17. // Function to display person details
18. void display() const {
19. cout << "\nPerson Name: " << name;
20. cout << "\nPerson Mobile Number: " << mobile;
21. cout << "\nPerson City: " << city << endl;
22. }
23.
24. // Function to search mobile number by name
25. bool searchByName(const string &nme) const {
26. return (nme == name);
27. }
28.
29. // Function to search name by mobile number
30. bool searchByMobile(int mno) const {
31. return (mno == mobile);
32. }
33.
34. // Function to get the city
35. string getCity() const {
36. return city;
37. }
38.
39. // Function to get the mobile number
40. int getMobile() const {
41. return mobile;
42. }
43.
44. // Function to get the name
45. string getName() const {
46. return name;
47. }
48. };
49.
50. int main() {
51. vector<Person> people; // Vector to store person objects
52. int choice, mobile;
53. string name, city;
54.
55. do {
56. cout << "\n1. Accept Person Details";
57. cout << "\n2. Display Person Details";
58. cout << "\n3. Search mobile number of a given person";
59. cout << "\n4. Search Person details of a given mobile number";
60. cout << "\n5. Exit";
61. cout << "\nEnter your choice: ";
62. cin >> choice;
63.
64. // Clear the input buffer before using getline
65. cin.ignore(numeric_limits<streamsize>::max(), '\n');
66.
67. switch (choice) {
68. case 1: {
69. cout << "\nEnter Person Name: ";
70. getline(cin, name);
71. cout << "Enter Person City: ";
72. getline(cin, city);
73.
74. // Input validation for mobile number
75. while (true) {
76. cout << "Enter Person Mobile Number: ";
77. cin >> mobile;
78.
79. // Check if the input is valid
80. if (cin.fail()) {
81. cin.clear(); // Clear the error flag
82. cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard invalid
input
83. cout << "Invalid input. Please enter a valid mobile number." << endl;
84. } else {
85. cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Clear the input
buffer
86. break; // Exit the loop if input is valid
87. }
88. }
89.
90. people.push_back(Person(name, city, mobile)); // Add new person to the
vector
91. break;
92. }
93. case 2:
94. for (size_t i = 0; i < people.size(); i++) {
95. people[i].display(); // Display each person's details
96. }
97. break;
98.
99. case 3:
100. cout << "Enter person name to search for mobile number: ";
101. getline(cin, name);
102. for (size_t i = 0; i < people.size(); i++) {
103. if (people[i].searchByName(name)) {
104. cout << "Mobile Number: " << people[i].getMobile() << endl;
105. break;
106. }
107. }
108. break;
109.
110. case 4:
111. cout << "Enter mobile number to search for person name: ";
112. cin >> mobile;
113. for (size_t i = 0; i < people.size(); i++) {
114. if (people[i].searchByMobile(mobile)) {
115. cout << "Person Name: " << people[i].getName() << endl;
116. break;
117. }
118. }
119. break;
120.
121. case 5:
122. cout << "Exiting..." << endl;
123. break;
124.
125. default:
126. cout << "Invalid choice! Please try again." << endl;
127. }
128. } while (choice != 5);
129.
130. return 0;
131. }
Slip 9:
1.Consider the following C++ class class Person { char Name [20]; charAddr [30]; float Salary;
float tax amount; public: // member functions };
Calculate tax amount by checking salary of a person
For salary <=20000 tax rate=0
For salary>20000|| <=40000 tax rate =5% of salary.
For salary>40000 tax rate=10% of salary[15 Marks]
1. #include <iostream>
2. #include <string>
3. using namespace std;
4.
5. class Person {
6. char name[20];
7. char addr[30];
8. float sal, tax;
9.
10. public:
11. void get() {
12. cout << "Enter Name: ";
13. cin >> name;
14. cout << "Enter Address: ";
15. cin >> addr;
16. cout << "Enter Salary: ";
17. cin >> sal;
18. }
19.
20. void put() {
21. cout << "\n\n-----Person Information-----";
22. cout << "\nPerson Name: " << name;
23. cout << "\nPerson Address: " << addr;
24. cout << "\nPerson Salary: " << sal;
25. cout << "\nTax is: " << tax << endl;
26. }
27.
28. void cal_tax() {
29. if (sal <= 20000) {
30. tax = 0;
31. } else if (sal > 20000 && sal <= 40000) {
32. tax = (sal * 5) / 100;
33. } else if (sal > 40000) {
34. tax = (sal * 10) / 100;
35. }
36. }
37. };
38.
39. int main() {
40. Person p;
41. p.get();
42. p.cal_tax();
43. p.put();
44. return 0;
45. }
2.Create a C++ class Time with data members Hours, Minutes and Seconds.
Write necessary member functions for the following: (Use Objects as arguments)
1. To accept a time.
2. To display a time In format hh:mm:ss.
3. To find difference between two time and display it in format hh:mm:ss.[25 Marks]
1. #include <iostream>
2. #include <iomanip> // For std::setw and std::setfill
3. using namespace std;
4.
5. class Time {
6. int h, m, s;
7.
8. public:
9. void get(); // Function to accept time
10. void display(); // Function to display time
11. Time operator -(const Time &t2); // Operator overloading for time difference
12. };
13.
14. void Time::get() {
15. cout << "\nEnter Hour, Minutes and Seconds: ";
16. cin >> h >> m >> s;
17.
18. // Input validation
19. if (h < 0 || m < 0 || s < 0 || m >= 60 || s >= 60) {
20. cout << "Invalid time input. Please enter again." << endl;
21. get(); // Call get() again for valid input
22. }
23. }
24.
25. void Time::display() {
26. cout << "\n----Time is---- " << setfill('0') << setw(2) << h
27. << ":" << setfill('0') << setw(2) << m
28. << ":" << setfill('0') << setw(2) << s << endl;
29. }
30.
31. Time Time::operator -(const Time &t2) {
32. Time t;
33. t.s = s - t2.s;
34. t.m = m - t2.m;
35. t.h = h - t2.h;
36.
37. // Adjust for negative seconds
38. if (t.s < 0) {
39. t.s += 60;
40. t.m--; // Borrow 1 minute
41. }
42.
43. // Adjust for negative minutes
44. if (t.m < 0) {
45. t.m += 60;
46. t.h--; // Borrow 1 hour
47. }
48.
49. return t;
50. }
51.
52. int main() {
53. Time t1, t2, t3;
54. t1.get();
55. t1.display();
56. t2.get();
57. t2.display();
58. t3 = t1 - t2;
59. cout << "\nTime1 - Time2:\n";
60. t3.display();
61. return 0;
62. }
Slip 10:
1.Write a C++ program to create a class Account with data members Acc number, Acc type
and Balance.
Write member functions to accept and display ‘n’ account details. (Use dynamic memory
allocation)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Account {
5. public:
6. int acc_no;
7. float balance; // Changed to float for balance
8. char acc_type[30];
9.
10. Account() {
11. // Constructor
12. }
13.
14. ~Account() {
15. // Destructor
16. }
17.
18. void get() {
19. cout << "\nEnter Account No: ";
20. cin >> acc_no;
21. cin.ignore(); // Clear the input buffer
22. cout << "Enter Account Type: ";
23. cin.getline(acc_type, 30); // Use getline to read the account type
24. cout << "Enter Balance: ";
25. cin >> balance;
26. }
27.
28. void display() {
29. cout << "\n\nAccount No: " << acc_no;
30. cout << "\nAccount Type: " << acc_type;
31. cout << "\nBalance: " << balance << endl;
32. }
33. };
34.
35. int main() {
36. int num, i;
37.
38. cout << "How many Records You Want: ";
39. cin >> num;
40.
41. // Dynamic memory allocation for accounts
42. Account *a = new Account[num];
43.
44. // Accept account details
45. for (i = 0; i < num; i++) {
46. a[i].get();
47. }
48.
49. // Display account details
50. for (i = 0; i < num; i++) {
51. a[i].display();
52. }
53.
54. // Free allocated memory
55. delete[] a;
56.
57. return 0;
58. }
2.Create a C++ class City with data members City code, City name, population. Write
necessary member functions for the following:
i.Accept details of n cities
ii. Display details of n cities in ascending order of population.
iii. Display details of a particular city.
(Use Array of object and to display city information use manipulators.)[25 Marks]
1. #include <iostream>
2. #include <iomanip>
3. #include <string>
4. using namespace std;
5.
6. class City {
7. public:
8. int population;
9. int city_code;
10. string name;
11.
12. void accept() {
13. cout << "\nEnter name of city: ";
14. cin >> name;
15. cout << "Enter city code: ";
16. cin >> city_code;
17. cout << "Enter Population of city: ";
18. cin >> population;
19. }
20.
21. void display() {
22. cout << "\n\nName of city: " << name << endl;
23. cout << "Population: " << population << endl;
24. cout << "City code: " << city_code << endl;
25. }
26. };
27.
28. // Function to sort cities based on population
29. void sortCities(City cities[], int num) {
30. for (int i = 0; i < num - 1; i++) {
31. for (int j = i + 1; j < num; j++) {
32. if (cities[i].population > cities[j].population) {
33. swap(cities[i], cities[j]);
34. }
35. }
36. }
37. }
38.
39. // Function to search for a city by name
40. void searchCity(City cities[], int num, const string &cityName) {
41. bool found = false;
42. for (int i = 0; i < num; i++) {
43. if (cities[i].name == cityName) {
44. cities[i].display();
45. found = true;
46. break;
47. }
48. }
49. if (!found) {
50. cout << "\nCity not found." << endl;
51. }
52. }
53.
54. int main() {
55. City cities[30];
56. int num, ch;
57. char cont;
58.
59. do {
60. cout << "\n1. Accept and Display";
61. cout << "\n2. Display in Ascending Order of Population";
62. cout << "\n3. Search by City";
63. cout << "\nEnter Your Choice: ";
64. cin >> ch;
65.
66. switch (ch) {
67. case 1:
68. cout << "\nHow many records you want to insert: ";
69. cin >> num;
70. for (int i = 0; i < num; i++) {
71. cities[i].accept();
72. }
73. for (int i = 0; i < num; i++) {
74. cities[i].display();
75. }
76. break;
77.
78. case 2:
79. sortCities(cities, num);
80. cout << "\nCities in Ascending Order of Population:\n";
81. for (int i = 0; i < num; i++) {
82. cities[i].display();
83. }
84. break;
85.
86. case 3: {
87. string cityName;
88. cout << "\nEnter city name: ";
89. cin >> cityName;
90. searchCity(cities, num, cityName);
91. break;
92. }
93.
94. default:
95. cout << "\nInvalid choice. Please try again." << endl;
96. }
97.
98. cout << "\nDo you want to continue (Y/N)? ";
99. cin >> cont;
100. } while (cont == 'Y' || cont == 'y');
101.
102. return 0;
103. }
Slip 11:
1 . Create a C++ class MyArray, which contains single dimensional integer array of a given
size. Write a member function to display sum of given array elements. (Use Dynamic
Constructor and Destructor)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class MyArray {
5. int size;
6. int *ptr;
7.
8. public:
9. // Constructor
10. MyArray(int no) {
11. size = no;
12. ptr = new int[size]; // Dynamic memory allocation
13. for (int i = 0; i < size; i++) {
14. cout << "Enter element " << (i + 1) << ": ";
15. cin >> ptr[i];
16. }
17. }
18.
19. // Function to display elements
20. void display() {
21. cout << "\nElements are:\n";
22. for (int i = 0; i < size; i++) {
23. cout << ptr[i] << "\t";
24. }
25. cout << endl;
26. }
27.
28. // Function to calculate the sum of the array elements
29. void calculateSum() {
30. int sum = 0;
31. for (int i = 0; i < size; i++) {
32. sum += ptr[i];
33. }
34. cout << "\nSum of all elements is: " << sum << endl;
35. }
36.
37. // Destructor
38. ~MyArray() {
39. delete[] ptr; // Free dynamically allocated memory
40. }
41. };
42.
43. int main() {
44. int n;
45. cout << "Enter size of the array: ";
46. cin >> n;
47. MyArray d(n); // Create an object of MyArray
48. d.display(); // Display the elements
49. d.calculateSum(); // Calculate and display the sum
50. return 0;
51. }
2 . Create a base class Student with data members Roll No, Name. Derives two classes from
it, class Theory with data members Ml, M2, M3, M4 and class Practical with data members
PI, P2. Class Result(Total Marks, Percentage, Grade) inherits both Theory and Practical
classes.
(Use concept of Virtual Base Class and protected access specifiers)
Write a C++ menu driven program to perform the following functions:
i. Accept Student Information
ii. Display Student Information
iii. Calculate Total marks, Percentage and Grade.[25 Marks]
1. #include <iostream>
2. #include <string>
3. using namespace std;
4.
5. class Student {
6. protected:
7. int rno;
8. string name;
9.
10. public:
11. void getDetails();
12. };
13.
14. class Theory : public virtual Student {
15. protected:
16. int mark1, mark2, mark3, mark4;
17.
18. public:
19. void getMarks();
20. };
21.
22. class Practical : public virtual Student {
23. protected:
24. int p1, p2;
25.
26. public:
27. void getPractical();
28. };
29.
30. class Result : public Theory, public Practical {
31. private:
32. int total_marks;
33. float per;
34. string grade;
35.
36. public:
37. void calculate();
38. void display();
39. };
40.
41. void Student::getDetails() {
42. cout << "\nEnter Roll No and Name: ";
43. cin >> rno >> name;
44. }
45.
46. void Theory::getMarks() {
47. cout << "\nEnter marks of 4 subjects: ";
48. cin >> mark1 >> mark2 >> mark3 >> mark4;
49. }
50.
51. void Practical::getPractical() {
52. cout << "\nEnter practical marks: ";
53. cin >> p1 >> p2;
54. }
55.
56. void Result::calculate() {
57. total_marks = mark1 + mark2 + mark3 + mark4 + p1 + p2;
58. per = total_marks / 6.0; // Use floating-point division
59. if (per < 50)
60. grade = "C";
61. else if (per < 60)
62. grade = "B";
63. else if (per < 75)
64. grade = "A";
65. else
66. grade = "A+";
67. }
68.
69. void Result::display() {
70. cout << "\n\nRoll No: " << rno << "\nName: " << name;
71. cout << "\n\nTheory Marks: ";
72. cout << "\nMarks 1: " << mark1;
73. cout << "\nMarks 2: " << mark2;
74. cout << "\nMarks 3: " << mark3;
75. cout << "\nMarks 4: " << mark4;
76. cout << "\n\nPractical Marks: ";
77. cout << "\nPractical 1: " << p1;
78. cout << "\nPractical 2: " << p2;
79. cout << "\n\nTotal Marks: " << total_marks;
80. cout << "\nPercentage: " << per;
81. cout << "\nGrade: " << grade << endl;
82. }
83.
84. int main() {
85. int n, ch;
86. Result r[40];
87.
88. do {
89. cout << "\n1. Accept Student Information";
90. cout << "\n2. Display Student Information";
91. cout << "\n3. Calculate Percentage and Grade";
92. cout << "\n4. Exit";
93. cout << "\n\nEnter your choice: ";
94. cin >> ch;
95.
96. switch (ch) {
97. case 1:
98. cout << "\nEnter Number of Students: ";
99. cin >> n;
100. for (int i = 0; i < n; i++) {
101. cout << "\nEnter details for Student " << (i + 1) << ":\n";
102. r[i].getDetails();
103. r[i].getMarks();
104. r[i].getPractical();
105. }
106. break;
107.
108. case 2:
109. for (int i = 0; i < n; i++) {
110. r[i].display();
111. }
112. break;
113.
114. case 3:
115. for (int i = 0; i < n; i++) {
116. r[i].calculate();
117. r[i].display(); // Display results after calculation
118. }
119. break;
120.
121. case 4:
122. cout << "Exiting the program." << endl;
123. break;
124.
125. default:
126. cout << "Invalid choice. Please try again." << endl;
127. }
128. } while (ch != 4); // Continue until the user chooses to exit
129.
130. return 0;
131. }
Slip 12:
1 .Write a C++ program to create a class Date with data members day, month, and year. Use
default and parameterized constructor to initialize date and display date in dd-Mon-yyyy
format. (Example: Input: 04-01-2021 Output: 04-Jan-2021)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Date {
5. private:
6. int dd, mm, yy;
7.
8. public:
9. // Default constructor
10. Date() : dd(1), mm(1), yy(2000) {}
11.
12. // Parameterized constructor
13. Date(int d, int m, int y) {
14. dd = d;
15. mm = m;
16. yy = y;
17. }
18.
19. // Function to display the date in dd-Mon-yyyy format
20. void display() {
21. cout << "\n---Given Date---\n";
22. cout << dd << "-" << mm << "-" << yy;
23. cout << "\n\nAfter formatting date is: ";
24.
25. // Month names array
26. const char* monthNames[] = {"Invalid", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
27. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
28.
29. if (mm >= 1 && mm <= 12) {
30. cout << dd << "-" << monthNames[mm] << "-" << yy;
31. } else {
32. cout << "Invalid month";
33. }
34. }
35. };
36.
37. int main() {
38. int dt, m, y;
39. cout << "Enter date (dd mm yyyy): ";
40. cin >> dt >> m >> y;
41.
42. Date d(dt, m, y); // Create Date object using parameterized constructor
43. d.display(); // Display the formatted date
44.
45. return 0;
46. }
2.Create a C++ class Weight with data members kilogram, gram. Write a C++ program using
operator overloading to perform following functions:
i. To accept weight.
ii. To display weight in kilogram and gram format.
iii. Overload +— operator to add two weights.
iv. Overload +— operator to check equality of two weights [25 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Weight {
5. private:
6. int kilogram;
7. int gram;
8.
9. public:
10. // Constructor to initialize weight
11. Weight() : kilogram(0), gram(0) {}
12.
13. // Function to accept weight
14. void getData() {
15. cout << "\nEnter kilograms: ";
16. cin >> kilogram;
17. cout << "Enter grams: ";
18. cin >> gram;
19. }
20.
21. // Function to display weight
22. void display() const {
23. cout << kilogram << " kg " << gram << " g";
24. }
25.
26. // Overload += operator to add two weights
27. Weight operator+=(const Weight &d) {
28. this->kilogram += d.kilogram;
29. this->gram += d.gram;
30.
31. // Convert grams to kilograms if greater than 1000
32. if (this->gram >= 1000) {
33. this->kilogram += this->gram / 1000;
34. this->gram = this->gram % 1000;
35. }
36. return *this; // Return the current object
37. }
38.
39. // Overload == operator to check equality of two weights
40. bool operator==(const Weight &d) const {
41. // Convert both weights to grams for comparison
42. int totalGrams1 = this->kilogram * 1000 + this->gram;
43. int totalGrams2 = d.kilogram * 1000 + d.gram;
44. return totalGrams1 == totalGrams2;
45. }
46. };
47.
48. int main() {
49. Weight w1, w2, w3;
50.
51. // Accept weights
52. w1.getData();
53. w2.getData();
54.
55. // Add weights
56. w3 = w1; // Copy w1 to w3
57. w3 += w2; // Add w2 to w3
58.
59. // Display the result
60. cout << "\nTotal Weight: ";
61. w3.display();
62.
63. // Check equality
64. Weight w4, w5;
65. cout << "\n\nEnter weight for comparison:\n";
66. w4.getData();
67. cout << "Enter another weight for comparison:\n";
68. w5.getData();
69.
70. if (w4 == w5) {
71. cout << "\nBoth weights are the same.";
72. } else {
73. cout << "\nBoth weights are not the same.";
74. }
75.
76. return 0;
77. }
Slip 13:
1 .Write a C++ program to create a class Product with data members Product id, Product
Name, Qty, Price. Write member functions to accept and display Product information also
display number of objects created for Product class. (Use Static data member and Static
member function)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Product {
5. private:
6. int id, price, qty;
7. char i_name[20];
8. static int cnt; // Static data member to count objects
9.
10. public:
11. // Constructor to initialize the static counter
12. Product() {
13. cnt = 0; // Initialize counter
14. }
15.
16. // Function to accept product data
17. void getData() {
18. cout << "\nEnter Product Id: ";
19. cin >> id;
20. cout << "Enter Product Name: ";
21. cin >> i_name;
22. cout << "Enter Product Price: ";
23. cin >> price;
24. cout << "Enter Product Qty: ";
25. cin >> qty;
26. cnt++; // Increment the count of objects created
27. }
28.
29. // Function to display product data
30. void display() const {
31. cout << "\n\nProduct Id = " << id;
32. cout << "\nProduct Name = " << i_name;
33. cout << "\nProduct Price = " << price;
34. cout << "\nProduct Qty = " << qty;
35. }
36.
37. // Static member function to display the number of objects created
38. static void displayCount() {
39. cout << "\nNumber of objects created for class are: " << cnt;
40. }
41. };
42.
43. // Initialize static member
44. int Product::cnt = 0;
45.
46. int main() {
47. Product ob[10]; // Array of Product objects
48. int n;
49.
50. cout << "\nEnter Number of products: ";
51. cin >> n;
52.
53. // Accept product data for n products
54. for (int i = 0; i < n; i++) {
55. ob[i].getData();
56. }
57.
58. // Display product data for n products
59. for (int i = 0; i < n; i++) {
60. ob[i].display();
61. }
62.
63. // Display the number of objects created
64. Product::displayCount();
65.
66. return 0;
67. }
2.Create a C++ class Cuboid with data members length, breadth, and height. Write necessary
member functions for the following:
i. void setvalues(float,float,float) to set values of data members.
ii. void getvalues( ) to display values of data members.
iii. float volume( ) to calculate and return the volume of cuboid.
iv. float surface area( ) to calculate and return the surface area of cuboid.
(Use Inline function)[25 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Cuboid {
5. private:
6. float len, bre, hei;
7.
8. public:
9. // Function to set values of data members
10. void setValues(float length, float breadth, float height) {
11. len = length;
12. bre = breadth;
13. hei = height;
14. }
15.
16. // Function to display values of data members
17. void getValues() const {
18. cout << "Length: " << len << ", Breadth: " << bre << ", Height: " << hei << endl;
19. }
20.
21. // Inline function to calculate and return the volume of the cuboid
22. inline float volume() const {
23. return len * bre * hei;
24. }
25.
26. // Inline function to calculate and return the surface area of the cuboid
27. inline float surfaceArea() const {
28. return 2 * (len * bre + bre * hei + len * hei);
29. }
30. };
31.
32. int main() {
33. Cuboid c;
34. float length, breadth, height;
35.
36. // Input values for the cuboid
37. cout << "Enter Length, Breadth and Height of cuboid: ";
38. cin >> length >> breadth >> height;
39.
40. // Set values for the cuboid
41. c.setValues(length, breadth, height);
42.
43. // Display values
44. c.getValues();
45.
46. // Display volume and surface area
47. cout << "The Volume of the cuboid is: " << c.volume() << endl;
48. cout << "The Surface area of the cuboid is: " << c.surfaceArea() << endl;
49.
50. return 0;
51. }
Slip 14:
1.Write a C++ program to accept radius of a Circle. Calculate and display diameter,
circumference as well as area of a Circle. (Use Inline function)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. // Inline function to calculate diameter
5. inline float diameter(float r) {
6. return 2 * r; // Corrected to return diameter
7. }
8.
9. // Inline function to calculate area of the circle
10. inline float circleArea(float r) {
11. return 3.14 * r * r; // Area = πr²
12. }
13.
14. // Inline function to calculate circumference of the circle
15. inline float circumference(float r) {
16. return 3.14 * 2 * r; // Circumference = 2πr
17. }
18.
19. int main() {
20. float radius;
21.
22. // Input radius of the circle
23. cout << "Enter Radius of circle: ";
24. cin >> radius;
25.
26. // Display diameter, area, and circumference
27. cout << "\nDiameter of circle: " << diameter(radius);
28. cout << "\nArea of circle: " << circleArea(radius);
29. cout << "\nCircumference of circle: " << circumference(radius) << endl;
30.
31. return 0;
32. }
2 .Create a C++ class MyString with data members a character pointer and str length. (Use
new and delete operator).
Write a C++ program using operator overloading to perform following operation:
i. To reverse the case of each alphabet from a given string.
ii. To compare length of two strings.
iii. To add constant ‘n’ to each alphabet of a string.[25 Marks]
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4.
5. class MyString {
6. private:
7. char *str;
8. int length;
9.
10. public:
11. // Constructor
12. MyString(const char *s) {
13. length = strlen(s);
14. str = new char[length + 1];
15. strcpy(str, s);
16. }
17.
18. // Copy Constructor
19. MyString(const MyString &other) {
20. length = other.length;
21. str = new char[length + 1];
22. strcpy(str, other.str);
23. }
24.
25. // Destructor
26. ~MyString() {
27. delete[] str;
28. }
29.
30. // Function to reverse the case of each alphabet
31. MyString& reverseCase() {
32. for (int i = 0; i < length; ++i) {
33. if (isalpha(str[i])) {
34. if (islower(str[i]))
35. str[i] = toupper(str[i]);
36. else
37. str[i] = tolower(str[i]);
38. }
39. }
40. return *this;
41. }
42.
43. // Function to compare length of two strings
44. bool operator<(const MyString &other) const {
45. return length < other.length;
46. }
47.
48. // Function to add a constant 'n' to each alphabet of a string
49. MyString operator+(int n) const {
50. MyString newStr(*this); // Create a copy of the current string
51. for (int i = 0; i < newStr.length; ++i) {
52. if (isalpha(newStr.str[i])) {
53. newStr.str[i] += n;
54. }
55. }
56. return newStr; // Return the new string
57. }
58.
59. // Function to display the string
60. void display() const {
61. cout << str << endl;
62. }
63. };
64.
65. int main() {
66. MyString str1("Hello World!");
67. MyString str2("Goodbye");
68.
69. cout << "Original strings:" << endl;
70. str1.display();
71. str2.display();
72.
73. // Reverse the case of each alphabet
74. str1.reverseCase();
75. cout << "After reversing case of String 1:" << endl;
76. str1.display();
77.
78. // Compare lengths of two strings
79. if (str1 < str2) {
80. cout << "String 1 is shorter than String 2." << endl;
81. } else {
82. cout << "String 1 is longer than or equal to String 2." << endl;
83. }
84.
85. // Add a constant 'n' to each alphabet of a string
86. MyString str2Modified = str2 + 1; // Create a new string with modified characters
87. cout << "After adding 1 to each alphabet of String 2:" << endl;
88. str2Modified.display();
89.
90. return 0;
91. }
Slip 15:
1.Create a C++ class Fraction with data members Numerator and Denominator. Write a C++
program to calculate and display sum of two fractions. (Use Constructor)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Fraction {
5. private:
6. int num; // Numerator
7. int dnm; // Denominator
8.
9. public:
10. // Default constructor
11. Fraction() : num(0), dnm(1) {}
12.
13. // Parameterized constructor
14. Fraction(int n, int d) {
15. if (d == 0) {
16. cout << "Denominator cannot be zero. Setting to 1." << endl;
17. dnm = 1;
18. } else {
19. dnm = d;
20. }
21. num = n;
22. }
23.
24. // Operator overloading for addition
25. Fraction operator+(const Fraction &f2) const {
26. int newNum = num * f2.dnm + f2.num * dnm; // Calculate new numerator
27. int newDnm = dnm * f2.dnm; // Calculate new denominator
28. return Fraction(newNum, newDnm); // Return new Fraction object
29. }
30.
31. // Function to display the fraction
32. void display() const {
33. cout << num << "/" << dnm << endl;
34. }
35. };
36.
37. int main() {
38. int n1, d1, n2, d2;
39.
40. cout << "Enter first fraction (numerator and denominator): ";
41. cin >> n1 >> d1;
42. cout << "Enter second fraction (numerator and denominator): ";
43. cin >> n2 >> d2;
44.
45. Fraction f1(n1, d1);
46. Fraction f2(n2, d2);
47.
48. // Calculate the sum of the two fractions
49. Fraction f3 = f1 + f2;
50.
51. // Display the result
52. cout << "Sum of the fractions: ";
53. f3.display();
54.
55. return 0;
56. }
2.Write a C++ class Seller (S Name, Product name, Sales Quantity, Target Quantity, Month,
Commission). Each salesman deals with a separate product and is assigned a target for a
month. At the end of the month his monthly sales is compared with target and commission
is calculated as follows:
i. If Sales Quantity>Target Quantity then commission is 25% of extra sales made + 10% of
target.
ii.If Sales Quantity = Target Quantity then commission is of target.
iii. Otherwise commission is zero.
Display salesman information along with commission obtained.
(Use array of objects)[25 Marks]
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4.
5. class Seller {
6. private:
7. char sname[20]; // Salesman name
8. char pname[20]; // Product name
9. int squantity; // Sales quantity
10. int target; // Target quantity
11. float commission; // Commission earned
12.
13. public:
14. // Function to get seller details
15. void get() {
16. cout << "\nEnter salesman name: ";
17. cin >> sname;
18.
19. cout << "Enter product name: ";
20. cin >> pname;
21.
22. cout << "Enter sales quantity: ";
23. cin >> squantity;
24.
25. cout << "Enter target: ";
26. cin >> target;
27. }
28.
29. // Function to calculate and display seller information
30. void put() {
31. cout << "\n\nSalesman name: " << sname;
32. cout << "\nProduct name: " << pname;
33. cout << "\nSales quantity: " << squantity;
34. cout << "\nTarget: " << target;
35.
36. // Calculate commission
37. if (squantity > target) {
38. commission = ((squantity - target) * 0.25) + (target * 0.10);
39. } else if (squantity == target) {
40. commission = target * 0.10;
41. } else {
42. commission = 0;
43. }
44.
45. cout << "\nCommission: " << commission;
46. }
47. };
48.
49. int main() {
50. Seller sman[10]; // Array of Seller objects
51. int n;
52.
53. cout << "\nEnter how many salesmen: ";
54. cin >> n;
55.
56. // Input validation for number of salesmen
57. if (n > 10) {
58. cout << "Maximum number of salesmen is 10." << endl;
59. return 1; // Exit if the number exceeds the limit
60. }
61.
62. // Get details for each salesman
63. for (int i = 0; i < n; i++) {
64. sman[i].get();
65. }
66.
67. // Display details and commission for each salesman
68. for (int i = 0; i < n; i++) {
69. sman[i].put();
70. }
71.
72. return 0;
73. }
Slip 16:
1.Write a C++ program to create a class Machine with data members Machine Id, Machine
Name, Price. Create and initialize all values of Machine object by using parameterized
constructor and copy constructor.
Display details of Machine using setw( ) and setprecision( ).[15 Marks]
1. #include <iostream>
2. #include <iomanip>
3. #include <cstring>
4. using namespace std;
5.
6. class Machine {
7. private:
8. int machine_id;
9. float price; // Changed to float for price
10. char name[20];
11.
12. public:
13. // Parameterized constructor
14. Machine(int id, float p, const char *n) {
15. machine_id = id;
16. price = p;
17. strcpy(name, n);
18. }
19.
20. // Copy constructor
21. Machine(const Machine &other) {
22. machine_id = other.machine_id;
23. price = other.price;
24. strcpy(name, other.name);
25. }
26.
27. // Function to display machine details
28. void display() const {
29. cout << "\nName: " << setw(20) << left << name;
30. cout << "\nMachine ID: " << setw(10) << machine_id;
31. cout << "\nPrice: " << fixed << setprecision(2) << price << endl;
32. }
33. };
34.
35. int main() {
36. Machine o1(13, 345.50, "Deep"); // Normal or parameterized constructor
37. Machine o2 = o1; // Copy constructor
38.
39. cout << "\nNormal constructor:";
40. o1.display();
41.
42. cout << "\nCopy constructor:";
43. o2.display();
44.
45. return 0;
46. }
2.Create a class Matrix Write necessary member functions for the following:
i. To accept a Matrix
ii. To display a Matrix
iii. Overload unary ‘-‘ operator to calculate transpose of a Matrix.
iv. Overload unaryoperator to increment matrix elements by I[25 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Matrix {
5. private:
6. int a[3][3]; // 3x3 matrix
7.
8. public:
9. // Function to accept matrix elements
10. void get() {
11. cout << "\nEnter matrix elements (3x3): \n";
12. for (int i = 0; i < 3; i++) {
13. for (int j = 0; j < 3; j++) {
14. cin >> a[i][j];
15. }
16. }
17. }
18.
19. // Function to display the matrix
20. void put() const {
21. cout << "\nMatrix is:\n";
22. for (int i = 0; i < 3; i++) {
23. for (int j = 0; j < 3; j++) {
24. cout << a[i][j] << "\t";
25. }
26. cout << endl; // New line after each row
27. }
28. }
29.
30. // Overload unary '-' operator to calculate transpose of the matrix
31. Matrix operator-() const {
32. Matrix transposed;
33. for (int i = 0; i < 3; i++) {
34. for (int j = 0; j < 3; j++) {
35. transposed.a[j][i] = a[i][j]; // Swap rows and columns
36. }
37. }
38. return transposed; // Return the transposed matrix
39. }
40.
41. // Overload unary '++' operator to increment matrix elements by 1
42. void operator++() {
43. for (int i = 0; i < 3; i++) {
44. for (int j = 0; j < 3; j++) {
45. a[i][j]++; // Increment each element
46. }
47. }
48. }
49. };
50.
51. int main() {
52. Matrix m1;
53. cout << "\nEnter matrix values: ";
54. m1.get();
55. m1.put();
56.
57. // Calculate and display the transpose of the matrix
58. Matrix transposed = -m1; // Using unary '-' operator
59. cout << "\nTranspose of the matrix:\n";
60. transposed.put();
61.
62. // Increment the matrix elements
63. ++m1; // Using unary '++' operator
64. cout << "\nAfter incrementing each element:\n";
65. m1.put();
66.
67. return 0;
68. }
Slip 17:
1. Create a C++ class MyMatrix. Write C++ program to accept an display matrix. Overload
Binary “-” operator to calculate subtraction of matrix.[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class MyMatrix {
5. private:
6. int a[3][3]; // 3x3 matrix
7.
8. public:
9. // Function to accept matrix elements
10. void get() {
11. cout << "\nEnter matrix elements (3x3): \n";
12. for (int i = 0; i < 3; i++) {
13. for (int j = 0; j < 3; j++) {
14. cin >> a[i][j];
15. }
16. }
17. }
18.
19. // Function to display the matrix
20. void put() const {
21. cout << "\nMatrix is:\n";
22. for (int i = 0; i < 3; i++) {
23. for (int j = 0; j < 3; j++) {
24. cout << a[i][j] << "\t";
25. }
26. cout << endl; // New line after each row
27. }
28. }
29.
30. // Overload binary '-' operator to calculate subtraction of matrices
31. MyMatrix operator-(const MyMatrix &z) const {
32. MyMatrix result; // Create a new matrix to store the result
33. for (int i = 0; i < 3; i++) {
34. for (int j = 0; j < 3; j++) {
35. result.a[i][j] = a[i][j] - z.a[i][j]; // Subtract corresponding elements
36. }
37. }
38. return result; // Return the resulting matrix
39. }
40. };
41.
42. int main() {
43. MyMatrix m1, m2;
44.
45. // Accept matrix elements
46. m1.get();
47. m2.get();
48.
49. // Display the matrices
50. cout << "\nMatrix 1 is: ";
51. m1.put();
52. cout << "\nMatrix 2 is: ";
53. m2.put();
54.
55. // Calculate and display the subtraction of the matrices
56. MyMatrix result = m1 - m2; // Using the overloaded '-' operator
57. cout << "\nSubtraction of matrices is: ";
58. result.put();
59.
60. return 0;
61. }
2.Design two base classes Student (S id, Name, Class) and Competition (C id, C Name).
Derive a class Stud Comp(Rank) from it. Write a menu driven program to perform following
functions:
i. Accept information.
ii. Display information.
iii. Display Student Details In the ascending order of Rank of a specified competition.
(Use array of objects)[25 Marks]
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4.
5. class Student {
6. public:
7. int roll;
8. char name[20];
9. char std[10];
10.
11. void accept_s();
12. void display_s() const;
13. };
14.
15. void Student::accept_s() {
16. cout << "\nEnter roll no: ";
17. cin >> roll;
18. cout << "Enter name of student: ";
19. cin >> name;
20. cout << "Enter class of student: ";
21. cin >> std;
22. }
23.
24. void Student::display_s() const {
25. cout << "\nStudent Details:\n";
26. cout << "Roll No: " << roll;
27. cout << "\nName: " << name;
28. cout << "\nClass: " << std << endl;
29. }
30.
31. class Competition {
32. public:
33. int cid;
34. char cname[20];
35.
36. void accept_c();
37. void display_c() const;
38. };
39.
40. void Competition::accept_c() {
41. cout << "\nEnter competition id: ";
42. cin >> cid;
43. cout << "Enter competition name: ";
44. cin >> cname;
45. }
46.
47. void Competition::display_c() const {
48. cout << "\nCompetition ID: " << cid;
49. cout << "\nCompetition Name: " << cname << endl;
50. }
51.
52. class StudComp : public Student, public Competition {
53. public:
54. int rank;
55.
56. void accept_sc();
57. void display_sc() const;
58. };
59.
60. void StudComp::accept_sc() {
61. cout << "Enter rank: ";
62. cin >> rank;
63. }
64.
65. void StudComp::display_sc() const {
66. cout << "Rank: " << rank << endl;
67. }
68.
69. void sort(StudComp *sc, int num) {
70. for (int i = 0; i < num - 1; i++) {
71. for (int j = 0; j < num - i - 1; j++) {
72. if (sc[j].rank > sc[j + 1].rank) {
73. // Swap the entire StudComp object
74. StudComp temp = sc[j];
75. sc[j] = sc[j + 1];
76. sc[j + 1] = temp;
77. }
78. }
79. }
80. cout << "\nSorted details by rank:\n";
81. for (int i = 0; i < num; i++) {
82. cout << "Rank: " << sc[i].rank << ", Roll No: " << sc[i].roll << endl;
83. }
84. }
85.
86. int main() {
87. int num, ch;
88.
89. cout << "Enter number of students: ";
90. cin >> num;
91.
92. StudComp *sc = new StudComp[num]; // Allocate memory for students
93.
94. do {
95. cout << "\n1. Accept information";
96. cout << "\n2. Display information";
97. cout << "\n3. Display information in ascending order of rank";
98. cout << "\n4. Exit";
99. cout << "\n\nEnter your choice: ";
100. cin >> ch;
101.
102. switch (ch) {
103. case 1:
104. for (int i = 0; i < num; i++) {
105. cout << "\nEntering details for student " << (i + 1) << ":\n";
106. sc[i].accept_s();
107. sc[i].accept_c();
108. sc[i].accept_sc();
109. }
110. break;
111.
112. case 2:
113. for (int i = 0; i < num; i++) {
114. cout << "\nDetails for student " << (i + 1) << ":\n";
115. sc[i].display_s();
116. sc[i].display_c();
117. sc[i].display_sc();
118. }
119. break;
120.
121. case 3:
122. sort(sc, num); // Sort and display the students by rank
123. break;
124.
125. case 4:
126. cout << "Exiting the program." << endl;
127. delete[] sc; // Free allocated memory
128. exit(0);
129.
130. default:
131. cout << "Invalid choice! Please try again." << endl;
132. }
133. } while (ch <= 4);
134.
135. delete[] sc; // Free allocated memory
136. return 0;
137. }
Slip 18:
1.Create a C++ class Student with data members Roll no, S Name, Class, Percentage. Accept
two students information and display information of student having maximum percentage.
(Use this pointer)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Student {
5. public:
6. int id;
7. float percentage; // Changed to float for percentage
8. char name[40];
9. char class1[40];
10.
11. void accept() {
12. cout << "\nEnter ID: ";
13. cin >> id;
14. cout << "Enter name: ";
15. cin >> name;
16. cout << "Enter class: ";
17. cin >> class1;
18. cout << "Enter percentage: ";
19. cin >> percentage;
20. }
21.
22. void display() const {
23. cout << "\n\nStudent ID: " << this->id;
24. cout << "\nStudent Name: " << this->name;
25. cout << "\nStudent Class: " << this->class1;
26. cout << "\nStudent Percentage: " << this->percentage << "%" << endl;
27. }
28. };
29.
30. int main() {
31. Student s[20];
32. int num, ch;
33.
34. do {
35. cout << "\n1. Accept information";
36. cout << "\n2. Display information";
37. cout << "\n3. Maximum percentage";
38. cout << "\n4. Exit";
39. cout << "\n\nEnter your choice: ";
40. cin >> ch;
41.
42. switch (ch) {
43. case 1:
44. cout << "\nEnter number of students: ";
45. cin >> num;
46. for (int i = 0; i < num; i++) {
47. s[i].accept();
48. }
49. break;
50.
51. case 2:
52. for (int i = 0; i < num; i++) {
53. s[i].display();
54. }
55. break;
56.
57. case 3: {
58. int maxIndex = 0; // Start with the first student
59. for (int i = 1; i < num; i++) {
60. if (s[i].percentage > s[maxIndex].percentage) {
61. maxIndex = i; // Update maxIndex if a higher percentage is found
62. }
63. }
64. cout << "\n\nStudent with highest percentage is:\n";
65. s[maxIndex].display(); // Display the student with the highest percentage
66. break;
67. }
68.
69. case 4:
70. cout << "Exiting the program." << endl;
71. exit(0);
72.
73. default:
74. cout << "Invalid choice! Please try again." << endl;
75. }
76. } while (ch <= 4);
77.
78. return 0;
79. }
1. #include <iostream>
2. using namespace std;
3.
4. class MyArray {
5. private:
6. int *arr;
7. int size;
8.
9. public:
10. // Constructor
11. MyArray(int s) : size(s) {
12. arr = new int[size];
13. }
14.
15. // Destructor
16. ~MyArray() {
17. delete[] arr;
18. }
19.
20. // Function to accept array elements
21. void acceptElements() {
22. cout << "Enter " << size << " elements:\n";
23. for (int i = 0; i < size; ++i) {
24. cin >> arr[i];
25. }
26. }
27.
28. // Function to display array elements
29. void displayElements() const {
30. cout << "Array elements are:\n";
31. for (int i = 0; i < size; ++i) {
32. cout << arr[i] << " ";
33. }
34. cout << endl;
35. }
36.
37. // Overloading unary operator to reverse array elements
38. MyArray operator-() const {
39. MyArray temp(size);
40. for (int i = 0; i < size; ++i) {
41. temp.arr[i] = arr[size - 1 - i];
42. }
43. return temp;
44. }
45.
46. // Overloading binary operator to add a constant to all array elements
47. MyArray operator+(int n) const {
48. MyArray temp(size);
49. for (int i = 0; i < size; ++i) {
50. temp.arr[i] = arr[i] + n;
51. }
52. return temp;
53. }
54. };
55.
56. int main() {
57. int size;
58. cout << "Enter size of the array: ";
59. cin >> size;
60.
61. MyArray arr(size);
62. arr.acceptElements();
63.
64. // Display original array
65. cout << "Original ";
66. arr.displayElements();
67.
68. // Reverse array elements
69. MyArray reversedArr = -arr;
70. cout << "Reversed ";
71. reversedArr.displayElements();
72.
73. // Add constant to array elements
74. int constant;
75. cout << "Enter constant to add to array elements: ";
76. cin >> constant;
77. MyArray modifiedArr = arr + constant;
78. cout << "Modified ";
79. modifiedArr.displayElements();
80.
81. return 0;
82. }
Slip 19:
1.Write a C++ program to create a class Distance with data members meter and centimeter
to represent distance. Write a function Larger( ) to return the larger of two distances. (Use
this pointer)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Distance {
5. private:
6. int meter;
7. float centimeter;
8.
9. public:
10. // Function to get distance values
11. void get() {
12. cout << "\nEnter meter value: ";
13. cin >> meter;
14. cout << "Enter centimeter value: ";
15. cin >> centimeter;
16. }
17.
18. // Function to display distance values
19. void put() const {
20. cout << "\nDistance: " << meter << " meters and " << centimeter << "
centimeters" << endl;
21. }
22.
23. // Function to return the larger distance
24. Distance larger(const Distance &d) {
25. // Convert both distances to centimeters for comparison
26. float totalCentimeters1 = (this->meter * 100) + this->centimeter;
27. float totalCentimeters2 = (d.meter * 100) + d.centimeter;
28.
29. // Return the larger distance
30. if (totalCentimeters1 > totalCentimeters2) {
31. return *this; // Return the current object
32. } else {
33. return d; // Return the passed object
34. }
35. }
36. };
37.
38. int main() {
39. Distance d1, d2, largerDistance;
40.
41. cout << "\nEnter First distance: ";
42. d1.get();
43. cout << "\nEnter Second distance: ";
44. d2.get();
45.
46. largerDistance = d1.larger(d2); // Compare d1 with d2
47. cout << "\nLarger Distance is: ";
48. largerDistance.put();
49.
50. return 0;
51. }
2. Create a C++ base class Media. Derive two different classes from it, class NewsPaper with
data members N Name, N Editor, N Price, No of Pages and class Magazine with data
members M Name, M Editor, M Price. Write a C++ program to accept and display
information of both NewsPaper and Magazine.
(Use pure virtual function)[25 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Media {
5. public:
6. virtual void display() = 0; // Pure virtual function
7. };
8.
9. class Newspaper : public Media {
10. private:
11. int no_of_pages;
12. float n_price;
13. char n_name[20];
14. char n_editor[20];
15.
16. public:
17. void getNewspaper() {
18. cout << "\nEnter number of pages: ";
19. cin >> no_of_pages;
20. cout << "Enter newspaper price: ";
21. cin >> n_price;
22. cout << "Enter newspaper name: ";
23. cin >> n_name;
24. cout << "Enter newspaper editor: ";
25. cin >> n_editor;
26. }
27.
28. void display() override {
29. cout << "\n\nNewspaper Details:";
30. cout << "\nNumber of Pages: " << no_of_pages;
31. cout << "\nPrice: " << n_price;
32. cout << "\nName: " << n_name;
33. cout << "\nEditor: " << n_editor << endl;
34. }
35. };
36.
37. class Magazine : public Media {
38. private:
39. char m_name[20];
40. char m_editor[20];
41. float m_price;
42.
43. public:
44. void getMagazine() {
45. cout << "\n\nEnter magazine name: ";
46. cin >> m_name;
47. cout << "Enter magazine editor: ";
48. cin >> m_editor;
49. cout << "Enter magazine price: ";
50. cin >> m_price;
51. }
52.
53. void display() override {
54. cout << "\n\nMagazine Details:";
55. cout << "\nName: " << m_name;
56. cout << "\nEditor: " << m_editor;
57. cout << "\nPrice: " << m_price << endl;
58. }
59. };
60.
61. int main() {
62. Newspaper n;
63. n.getNewspaper();
64. n.display();
65.
66. Magazine m;
67. m.getMagazine();
68. m.display();
69.
70. return 0;
71. }
Slip 20:
1.Create a C++ class Number with integer data member. Write necessary member functions
to overload the operator unary pre and post increment ‘++’[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Number {
5. private:
6. int i;
7.
8. public:
9. // Default constructor
10. Number() : i(0) {}
11.
12. // Parameterized constructor
13. Number(int num) : i(num) {}
14.
15. // Overloading the pre-increment operator
16. Number& operator++() {
17. ++i; // Increment the value
18. return *this; // Return the current object
19. }
20.
21. // Overloading the post-increment operator
22. Number operator++(int) {
23. Number temp = *this; // Store the current value
24. i++; // Increment the value
25. return temp; // Return the old value
26. }
27.
28. // Function to display the value
29. void display() const {
30. cout << "i = " << i << endl;
31. }
32. };
33.
34. int main() {
35. Number o(5), o1(5);
36.
37. cout << "\nOriginal Number = ";
38. o.display();
39.
40. ++o; // Pre-increment
41. cout << "\nAfter pre-increment number = ";
42. o.display();
43.
44. o1++; // Post-increment
45. cout << "\nAfter post-increment number = ";
46. o1.display();
47.
48. return 0;
49. }
2. Create a C++ class for inventory of Mobiles with data members Model, Mobile Company,
Color, Price and Quantity. Mobile can be sold, if stock is available, otherwise purchase will be
made.
Write necessary member functions for the following:
i.To accept mobile details from user.
ii. To sale a mobile. (Sale contains Mobile details & number of mobiles to be sold.)
iii. To Purchase a Mobile. (Purchase contains Mobile details & number of mobiles to be
purchased)[25 Marks]
1. #include <iostream>
2. #include <string>
3. using namespace std;
4.
5. class Inventory {
6. private:
7. int modelNumber;
8. string modelName;
9. int stock;
10. float price;
11.
12. public:
13. // Function to accept mobile details from user
14. void accept() {
15. cout << "\nEnter model number: ";
16. cin >> modelNumber;
17. cout << "Enter model name: ";
18. cin >> modelName;
19. cout << "Enter price: ";
20. cin >> price;
21. cout << "Enter stock: ";
22. cin >> stock;
23. }
24.
25. // Function to display mobile details
26. void display() const {
27. cout << "\n\nModel Number: " << modelNumber;
28. cout << "\nModel Name: " << modelName;
29. cout << "\nModel Price: " << price;
30. cout << "\nModel Stock: " << stock << endl;
31. }
32.
33. // Function to sell a mobile
34. int sale(int modelNo, int quantity) {
35. if (modelNumber == modelNo) {
36. if (stock >= quantity) {
37. stock -= quantity;
38. cout << "\nSale is done";
39. display();
40. return 2; // Sale successful
41. } else {
42. cout << "\nPurchase is required";
43. return 1; // Stock insufficient
44. }
45. }
46. return 0; // Model not found
47. }
48.
49. // Function to purchase a mobile
50. void purchase(int modelNo, int quantity) {
51. if (modelNo == modelNumber) {
52. stock += quantity;
53. cout << "\nPurchase is done.";
54. display();
55. }
56. }
57. };
58.
59. int main() {
60. Inventory inventory[20];
61. int quantity, response, modelNo, i, numModels;
62.
63. cout << "\nEnter number of models: ";
64. cin >> numModels;
65.
66. for (i = 0; i < numModels; i++) {
67. inventory[i].accept();
68. }
69.
70. for (i = 0; i < numModels; i++) {
71. inventory[i].display();
72. }
73.
74. cout << "\n\nEnter model number to be sold and quantity: ";
75. cin >> modelNo >> quantity;
76.
77. for (i = 0; i < numModels; i++) {
78. response = inventory[i].sale(modelNo, quantity);
79. if (response == 1) {
80. cout << "\nEnter model number to purchase and quantity: ";
81. cin >> modelNo >> quantity;
82. for (int j = 0; j < numModels; j++) {
83. inventory[j].purchase(modelNo, quantity);
84. }
85. break; // Exit the loop after attempting to purchase
86. }
87. }
88.
89. return 0;
90. }
Slip 21:
1 . Create a C++ class Employee with data members Emp id, Emp Name, Company Name and
Salary. Write member functions to accept and display Employee information. Design User
defined Manipulator to print Salary.
(For Salary set right justification, maximum width to 7 and fill remaining spaces with ‘*’)
[15 Marks]
1. #include <iostream>
2. #include <iomanip> // For std::setw and std::setfill
3. using namespace std;
4.
5. // Function declaration for the salary formatting manipulator
6. ostream& formatSalary(ostream& os, double salary);
7.
8. class Employee {
9. private:
10. int empId;
11. string empName;
12. string companyName;
13. double salary;
14.
15. public:
16. // Function to accept employee details
17. void accept() {
18. cout << "Enter Employee ID: ";
19. cin >> empId;
20. cin.ignore(); // To ignore the newline character after integer input
21. cout << "Enter Employee Name: ";
22. getline(cin, empName);
23. cout << "Enter Company Name: ";
24. getline(cin, companyName);
25. cout << "Enter Salary: ";
26. cin >> salary;
27. }
28.
29. // Function to display employee details
30. void display() const {
31. cout << "\nEmployee ID: " << empId;
32. cout << "\nEmployee Name: " << empName;
33. cout << "\nCompany Name: " << companyName;
34. cout << "\nSalary: ";
35. formatSalary(cout, salary); // Use the manipulator
36. cout << endl;
37. }
38. };
39.
40. // User-defined manipulator for salary formatting
41. ostream& formatSalary(ostream& os, double salary) {
42. os << setw(7) << setfill('*') << right << salary;
43. return os;
44. }
45.
46. // Overload the operator to use the manipulator
47. ostream& operator<<(ostream& os, const Employee& emp) {
48. emp.display();
49. return os;
50. }
51.
52. int main() {
53. Employee emp;
54. emp.accept(); // Accept employee details
55. cout << emp; // Display employee details using overloaded operator
56. return 0;
57. }
2.Create a C++ class for a two dimensional points. Write necessary member functions to
accept & display the point object. Overload the following operators:
1. #include <iostream>
2. using namespace std;
3.
4. class Point {
5. private:
6. int x, y;
7.
8. public:
9. // Function to accept point coordinates
10. void get() {
11. cout << "\nEnter 2-Dimensional point (x y): ";
12. cin >> x >> y;
13. }
14.
15. // Function to display point coordinates
16. void put() const {
17. cout << "x = " << x << "\t" << "y = " << y << endl;
18. }
19.
20. // Overloading the + operator to add two points
21. Point operator+(const Point& t) const {
22. Point tp;
23. tp.x = x + t.x;
24. tp.y = y + t.y;
25. return tp;
26. }
27.
28. // Overloading the - operator to negate the point coordinates
29. Point operator-() const {
30. Point tp;
31. tp.x = -x;
32. tp.y = -y;
33. return tp;
34. }
35.
36. // Overloading the * operator to multiply point coordinates by a constant
37. Point operator*(int n) const {
38. Point tp;
39. tp.x = x * n;
40. tp.y = y * n;
41. return tp;
42. }
43. };
44.
45. int main() {
46. Point p1, p2, p3;
47. int ch, n;
48.
49. p1.get();
50. p2.get();
51. cout << "\nFirst 2-dimensional point: ";
52. p1.put();
53. cout << "\nSecond 2-dimensional point: ";
54. p2.put();
55.
56. do {
57. cout << "\n1. Addition";
58. cout << "\n2. Negate coordinates of point";
59. cout << "\n3. Multiply coordinates by constant n";
60. cout << "\n4. Exit";
61. cout << "\n\nEnter your choice: ";
62. cin >> ch;
63.
64. switch (ch) {
65. case 1:
66. p3 = p1 + p2;
67. cout << "\nAddition of points is: ";
68. p3.put();
69. break;
70.
71. case 2:
72. cout << "\nNegated point is: ";
73. (-p1).put(); // Negate and display
74. break;
75.
76. case 3:
77. cout << "\nEnter value of n: ";
78. cin >> n;
79. p3 = p1 * n; // Multiply and store in p3
80. cout << "\nMultiplication of point by " << n << " is: ";
81. p3.put();
82. break;
83.
84. case 4:
85. cout << "Exiting..." << endl;
86. break;
87.
88. default:
89. cout << "Invalid choice! Please try again." << endl;
90. }
91. } while (ch != 4);
92.
93. return 0;
94. }
Slip 22:
1. Write a C++ program to define two function templates for calculating the square and cube
of given numbers with different data types.[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. // Function template for calculating square
5. template <class T>
6. T square(T num) {
7. return num * num;
8. }
9.
10. // Function template for calculating cube
11. template <class T>
12. T cube(T num) {
13. return num * num * num;
14. }
15.
16. int main() {
17. // Calculate square and cube for integer
18. int intNum = 2;
19. cout << "For integer: " << intNum << endl;
20. cout << "Square: " << square(intNum) << endl;
21. cout << "Cube: " << cube(intNum) << endl;
22.
23. // Calculate square and cube for float
24. float floatNum = 3.1;
25. cout << "\nFor float: " << floatNum << endl;
26. cout << "Square: " << square(floatNum) << endl;
27. cout << "Cube: " << cube(floatNum) << endl;
28.
29. return 0;
30. }
1. #include <iostream>
2. #include <cstring> // For strlen
3. using namespace std;
4.
5. class Display {
6. public:
7. // Display a string in double quotes
8. void display_str(const char *str) {
9. cout << "\"" << str << "\"" << endl;
10. }
11.
12. // Display first n characters from a given string
13. void display_str(int n, const char *str) {
14. for (int i = 0; i < n && str[i] != '\0'; ++i) {
15. cout << str[i];
16. }
17. cout << endl;
18. }
19.
20. // Display substring of a given string from position m to n
21. void display_str(int m, int n, const char *str) {
22. if (m < 0 || m >= strlen(str) || n < 0 || n >= strlen(str) || m > n) {
23. cout << "Invalid position!" << endl;
24. return;
25. }
26. for (int i = m; i <= n; ++i) {
27. cout << str[i];
28. }
29. cout << endl;
30. }
31. };
32.
33. int main() {
34. Display display;
35.
36. char str[] = "Hello, World!";
37.
38. // Displaying string in double quotes
39. display.display_str(str);
40.
41. // Displaying first 7 characters
42. display.display_str(7, str);
43.
44. // Displaying substring from position 7 to 12
45. display.display_str(7, 12, str);
46.
47. return 0;
48. }
Slip 23:
1. Create a C++ class MyString with data member character pointer. Write a C++ program to
accept and display a string. Overload operator to concatenate two strings.[15 Marks]
1. #include <iostream>
2. #include <cstring> // For strlen, strcpy, strcat
3. using namespace std;
4.
5. class MyString {
6. private:
7. char *str; // Pointer to hold the string
8.
9. public:
10. // Default constructor
11. MyString() : str(NULL) {} // Use NULL instead of nullptr
12.
13. // Parameterized constructor
14. MyString(const char s[]) {
15. str = new char[strlen(s) + 1]; // Allocate memory
16. strcpy(str, s); // Copy the string
17. }
18.
19. // Copy constructor
20. MyString(const MyString &other) {
21. str = new char[strlen(other.str) + 1]; // Allocate memory
22. strcpy(str, other.str); // Copy the string
23. }
24.
25. // Destructor
26. ~MyString() {
27. delete[] str; // Free allocated memory
28. }
29.
30. // Display the string
31. void display() const {
32. if (str) {
33. cout << str << endl;
34. } else {
35. cout << "Empty string" << endl;
36. }
37. }
38.
39. // Overload the + operator for string concatenation
40. MyString operator+(const MyString &ob) {
41. MyString result;
42. result.str = new char[strlen(str) + strlen(ob.str) + 1]; // Allocate memory for
concatenated string
43. strcpy(result.str, str); // Copy the first string
44. strcat(result.str, ob.str); // Concatenate the second string
45. return result; // Return the concatenated string
46. }
47. };
48.
49. int main() {
50. char s1[100], s2[100]; // Increased size for input strings
51. cout << "Enter 1st string: ";
52. cin.getline(s1, 100); // Use getline to allow spaces
53. cout << "Enter 2nd string: ";
54. cin.getline(s2, 100); // Use getline to allow spaces
55.
56. MyString m1(s1), m2(s2), m3; // Create MyString objects
57. cout << "First string: ";
58. m1.display(); // Display first string
59. cout << "Second string: ";
60. m2.display(); // Display second string
61.
62. m3 = m1 + m2; // Concatenate strings
63. cout << "Concatenated string: ";
64. m3.display(); // Display concatenated string
65.
66. return 0;
67. }
2.Create a C++ class Complex Number with data members real and imaginary. Write
necessary functions:
i. To accept Complex Number using constructor.
ii. To display Complex Number in format [x + iy].
iii. To add two Complex Numbers by using friend function.[25 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Complex {
5. private:
6. int real; // Real part
7. int imag; // Imaginary part
8.
9. public:
10. // Constructor to accept complex number
11. Complex(int r = 0, int i = 0) : real(r), imag(i) {}
12.
13. // Function to display complex number in format [x + iy]
14. void display() const {
15. cout << "[" << real << " + " << imag << "i]" << endl;
16. }
17.
18. // Friend function to add two complex numbers
19. friend Complex operator+(const Complex &c1, const Complex &c2);
20. };
21.
22. // Overloaded + operator to add two complex numbers
23. Complex operator+(const Complex &c1, const Complex &c2) {
24. return Complex(c1.real + c2.real, c1.imag + c2.imag);
25. }
26.
27. int main() {
28. int r1, i1, r2, i2;
29.
30. // Input for first complex number
31. cout << "Enter real and imaginary parts of the first complex number: ";
32. cin >> r1 >> i1;
33. Complex c1(r1, i1); // Create first complex number
34.
35. // Input for second complex number
36. cout << "Enter real and imaginary parts of the second complex number: ";
37. cin >> r2 >> i2;
38. Complex c2(r2, i2); // Create second complex number
39.
40. // Display the complex numbers
41. cout << "First complex number: ";
42. c1.display();
43. cout << "Second complex number: ";
44. c2.display();
45.
46. // Add the two complex numbers
47. Complex c3 = c1 + c2; // Use overloaded + operator
48. cout << "Sum of the two complex numbers: ";
49. c3.display();
50.
51. return 0;
52. }
Slip 24:
1.Create a C++ class FixDeposit with data members FD No, Cust Name, FD Amt, Interest rate,
Maturity amt, Number of months. Create and Initialize all values of FixDeposit object by
using parameterized constructor with default value for interest rate. Calculate maturity amt
using interest rate and display all the details.[15 Marks]
1. #include <iostream>
2. #include <cstring> // For strcpy
3. #include <cmath> // For pow
4. using namespace std;
5.
6. class FixDeposit {
7. private:
8. int fdNo; // FD Number
9. char custName[20]; // Customer Name
10. float fdAmt; // FD Amount
11. float interestRate; // Interest Rate
12. float maturityAmt; // Maturity Amount
13. int numMonths; // Number of Months
14.
15. public:
16. // Parameterized constructor with default interest rate
17. FixDeposit(int fNo, const char *name, float amount, int months, float rate = 5.0) {
18. fdNo = fNo;
19. strcpy(custName, name);
20. fdAmt = amount;
21. numMonths = months;
22. interestRate = rate;
23. calculateMaturity(); // Calculate maturity amount during initialization
24. }
25.
26. // Function to calculate maturity amount
27. void calculateMaturity() {
28. double years = numMonths / 12.0;
29. maturityAmt = fdAmt * pow((1 + interestRate / 100), years);
30. }
31.
32. // Function to display all details
33. void display() const {
34. cout << "\nFD No: " << fdNo;
35. cout << "\nCustomer Name: " << custName;
36. cout << "\nFD Amount: " << fdAmt;
37. cout << "\nInterest Rate: " << interestRate << "%";
38. cout << "\nNumber of Months: " << numMonths;
39. cout << "\nMaturity Amount: " << maturityAmt << endl;
40. }
41. };
42.
43. int main() {
44. int fdNo, numMonths;
45. float fdAmt;
46. char custName[20];
47.
48. // Input for Fix Deposit
49. cout << "Enter FD No: ";
50. cin >> fdNo;
51. cout << "Enter Customer Name: ";
52. cin >> custName;
53. cout << "Enter FD Amount: ";
54. cin >> fdAmt;
55. cout << "Enter Number of Months: ";
56. cin >> numMonths;
57.
58. // Create FixDeposit object with default interest rate
59. FixDeposit fd(fdNo, custName, fdAmt, numMonths);
60.
61. // Display the details
62. fd.display();
63.
64. return 0;
65. }
2.Create a C++ class InvoiceBill with data members Order id, O Date, Customer Name, No of
Products, Prod Name[], Quantity[], Prod Price[]. A Customer can buy ‘n’ products. Accept
quantity for each product. Generate and Display the bill using appropriate Manipulators.
(Use new operator) [25 Marks]
1. #include <iostream>
2. #include <iomanip> // For std::setw and std::setprecision
3. #include <string>
4. using namespace std;
5.
6. class InvoiceBill {
7. private:
8. int orderId; // Order ID
9. string customerName; // Customer Name
10. int numberOfProducts; // Number of Products
11. string* productNames; // Dynamic array for product names
12. int* quantities; // Dynamic array for quantities
13. float* prices; // Dynamic array for prices
14.
15. public:
16. // Constructor
17. InvoiceBill() : orderId(0), numberOfProducts(0), productNames(NULL),
quantities(NULL), prices(NULL) {}
18.
19. // Destructor to free allocated memory
20. ~InvoiceBill() {
21. delete[] productNames;
22. delete[] quantities;
23. delete[] prices;
24. }
25.
26. // Function to get data
27. void getData() {
28. cout << "\nEnter Customer Name: ";
29. cin >> customerName;
30. cout << "Enter Order ID: ";
31. cin >> orderId;
32. cout << "Enter Number of Products: ";
33. cin >> numberOfProducts;
34.
35. // Allocate memory for product names, quantities, and prices
36. productNames = new string[numberOfProducts];
37. quantities = new int[numberOfProducts];
38. prices = new float[numberOfProducts];
39.
40. for (int i = 0; i < numberOfProducts; i++) {
41. cout << "\nEnter Product Name: ";
42. cin >> productNames[i];
43. cout << "Enter Quantity: ";
44. cin >> quantities[i];
45. cout << "Enter Price: ";
46. cin >> prices[i];
47. }
48. }
49.
50. // Function to display the invoice
51. void display() const {
52. cout << "\nOrder ID: " << orderId;
53. cout << "\nCustomer Name: " << customerName;
54. cout << "\nNumber of Products: " << numberOfProducts;
55.
56. cout << "\n\nProducts:\n";
57. cout << setw(20) << left << "Product Name"
58. << setw(10) << left << "Quantity"
59. << setw(10) << left << "Price"
60. << setw(10) << left << "Total" << endl;
61.
62. for (int i = 0; i < numberOfProducts; i++) {
63. float total = quantities[i] * prices[i];
64. cout << setw(20) << left << productNames[i]
65. << setw(10) << left << quantities[i]
66. << setw(10) << left << fixed << setprecision(2) << prices[i]
67. << setw(10) << left << total << endl;
68. }
69. }
70.
71. // Function to calculate total amount
72. float calculateTotal() const {
73. float total = 0;
74. for (int i = 0; i < numberOfProducts; i++) {
75. total += quantities[i] * prices[i];
76. }
77. return total;
78. }
79. };
80.
81. int main() {
82. int n; // Number of records
83. cout << "Enter number of records: ";
84. cin >> n;
85.
86. // Create an array of InvoiceBill objects dynamically
87. InvoiceBill* invoices = new InvoiceBill[n];
88.
89. // Get data for each invoice
90. for (int i = 0; i < n; i++) {
91. invoices[i].getData();
92. }
93.
94. // Display each invoice and calculate total
95. for (int i = 0; i < n; i++) {
96. invoices[i].display();
97. float total = invoices[i].calculateTotal();
98. cout << "Total Amount for Order ID " << invoices[i].calculateTotal() << ": " <<
total << endl;
99. }
100.
101. // Free allocated memory
102. delete[] invoices;
103.
104. return 0;
105. }
Slip 25:
1. Write a C++ program to calculate mean, mode and median of three integer numbers.
(Use Inline function)[15 Marks]
1. #include <iostream>
2. #include <algorithm> // For std::sort
3. #include <iomanip> // For std::setprecision
4. using namespace std;
5.
6. // Inline function to calculate the mean
7. inline float calculateMean(int a, int b, int c) {
8. return (a + b + c) / 3.0;
9. }
10.
11. // Inline function to calculate the median
12. inline float calculateMedian(int a, int b, int c) {
13. int arr[3] = {a, b, c};
14. // Sort the array to find the median
15. sort(arr, arr + 3);
16. return arr[1]; // The median is the second element after sorting
17. }
18.
19. // Inline function to calculate the mode
20. inline int calculateMode(int a, int b, int c) {
21. if (a == b && b == c)
22. return a; // All three numbers are the same
23. else if (a == b || a == c)
24. return a; // a is the mode
25. else if (b == c)
26. return b; // b is the mode
27. else
28. return -1; // No mode
29. }
30.
31. int main() {
32. int num1, num2, num3;
33.
34. cout << "Enter three integers: ";
35. cin >> num1 >> num2 >> num3;
36.
37. float mean = calculateMean(num1, num2, num3);
38. float median = calculateMedian(num1, num2, num3);
39. int mode = calculateMode(num1, num2, num3);
40.
41. cout << fixed << setprecision(2); // Set precision for floating-point output
42. cout << "Mean: " << mean << endl;
43. cout << "Median: " << median << endl;
44.
45. if (mode != -1) {
46. cout << "Mode: " << mode << endl;
47. } else {
48. cout << "Mode: No mode" << endl; // Indicate no mode
49. }
50.
51. return 0;
52. }
2. Write a C++ program to read the contents of a “SampleData.txt” file. Create “Upper.txt”
file to store uppercase characters, “Lower.txt” file to store lowercase characters, “Digit.txt”
file to store digits and “Other.txt” file to store remaining characters of a given file.[25 Marks]
1. #include <iostream>
2. #include <fstream>
3. #include <cctype> // For islower, isupper, isdigit
4. using namespace std;
5.
6. int main() {
7. string inputFileName;
8. ifstream fin;
9. ofstream upperFile, lowerFile, digitFile, otherFile;
10.
11. cout << "Enter the name of the input file (e.g., SampleData.txt): ";
12. cin >> inputFileName;
13.
14. // Open the input file
15. fin.open(inputFileName.c_str()); // Use c_str() to convert to C-style string
16. if (!fin) {
17. cout << "Error: File does not exist." << endl;
18. return 1; // Exit with error code
19. }
20.
21. // Open output files
22. upperFile.open("Upper.txt");
23. lowerFile.open("Lower.txt");
24. digitFile.open("Digit.txt");
25. otherFile.open("Other.txt");
26.
27. char ch;
28. // Read characters from the input file
29. while (fin.get(ch)) {
30. if (islower(ch)) {
31. lowerFile.put(ch);
32. } else if (isupper(ch)) {
33. upperFile.put(ch);
34. } else if (isdigit(ch)) {
35. digitFile.put(ch);
36. } else {
37. otherFile.put(ch);
38. }
39. }
40.
41. // Close all files
42. fin.close();
43. upperFile.close();
44. lowerFile.close();
45. digitFile.close();
46. otherFile.close();
47.
48. cout << "Task completed. Files created: Upper.txt, Lower.txt, Digit.txt, Other.txt" <<
endl;
49.
50. return 0;
51. }
Slip 26:
1.Write a C++ program to find average of 3 integer numbers and average of 3 float numbers.
(Use function overloading)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. // Function to calculate the average of three integers
5. int avg(int n1, int n2, int n3) {
6. return (n1 + n2 + n3) / 3;
7. }
8.
9. // Function to calculate the average of three floats
10. float avg(float n1, float n2, float n3) {
11. return (n1 + n2 + n3) / 3.0f; // Use 3.0f to ensure floating-point division
12. }
13.
14. int main() {
15. float fn1, fn2, fn3, favg;
16. int in1, in2, in3, iavg;
17.
18. cout << "Enter three float numbers: ";
19. cin >> fn1 >> fn2 >> fn3;
20.
21. cout << "Enter three integer numbers: ";
22. cin >> in1 >> in2 >> in3;
23.
24. // Calculate averages
25. favg = avg(fn1, fn2, fn3);
26. iavg = avg(in1, in2, in3); // Correctly call the avg function for integers
27.
28. // Display results
29. cout << "\nAverage of float numbers: " << favg << endl;
30. cout << "Average of integer numbers: " << iavg << endl;
31.
32. return 0;
33. }
2.Create a C++ class Time with data members hours, minutes, seconds. Write a C++ program
using operator overloading to perform the following:
!= To check whether two Times are equal or not.
>> To accept the time.
<< To display the time.[25 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. class Time {
5. private:
6. int hours, minutes, seconds;
7.
8. public:
9. // Default constructor
10. Time() : hours(0), minutes(0), seconds(0) {}
11.
12. // Overloading >> operator for input
13. friend istream& operator>>(istream &input, Time &t) {
14. cout << "\nEnter Hours: ";
15. input >> t.hours;
16. cout << "Enter Minutes: ";
17. input >> t.minutes;
18. cout << "Enter Seconds: ";
19. input >> t.seconds;
20.
21. // Normalize time
22. t.minutes += t.seconds / 60;
23. t.seconds %= 60;
24. t.hours += t.minutes / 60;
25. t.minutes %= 60;
26.
27. if (t.hours >= 24) {
28. cout << "Invalid Time: Hours should be less than 24." << endl;
29. t.hours = t.minutes = t.seconds = 0; // Reset to zero on invalid input
30. }
31. return input;
32. }
33.
34. // Overloading << operator for output
35. friend ostream& operator<<(ostream &output, const Time &t) {
36. output << "Hours: " << t.hours << ", Minutes: " << t.minutes << ", Seconds: " <<
t.seconds;
37. return output;
38. }
39.
40. // Overloading == operator for equality check
41. bool operator==(const Time &t1) const {
42. return (hours == t1.hours && minutes == t1.minutes && seconds == t1.seconds);
43. }
44.
45. // Overloading != operator for inequality check
46. bool operator!=(const Time &t1) const {
47. return !(*this == t1); // Use the already defined == operator
48. }
49.
50. // Destructor
51. ~Time() {}
52. };
53.
54. int main() {
55. Time t, t1;
56.
57. cout << "\nEnter First Time";
58. cout << "\n--------------------";
59. cin >> t;
60.
61. cout << "\nFirst Time: " << t;
62.
63. cout << "\n\nEnter Second Time";
64. cout << "\n--------------------";
65. cin >> t1;
66.
67. cout << "\nSecond Time: " << t1;
68.
69. if (t == t1) {
70. cout << "\n\nTimes are Same";
71. } else {
72. cout << "\n\nTimes are Different";
73. }
74.
75. return 0;
76. }
Slip 27:
1.Create a C++ class College, with data members College Id, College Name,
Establishment_year, University Name. Overload operators>> and << to accept and display
College information.[15 Marks]
1. #include <iostream>
2. #include <string> // For std::string
3. using namespace std;
4.
5. class College {
6. private:
7. int id; // College ID
8. int year; // Establishment year
9. string name; // College name
10. string universityName; // University name
11.
12. public:
13. // Default constructor
14. College() : id(0), year(0), name(""), universityName("") {}
15.
16. // Overloading >> operator for input
17. friend istream& operator>>(istream &in, College &c) {
18. cout << "Enter college ID: ";
19. in >> c.id;
20. cout << "Enter college name: ";
21. in.ignore(); // To ignore the newline character left in the buffer
22. getline(in, c.name); // Use getline to allow spaces in the name
23. cout << "Enter year of establishment: ";
24. in >> c.year;
25. cout << "Enter university name: ";
26. in.ignore(); // To ignore the newline character left in the buffer
27. getline(in, c.universityName); // Use getline for university name
28. return in;
29. }
30.
31. // Overloading << operator for output
32. friend ostream& operator<<(ostream &out, const College &c) {
33. out << "\nCollege ID: " << c.id;
34. out << "\nCollege Name: " << c.name;
35. out << "\nEstablishment Year: " << c.year;
36. out << "\nUniversity Name: " << c.universityName << endl;
37. return out;
38. }
39. };
40.
41. int main() {
42. College c1; // Create a College object
43. cin >> c1; // Accept college information
44. cout << "\nThe college details are: \n" << c1; // Display college information
45. return 0;
46. }
2Create a base class Travels with data members T no, Company Name. Derive a class Route
with data members Route id, Source, and Destination from Travels class. Also derive a class
Reservation with data members Number of Seats, Travels Class, Fare, and Travel Date from
Route. Write a C++ program to perform following necessary member functions:
i. Accept details of ‘n’ reservations.
ii. Display details of all reservations.
iii. Display reservation details of a specified Date.[25 Marks]
1. #include <iostream>
2. #include <string>
3. #include <vector>
4. using namespace std;
5.
6. class Travels {
7. protected:
8. int tno; // Travel number
9. string cname; // Company name
10.
11. public:
12. void accept() {
13. cout << "\nEnter Traveling No: ";
14. cin >> tno;
15. cout << "Enter Company Name: ";
16. cin.ignore(); // To ignore the newline character left in the buffer
17. getline(cin, cname); // Use getline to allow spaces in the company name
18. }
19. };
20.
21. class Route : public Travels {
22. protected:
23. int id; // Route ID
24. string source; // Source station
25. string destination; // Destination station
26.
27. public:
28. void acc() {
29. cout << "\nEnter Route ID: ";
30. cin >> id;
31. cout << "Enter Source Station: ";
32. cin.ignore(); // To ignore the newline character left in the buffer
33. getline(cin, source);
34. cout << "Enter Destination Station: ";
35. getline(cin, destination);
36. }
37. };
38.
39. class Reservation : public Route {
40. private:
41. int no_of_seats; // Number of seats
42. float fare; // Fare
43. int dd, mm, yyyy; // Travel date
44. string tclass; // Travel class
45.
46. public:
47. void get() {
48. cout << "\nEnter Number of Seats: ";
49. cin >> no_of_seats;
50. cout << "Enter Travel Class: ";
51. cin.ignore(); // To ignore the newline character left in the buffer
52. getline(cin, tclass);
53. cout << "Enter Date (DD MM YYYY): ";
54. cin >> dd >> mm >> yyyy;
55. }
56.
57. void put() const {
58. cout << "\n\nTravel No: " << tno;
59. cout << "\nCompany Name: " << cname;
60. cout << "\nRoute ID: " << id;
61. cout << "\nRoute Source: " << source;
62. cout << "\nRoute Destination: " << destination;
63. cout << "\nNumber of Seats: " << no_of_seats;
64. cout << "\nTravel Class: " << tclass;
65. cout << "\nTravel Date: " << dd << "/" << mm << "/" << yyyy << endl;
66. }
67.
68. // Function to check if the reservation date matches the specified date
69. bool isDate(int day, int month, int year) const {
70. return (dd == day && mm == month && yyyy == year);
71. }
72. };
73.
74. int main() {
75. int n;
76. vector<Reservation> reservations; // Use vector for dynamic size
77.
78. cout << "\nEnter Number of Records: ";
79. cin >> n;
80.
81. for (int i = 0; i < n; i++) {
82. Reservation r;
83. r.accept();
84. r.acc();
85. r.get();
86. reservations.push_back(r); // Store the reservation
87. }
88.
89. cout << "\nAll Reservations:\n";
90. for (int i = 0; i < reservations.size(); i++) {
91. reservations[i].put();
92. }
93.
94. // Display reservations for a specified date
95. int day, month, year;
96. cout << "\nEnter Date to Display Reservations (DD MM YYYY): ";
97. cin >> day >> month >> year;
98.
99. cout << "\nReservations on " << day << "/" << month << "/" << year << ":\n";
100. bool found = false;
101. for (int i = 0; i < reservations.size(); i++) {
102. if (reservations[i].isDate(day, month, year)) {
103. reservations[i].put();
104. found = true;
105. }
106. }
107.
108. if (!found) {
109. cout << "No reservations found for this date." << endl;
110. }
111.
112. return 0;
113. }
Slip 28:
1. Write a C++ program to read array of ‘n’ integers from user and display it in reverse order.
(Use Dynamic memory allocation)[15 Marks]
1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. int n;
6.
7. cout << "Enter number of array elements: ";
8. cin >> n;
9.
10. // Dynamic memory allocation for an array of n integers
11. int *arr = new int[n];
12.
13. cout << "Enter " << n << " items:\n";
14. for (int i = 0; i < n; i++) {
15. cin >> arr[i];
16. }
17.
18. cout << "\nOriginal array is:\n";
19. for (int i = 0; i < n; i++) {
20. cout << arr[i] << "\t";
21. }
22.
23. cout << "\n\nReverse array is:\n";
24. for (int i = n - 1; i >= 0; i--) {
25. cout << arr[i] << "\t";
26. }
27.
28. // Free the dynamically allocated memory
29. delete[] arr;
30.
31. return 0;
32. }
2.Create a C++ class Employee with data members Emp Id, Emp Name, Mobile No, Salary.
Write necessary member functions for the following:
i. Accept details of n employees
ii. Display employee details in descending order of their salary
iii. Display details of a particular employee.
(Use Array of object and Use appropriate manipulators)[25 Marks]
1. #include <iostream>
2. #include <iomanip>
3. #include <vector>
4. #include <string>
5. #include <algorithm> // For std::sort
6. using namespace std;
7.
8. class Employee {
9. public:
10. int empId;
11. string name;
12. long mobileNo;
13. float salary;
14.
15. void accept() {
16. cout << "\nEnter Employee ID: ";
17. cin >> empId;
18. cout << "Enter Name of Employee: ";
19. cin.ignore(); // To ignore the newline character left in the buffer
20. getline(cin, name);
21. cout << "Enter Mobile No: ";
22. cin >> mobileNo;
23. cout << "Enter Salary: ";
24. cin >> salary;
25. }
26.
27. void display() const {
28. cout << "\nEmployee ID: " << setw(15) << empId
29. << "\nName: " << setw(15) << name
30. << "\nMobile No: " << setw(10) << mobileNo
31. << "\nSalary: " << setw(15) << salary << endl;
32. }
33. };
34.
35. // Comparator function for sorting employees by salary in descending order
36. bool compareSalary(const Employee &e1, const Employee &e2) {
37. return e1.salary > e2.salary; // For descending order
38. }
39.
40. // Function to search for an employee by name
41. void searchEmployee(const vector<Employee> &employees, const string
&searchName) {
42. bool found = false;
43. for (size_t i = 0; i < employees.size(); i++) {
44. if (employees[i].name == searchName) {
45. employees[i].display();
46. found = true;
47. break; // Exit after finding the first match
48. }
49. }
50. if (!found) {
51. cout << "Employee with name '" << searchName << "' not found." << endl;
52. }
53. }
54.
55. int main() {
56. vector<Employee> employees; // Use vector for dynamic size
57. int num;
58. char cont;
59.
60. do {
61. cout << "\n1. Accept Employee Details";
62. cout << "\n2. Display Employees in Descending Order of Salary";
63. cout << "\n3. Search for an Employee by Name";
64. cout << "\nEnter your choice: ";
65. int choice;
66. cin >> choice;
67.
68. switch (choice) {
69. case 1:
70. cout << "\nHow many records do you want to enter? ";
71. cin >> num;
72. for (int i = 0; i < num; i++) {
73. Employee emp;
74. emp.accept();
75. employees.push_back(emp); // Add employee to the vector
76. }
77. break;
78.
79. case 2:
80. // Sort employees by salary
81. sort(employees.begin(), employees.end(), compareSalary);
82. cout << "\nEmployees in Descending Order of Salary:\n";
83. for (size_t i = 0; i < employees.size(); i++) {
84. employees[i].display();
85. }
86. break;
87.
88. case 3:
89. {
90. string searchName;
91. cout << "\nEnter Employee Name to Search: ";
92. cin.ignore(); // To ignore the newline character left in the buffer
93. getline(cin, searchName);
94. searchEmployee(employees, searchName);
95. }
96. break;
97.
98. default:
99. cout << "Invalid choice. Please try again." << endl;
100. break;
101. }
102.
103. cout << "\nDo you want to continue? (Y/N): ";
104. cin >> cont;
105. } while (cont == 'Y' || cont == 'y');
106.
107. return 0;
108. }
Slip 29:
1.Write a C++ program to create a class E Bill with data members Cust Name, Meter ID, No of
Units and Total Charges. Write member functions to accept and display customer
information by calculating charges. (Rules to calculate electricity board charges)
For first 100 units : Rs. 1 per unit
For second 200 units : Rs. 2 per unit
Beyond 300 units : Rs. 5 per unit
All users are charged a minimum of Rs.150. If the total charge is more than Rs.250.00 then
an additional charge of 15% is added.[15 Marks]
1. #include <iostream>
2. #include <string>
3. #include <iomanip> // For std::setprecision
4. using namespace std;
5.
6. class Bill {
7. private:
8. string custName; // Customer Name
9. int meterID; // Meter ID
10. int noOfUnits; // Number of Units
11. float totalCharges; // Total Charges
12.
13. public:
14. void getInput(); // Function to accept customer information
15. void calculateCharges(); // Function to calculate charges
16. void display(); // Function to display customer information
17. };
18.
19. void Bill::getInput() {
20. cout << "\nEnter Meter ID: ";
21. cin >> meterID;
22. cout << "Enter Customer Name: ";
23. cin.ignore(); // To ignore the newline character left in the buffer
24. getline(cin, custName);
25. cout << "Enter Number of Units: ";
26. cin >> noOfUnits;
27. }
28.
29. void Bill::calculateCharges() {
30. totalCharges = 0.0;
31.
32. // Calculate charges based on the number of units
33. if (noOfUnits <= 100) {
34. totalCharges = noOfUnits * 1.0;
35. } else if (noOfUnits <= 300) {
36. totalCharges = 100 * 1.0 + (noOfUnits - 100) * 2.0;
37. } else {
38. totalCharges = 100 * 1.0 + 200 * 2.0 + (noOfUnits - 300) * 5.0;
39. }
40.
41. // Apply minimum charge
42. if (totalCharges < 150) {
43. totalCharges = 150;
44. }
45.
46. // Apply additional charge if total exceeds 250
47. if (totalCharges > 250) {
48. totalCharges += totalCharges * 0.15; // Add 15%
49. }
50. }
51.
52. void Bill::display() {
53. cout << "\nMeter ID: " << meterID;
54. cout << "\nCustomer Name: " << custName;
55. cout << "\nNumber of Units: " << noOfUnits;
56. cout << "\nTotal Charges: " << fixed << setprecision(2) << totalCharges << endl; //
Display with 2 decimal places
57. }
58.
59. int main() {
60. int n;
61. cout << "Enter number of records: ";
62. cin >> n;
63.
64. Bill* bills = new Bill[n]; // Dynamic allocation for n bills
65.
66. for (int i = 0; i < n; i++) {
67. bills[i].getInput();
68. bills[i].calculateCharges();
69. }
70.
71. cout << "\nBill Details:\n";
72. for (int i = 0; i < n; i++) {
73. bills[i].display();
74. }
75.
76. delete[] bills; // Free dynamically allocated memory
77. return 0;
78. }
2.Create a C++ class Visiting Staff with data members Name, No of Subjects, Name of
Subjects[],Working hours, Total Salary. (Number of subjects varies for a Staff).Write a
parameterized constructor to initialize the data members and create an array for Name of
Subjects dynamically. Display Visiting Staff details by calculating salary. (Assume
remuneration Rs. 300 per working hour)[25 Marks]
1. #include <iostream>
2. #include <string>
3. using namespace std;
4.
5. class VisitingStaff {
6. private:
7. string name; // Name of the staff
8. int totalSubjects; // Number of subjects
9. string* subjectNames; // Dynamically allocated array for subject names
10. int workingHours; // Working hours
11.
12. public:
13. // Default constructor
14. VisitingStaff() : name(""), totalSubjects(0), subjectNames(NULL), workingHours(0)
{}
15.
16. // Parameterized constructor
17. VisitingStaff(string staffName, int numSubjects, int hours)
18. : name(staffName), totalSubjects(numSubjects), workingHours(hours) {
19. subjectNames = new string[totalSubjects]; // Dynamic allocation for subject
names
20. }
21.
22. // Destructor to free allocated memory
23. ~VisitingStaff() {
24. delete[] subjectNames;
25. }
26.
27. // Function to set subject names
28. void setSubjectNames() {
29. for (int i = 0; i < totalSubjects; i++) {
30. cout << "Enter subject name " << (i + 1) << ": ";
31. cin >> subjectNames[i];
32. }
33. }
34.
35. // Function to display staff details
36. void display() const {
37. cout << "\nStaff Name: " << name;
38. cout << "\nTotal Subjects: " << totalSubjects;
39. for (int i = 0; i < totalSubjects; i++) {
40. cout << "\nSubject Name " << (i + 1) << ": " << subjectNames[i];
41. }
42. cout << "\nWorking Hours: " << workingHours;
43. }
44.
45. // Function to calculate and display salary
46. void calculateSalary(int rate = 300) const {
47. float salary = workingHours * rate;
48. cout << "\nSalary of Visiting Staff: " << salary << endl;
49. }
50. };
51.
52. int main() {
53. int n;
54. cout << "Enter number of records: ";
55. cin >> n;
56.
57. VisitingStaff* staffArray = new VisitingStaff[n]; // Dynamic allocation for staff array
58.
59. for (int i = 0; i < n; i++) {
60. string name;
61. int totalSubjects, workingHours;
62.
63. cout << "\nEnter name of staff: ";
64. cin >> name;
65. cout << "Enter number of subjects: ";
66. cin >> totalSubjects;
67. cout << "Enter working hours: ";
68. cin >> workingHours;
69.
70. // Create a VisitingStaff object
71. staffArray[i] = VisitingStaff(name, totalSubjects, workingHours);
72. staffArray[i].setSubjectNames(); // Set subject names
73. }
74.
75. cout << "\nVisiting Staff Details:\n";
76. for (int i = 0; i < n; i++) {
77. staffArray[i].display();
78. staffArray[i].calculateSalary();
79. }
80.
81. delete[] staffArray; // Free dynamically allocated memory
82. return 0;
83. }
Slip 30:
1.Write C++ program to create two classes Integer Array and Float Array with an array as a
data member. Write necessary member functions to accept and display array elements of
both the classes. Find and display average of both the array. (Use Friend function)[15
Marks]
1.
2.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 5 subjects. Calculate Total, Grand Total,
Percentage, Grade and use setw(), setprecision()and setfill()to display Marksheet.[25
Marks]
1. #include <iostream>
2. #include <iomanip>
3. #include <string>
4. using namespace std;
5.
6. class Marksheet {
7. private:
8. int seatNo;
9. string studentName;
10. string className;
11. string subjectNames[5];
12. int intMarks[5];
13. int extMarks[5];
14. int totalMarks[5];
15. int grandTotal;
16. float percentage;
17. char grade;
18.
19. public:
20. // Function to accept student information
21. void acceptData() {
22. cout << "Enter Seat No: ";
23. cin >> seatNo;
24. cin.ignore(); // To ignore the newline character after seat number input
25. cout << "Enter Student Name: ";
26. getline(cin, studentName);
27. cout << "Enter Class: ";
28. getline(cin, className);
29.
30. // Accepting data for 5 subjects
31. for (int i = 0; i < 5; i++) {
32. cout << "Enter Subject Name " << (i + 1) << ": ";
33. getline(cin, subjectNames[i]);
34. cout << "Enter Internal Marks for " << subjectNames[i] << ": ";
35. cin >> intMarks[i];
36. cout << "Enter External Marks for " << subjectNames[i] << ": ";
37. cin >> extMarks[i];
38. totalMarks[i] = intMarks[i] + extMarks[i]; // Calculate total for each subject
39. }
40. }
41.
42. // Function to calculate total, grand total, percentage, and grade
43. void calculateResults() {
44. grandTotal = 0;
45. for (int i = 0; i < 5; i++) {
46. grandTotal += totalMarks[i];
47. }
48. percentage = (static_cast<float>(grandTotal) / (5 * 100)) * 100; // Assuming each
subject is out of 100
49.
50. // Determine grade
51. if (percentage >= 70) {
52. grade = 'A'; // Distinction
53. } else if (percentage >= 60) {
54. grade = 'B'; // First Class
55. } else if (percentage >= 50) {
56. grade = 'C'; // Second Class
57. } else if (percentage >= 40) {
58. grade = 'D'; // Pass
59. } else {
60. grade = 'F'; // Fail
61. }
62. }
63.
64. // Function to display the marksheet
65. void displayMarksheet() {
66. cout << "\nMarksheet\n";
67. cout << "----------------------------------------\n";
68. cout << setw(15) << left << "Seat No:" << seatNo << endl;
69. cout << setw(15) << left << "Student Name:" << studentName << endl;
70. cout << setw(15) << left << "Class:" << className << endl;
71. cout << "\nSubject Details:\n";
72. cout << setw(20) << left << "Subject Name"
73. << setw(15) << left << "Int Marks"
74. << setw(15) << left << "Ext Marks"
75. << setw(15) << left << "Total Marks" << endl;
76. cout << "---------------------------------------------------\n";
77.
78. for (int i = 0; i < 5; i++) {
79. cout << setw(20) << left << subjectNames[i]
80. << setw(15) << left << intMarks[i]
81. << setw(15) << left << extMarks[i]
82. << setw(15) << left << totalMarks[i] << endl;
83. }
84.
85. cout << "---------------------------------------------------\n";
86. cout << setw(20) << left << "Grand Total:" << grandTotal << endl;
87. cout << setw(20) << left << "Percentage:" << fixed << setprecision(2) <<
percentage << "%" << endl;
88. cout << setw(20) << left << "Grade:" << grade << endl;
89. }
90. };
91.
92. int main() {
93. Marksheet marksheet;
94. marksheet.acceptData();
95. marksheet.calculateResults();
96. marksheet.displayMarksheet();
97. return 0;
98. }