0% found this document useful (0 votes)
21 views52 pages

Exp1 Oop

C++ experiments

Uploaded by

manursami35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views52 pages

Exp1 Oop

C++ experiments

Uploaded by

manursami35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Name: Manur Sami Mujeeb

Class: SY (CSE) C
Roll: 63

Experiment No.1
Q1. Write a program to find size of fundamental datatype?
#include<iostream>
using namespace std;
int main(){
cout<<"Size of integer is:"<<sizeof(int)<<" bytes"<<endl;
cout<<"Size of float is:"<<sizeof(float)<<" bytes"<<endl;
cout<<"Size of double is:"<<sizeof(double)<<" bytes"<<endl;
cout<<"Size of long double is:"<<sizeof(long double)<<" bytes"<<endl;
cout<<"Size of char is:"<<sizeof(char)<<" bytes"<<endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2.Write a program to show the base of numeric value of the variable using hex, oct and dec
manipulator functions.
 #include <iostream>
#include <iomanip>
using namespace std;
int main() {
int number = 255; // Example number
cout << "Number in decimal: " << dec << number << endl;
cout << "Number in hexadecimal: " << hex << number << endl;
cout << "Number in octal: " << oct << number << endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3. Write a program to convert temperature from Celsius to Fahrenheit and Fahrenheit to
Celsius
 #include <iostream>
using namespace std;
int main() {
int choice;
float temp, convertedTemp;
cout << "Temperature Conversion Program\n";
cout << "1. Convert Celsius to Fahrenheit\n";
cout << "2. Convert Fahrenheit to Celsius\n";
cout << "Enter your choice: ";
cin >> choice;
if (choice == 1) {
cout << "Enter temperature in Celsius: ";
cin >> temp;
convertedTemp = (temp * 9 / 5) + 32;
cout << temp << " Celsius is equal to " << convertedTemp << " Fahrenheit." << endl;
}
else if (choice == 2) {
cout << "Enter temperature in Fahrenheit: ";
cin >> temp;
convertedTemp = (temp - 32) * 5 / 9;

cout << temp << " Fahrenheit is equal to " << convertedTemp << " Celsius." << endl;
}
else {
cout << "Invalid choice!" << endl;
}
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.2
Q1. Write a program to display n terms of natural numbers and their sum.
 #include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "Enter the number of terms: ";
cin >> n;
cout << "The first " << n << " natural numbers are: " << endl;
for (int i = 1; i <= n; i++) {
cout << i << " ";
sum += i;
}

cout << "\nThe sum of the first " << n << " natural numbers is: " << sum << endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2. Write a program to read matrix of size m*n using function.
 #include <iostream>
using namespace std;
int main() {
int m, n;
cout << "Enter the number of rows (m): ";
cin >> m;
cout << "Enter the number of columns (n): ";
cin >> n;
int matrix[m][n];
cout << "Enter the elements of the matrix:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << "Element at position [" << i << "][" << j << "]: ";
cin >> matrix[i][j];
}
}
cout << "\nThe matrix is:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}

cout << endl;


}
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3.Write a program to count all the vowels in the given string.
 #include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[100];
int vowelCount = 0;
cout << "Enter a string: ";
cin.getline(str, 100);
for (int i = 0; i < strlen(str); i++) {
char ch = tolower(str[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}
cout << "Total number of vowels in the string: " << vowelCount << endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.3
Q1.Write a program to swap two numbers using call by value and call by reference using class
and object
#include<iostream>
using namespace std;
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "Inside swapByValue function: a = " << a << ", b = " << b << endl;
}
void swapByReference(int &a, int &b) {
int temp = a;

a = b;
b = temp;
cout << "Inside swapByReference function: a = " << a << ", b = " << b << endl;
}
int main() {
int x = 5, y = 10;
cout << "Before swap (Call by Value): x = " << x << ", y = " << y << endl;
swapByValue(x, y);
cout << "After swap (Call by Value): x = " << x << ", y = " << y << endl;
cout << "Before swap (Call by Reference): x = " << x << ", y = " << y << endl;
swapByReference(x, y);
cout << "After swap (Call by Reference): x = " << x << ", y = " << y << endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2.Write a program to calculate square and cube of a number using inline function.
 #include<iostream>
using namespace std;
int square(int num) {
return num * num;
}
int cube(int num) {
return num * num * num;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
cout << "Square of " << number << " is: " << square(number) << endl;
cout << "Cube of " << number << " is: " << cube(number) << endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3.Write a program to find area of rectangle, area of triangle and surface area of sphere
using function overloading.
 #include<iostream>
using namespace std;
double area(double length, double width) {
return length * width;
}
double area(double base, double height, int triangle) {
return 0.5 * base * height;
}
double area(double radius) {
return 4 * 3.1416 * radius * radius;
}
int main() {
double length, width, base, height, radius;
cout << "Enter length and width of the rectangle: ";
cin >> length >> width;
cout << "Area of Rectangle: " << area(length, width) << endl;
cout << "Enter base and height of the triangle: ";
cin >> base >> height;
cout << "Area of Triangle: " << area(base, height, 1) << endl;
cout << "Enter radius of the sphere: ";

cin >> radius;


cout << "Surface Area of Sphere: " << area(radius) << endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.4
Q1.Write a program to implement student class having data members as name, roll number
and PRN number, implement methods to enter details of a single student(data members
must be private)

#include <iostream>

#include <string>
using namespace std;
class Student {
private:
string name;
string roll_number;
string PRN_number;
public:
void enterDetails() {
cout << "Enter student's name: ";
getline(cin, name);
cout << "Enter student's roll number: ";
getline(cin, roll_number);
cout << "Enter student's PRN number: ";
getline(cin, PRN_number);
}
void displayDetails() const {
cout << "Student's Name: " << name << endl;
cout << "Roll Number: " << roll_number << endl;
cout << "PRN Number: " << PRN_number << endl;
}
};
int main() {
Student student;
student.enterDetails();
student.displayDetails();
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2.Write a program to calculate gross salary of an employee using class. Few member
functions must be defined outside the class using scope resolution operator. (Gross
salary=basic+TA+DA, TA=15% of the basic salary, DA=30% of basic salary)

#include <iostream>
using namespace std;
class Employee{
private:
float basicSalary;
float grossSalary;
public:
void setBasicSalary(float basic);
void calculateGrossSalary();
void displayGrossSalary();
};
void Employee::setBasicSalary(float basic){
basicSalary = basic;
}
void Employee::calculateGrossSalary(){
float TA = 0.15 * basicSalary;
float DA = 0.30 * basicSalary;
grossSalary = basicSalary + TA + DA;
}
void Employee::displayGrossSalary(){
cout << "Gross Salary: " << grossSalary << endl;
}
int main(){
float basic;
cout << "Enter Basic Salary: ";
cin >> basic;
Employee emp;
emp.setBasicSalary(basic);
emp.calculateGrossSalary();
emp.displayGrossSalary();
return 0;
}
Output.
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3. WAP to find the number and sum of all integers between 100 and 200 which are divisible
by 9 using friend function.

#include <iostream>
using namespace std;
class DivisibleByNine {
private:
int sum;
int count;
public:
DivisibleByNine() : sum(0), count(0) {}
friend void findDivisible(DivisibleByNine& obj);
void display() const {
cout << "Number of integers divisible by 9 between 100 and 200: " <<
count << endl;
cout << "Sum of integers divisible by 9 between 100 and 200: " << sum <<
endl;
}
};
void findDivisible(DivisibleByNine& obj) {
for (int i = 100; i <= 200; i++) {
if (i % 9 == 0) {
obj.count++;
obj.sum += i;
}
}
}
int main() {
DivisibleByNine obj;
findDivisible(obj);
obj.display();
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.5
Q1.Write a Program to display square and cube of a number using default constructor.

#include <iostream>
using namespace std;
class Number {
private:
int num;
public:
Number() {
num = 0;
}
void setNumber(int n) {
num = n;
}
void displaySquareAndCube() {
cout << "Square of " << num << " is: " << num * num << endl;
cout << "Cube of " << num << " is: " << num * num * num << endl;
}
};
int main() {
Number n;
int value;
cout << "Enter a number: ";
cin >> value;
n.setNumber(value);
n.displaySquareAndCube();
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2. Write a program to implement details of student having data members as roll no. , name,
PRN, and total marks using parameterized constructor. Implement methods to calculate
result/percentage.

#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int rollNo;
string name;
string PRN;
float totalMarks;
float percentage;
public:
Student(int r, string n, string p, float marks) {
rollNo = r;
name = n;
PRN = p;
totalMarks = marks;
percentage = 0.0;
}
void calculatePercentage() {
percentage = (totalMarks / 500) * 100;
}
void displayDetails() {
cout << "Student Details:" << endl;
cout << "Roll No.: " << rollNo << endl;
cout << "Name: " << name << endl;
cout << "PRN: " << PRN << endl;
cout << "Total Marks: " << totalMarks << endl;
cout << "Percentage: " << percentage << "%" << endl;
}
};
int main() {
int roll;
string name, prn;
float marks;
cout << "Enter Roll No.: ";
cin >> roll;
cout << "Enter Name: ";
cin.ignore();
getline(cin, name);
cout << "Enter PRN: ";
cin >> prn;
cout << "Enter Total Marks (out of 500): ";
cin >> marks;
Student student(roll, name, prn, marks);
student.calculatePercentage();
student.displayDetails();
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3. Write a program to create Book class having data members as Book name, author name,
price and ISBN. Implement details of a book. Use copy constructor to copy the details of book
from one object to other.

#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string bookName;
string authorName;
float price;
string ISBN;
public:
Book(string bName, string aName, float p, string isbn) {
bookName = bName;
authorName = aName;
price = p;
ISBN = isbn;
}
Book(const Book &obj) {
bookName = obj.bookName;
authorName = obj.authorName;
price = obj.price;
ISBN = obj.ISBN;
}
void displayDetails() {
cout << "Book Name: " << bookName << endl;
cout << "Author Name: " << authorName << endl;
cout << "Price: $" << price << endl;
cout << "ISBN: " << ISBN << endl;
}
};
int main() {
Book book1("The C++ Programming Language", "Bjarne Stroustrup", 45.99, "978-
0321563842");
cout << "Details of Book 1:" << endl;
book1.displayDetails();
Book book2 = book1;
cout << "\nDetails of Book 2 (Copied from Book 1):" << endl;
book2.displayDetails();
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.6
Q1.write a program to implement constructor overloading for employee class having data
members emp_id, name, designation and salary release the object using destructor.

#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
int emp_id;
string name;
string designation;
float salary;
public:
Employee() {
emp_id = 0;
name = "Not assigned";
designation = "Not assigned";
salary = 0.0;
cout << "Default constructor called!" << endl;
}
Employee(int id, string empName) {
emp_id = id;
name = empName;
designation = "Not assigned";
salary = 0.0;
cout << "Constructor with emp_id and name called!" << endl;
}
Employee(int id, string empName, string empDesignation, float empSalary) {
emp_id = id;
name = empName;
designation = empDesignation;
salary = empSalary;
cout << "Constructor with all details called!" << endl;
}
void displayDetails() {
cout << "Employee ID: " << emp_id << endl;
cout << "Name: " << name << endl;
cout << "Designation: " << designation << endl;
cout << "Salary: $" << salary << endl;
}
~Employee() {
cout << "Destructor called for Employee ID: " << emp_id << endl;
}
};
int main() {
Employee emp1; // Using default constructor
cout << "\nDetails of Employee 1:" << endl;
emp1.displayDetails();
Employee emp2(101, "John Doe");
cout << "\nDetails of Employee 2:" << endl;
emp2.displayDetails();
Employee emp3(102, "Alice Smith", "Software Engineer", 75000);
cout << "\nDetails of Employee 3:" << endl;
emp3.displayDetails();
return 0;
}

Output
Q2.Write a program to overload unary and binary operator.

#include <iostream>
using namespace std;
class OperatorOverload {
private:
int value;
public:
OperatorOverload(int v = 0) {
value = v;
}
OperatorOverload operator-() {
return OperatorOverload(-value);
}
OperatorOverload operator+(const OperatorOverload &obj) {
return OperatorOverload(value + obj.value);
}
void display() const {
cout << "Value: " << value << endl;
}
};
int main() {
OperatorOverload obj1(10);
OperatorOverload obj2(20);
cout << "Initial values:" << endl;
obj1.display();
obj2.display();
OperatorOverload negObj = -obj1;
cout << "\nAfter unary '-' operator on obj1:" << endl;
negObj.display();
OperatorOverload sumObj = obj1 + obj2;
cout << "\nAfter binary '+' operator on obj1 and obj2:" << endl;
sumObj.display();
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.7
Q1.write a program to read and print student information using two classes and simple
inheritance.

#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
public:
void getPersonalDetails() {
cout << "Enter name: ";
getline(cin, name);
cout << "Enter age: ";
cin >> age;
cin.ignore();
}
void displayPersonalDetails() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class Student : public Person {
private:
int rollNo;
string course;
public:
void getStudentDetails() {
getPersonalDetails();
cout << "Enter Roll No.: ";
cin >> rollNo;
cin.ignore();
cout << "Enter Course: ";
getline(cin, course);
}
void displayStudentDetails() {
displayPersonalDetails();
cout << "Roll No.: " << rollNo << endl;
cout << "Course: " << course << endl;
}
};
int main() {
Student student;
cout << "Enter student information:" << endl;
student.getStudentDetails();
cout << "\nStudent Information:" << endl;
student.displayStudentDetails();
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2. Write a program to read and print employee information using multiple inheritance and
multilevel inheritance
1) Multiple Inheritance

#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
public:
void getPersonalDetails() {
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Age: ";
cin >> age;
cin.ignore();
}
void displayPersonalDetails() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class JobDetails {
protected:
string jobTitle;
float salary;
public:
void getJobDetails() {
cout << "Enter Job Title: ";
getline(cin, jobTitle);
cout << "Enter Salary: ";
cin >> salary;
cin.ignore();
}
void displayJobDetails() {
cout << "Job Title: " << jobTitle << endl;
cout << "Salary: $" << salary << endl;
}
};
class Employee : public Person, public JobDetails {
private:
int empID;
public:
void getEmployeeDetails() {
getPersonalDetails();
getJobDetails();
cout << "Enter Employee ID: ";
cin >> empID;
cin.ignore();
}
void displayEmployeeDetails() {
displayPersonalDetails();
displayJobDetails();
cout << "Employee ID: " << empID << endl;
}
};
int main() {
Employee emp;
cout << "Enter Employee Information:" << endl;
emp.getEmployeeDetails();
cout << "\nEmployee Information:" << endl;
emp.displayEmployeeDetails();
return 0;
}

Output
2) Multilevel Inheritance

#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
public:
void getPersonalDetails() {
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Age: ";
cin >> age;
cin.ignore();
}
void displayPersonalDetails() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class EmployeeBase : public Person {
protected:
int empID;
public:
void getEmployeeID() {
cout << "Enter Employee ID: ";
cin >> empID;
cin.ignore();
}
void displayEmployeeID() {
cout << "Employee ID: " << empID << endl;
}
};
class Employee : public EmployeeBase {
private:
string jobTitle;
float salary;
public:
void getJobDetails() {
getPersonalDetails();
getEmployeeID();
cout << "Enter Job Title: ";
getline(cin, jobTitle);
cout << "Enter Salary: ";
cin >> salary;
cin.ignore();
}
void displayJobDetails() {
displayPersonalDetails();
displayEmployeeID();
cout << "Job Title: " << jobTitle << endl;
cout << "Salary: $" << salary << endl;
}
};
int main() {
Employee emp;
cout << "Enter Employee Information:" << endl;
emp.getJobDetails();
cout << "\nEmployee Information:" << endl;
emp.displayJobDetails();
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3 Write a program to implement hybrid and hierarchical implementation.
1) Hybrid Inheritance

#include <iostream>
using namespace std;
class A {
public:
void showA() {
cout << "This is class A" << endl;
}
};
class B {
public:
void showB() {
cout << "This is class B" << endl;
}
};
class C : public A, public B {
public:
void showC() {
cout << "This is class C" << endl;
}
};
class D : public C {
public:
void showD() {
cout << "This is class D" << endl;
}
};
int main() {
D obj;
obj.showA();
obj.showB();
obj.showC();
obj.showD();
return 0;
}
Output

2) Hierarchical Inheritance
#include <iostream>
using namespace std;
class A {
public:
void showA() {
cout << "This is class A" << endl;
}
};
class B : public A {
public:
void showB() {
cout << "This is class B" << endl;
}
};
class C : public A {
public:
void showC() {
cout << "This is class C" << endl;
}
};
int main() {
B objB;
C objC;
objB.showA();
objB.showB();
objC.showA();
objC.showC();
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.8
Q1. Write a program to display reverse of number using virtual base class.

#include <iostream>
using namespace std;
class Number {
protected:
int num;
public:
Number(int n) : num(n) {}
virtual void reverseNumber() = 0;
};
class Reverse : public virtual Number {
public:
Reverse(int n) : Number(n) {}
void reverseNumber() override {
int rev = 0, remainder;
int temp = num;
while (temp != 0) {
remainder = temp % 10;
rev = rev * 10 + remainder;
temp /= 10;
}
cout << "Reversed Number: " << rev << endl;
}
};
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
Reverse obj(n);
obj.reverseNumber();

return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2.Write a program to implement concept of function overriding.

#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animals make sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
class Cow : public Animal {
public:
void sound() override {
cout << "Cow moos" << endl;
}
};
int main() {
Animal *animal;
Dog dog;
Cat cat;
Cow cow;
animal = &dog;
animal->sound();
animal = &cat;
animal->sound();
animal = &cow;
animal->sound();
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3.Write a program to implement virtual function.

#include <iostream>
using namespace std;
class Shape {
public:
virtual void display() {
cout << "This is a generic shape." << endl;
}
};

class Circle : public Shape {


public:
void display() override {
cout << "This is a circle." << endl;
}
};
class Square : public Shape {
public:
void display() override {
cout << "This is a square." << endl;
}
};
int main() {
Shape* shapePtr;
Circle circle;
Square square;
shapePtr = &circle;
shapePtr->display();
shapePtr = &square;
shapePtr->display();
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.9
Q1. Write a program to open a file for writing and reading purpose use open function () in c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream file;
string content;
file.open("example.txt", ios::out | ios::in | ios::trunc);
if (!file) {
cout << "Error: File could not be opened!" << endl;
return 1;
}
file << "Hello, this is a test file." << endl;
file.seekg(0);
getline(file, content);
cout << "Content of the file: " << content << endl;
file.close();
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2. Write a program to write text in a file, read the text from file from EOF(). Display the
content in reverse order.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Write text to a file
ofstream outfile("example.txt");
outfile << "This is an example of reversing text from a file.";
outfile.close();
ifstream infile("example.txt");
string content, line;
while (getline(infile, line)) {
content += line;
}
infile.close();
for (int i = 0, j = content.length() - 1; i < j; i++, j--) {
swap(content[i], content[j]);
}
cout << "Reversed Content: " << content << endl;
return 0;
}

Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63

Experiment No.10
Q1. Write a program to demonstrate that the data is read from file using ASCII format

#include <iostream>
#include <fstream>
#include <bitset>
using namespace std;
int main() {
ofstream outfile("example.txt");
outfile << "Hello, ASCII!";
outfile.close();
ifstream infile("example.txt");
char ch;
cout << "Character - ASCII Code - Binary Representation" << endl;
while (infile.get(ch)) {
int asciiValue = static_cast<int>(ch);
cout << ch << " - " << asciiValue << " - " <<
bitset<8>(asciiValue) << endl;
}
infile.close();
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q2. Write a program to find the factorial of a number throw multiple exception and define
multiple catch statement to handle exception.

#include <iostream>
using namespace std;
long factorial(int n) {
if (n < 0) {
throw invalid_argument("Factorial is not defined for negative numbers.");
}
if (n > 20) {
throw overflow_error("Input is too large; may cause overflow.");
}
long long result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
int main() {
int num;
cout << "Enter a number to find its factorial: ";
cin >> num;
try {
long long result = factorial(num);
cout << "Factorial of " << num << " is: " << result << endl;
}
catch (const invalid_argument& e) {
cout << "Error: " << e.what() << endl;
}
catch (const overflow_error& e) {
cout << "Error: " << e.what() << endl;
}
catch (...) {
cout << "An unknown error occurred." << endl;
}
return 0;
}
Output
Name: Manur Sami Mujeeb
Class: SY (CSE) C
Roll: 63
Q3. Write a program to illustrate template class.

#include <iostream>
using namespace std;
template <typename T>
class Calculator {
T num1, num2;
public:
Calculator(T n1, T n2) : num1(n1), num2(n2) {}
T add() {
return num1 + num2;
}
T subtract() {
return num1 - num2;
}
T multiply() {
return num1 * num2;
}
T divide() {
if (num2 != 0)
return num1 / num2;
else {
cout << "Error: Division by zero!" << endl;
return 0;
}
}
};
int main() {
Calculator<int> intCalc(10, 5);
cout << "Integer Calculations:" << endl;
cout << "10 + 5 = " << intCalc.add() << endl;
cout << "10 - 5 = " << intCalc.subtract() << endl;
cout << "10 * 5 = " << intCalc.multiply() << endl;
cout << "10 / 5 = " << intCalc.divide() << endl;
Calculator<double> doubleCalc(5.5, 2.2);
cout << "\nDouble Calculations:" << endl;
cout << "5.5 + 2.2 = " << doubleCalc.add() << endl;
cout << "5.5 - 2.2 = " << doubleCalc.subtract() << endl;
cout << "5.5 * 2.2 = " << doubleCalc.multiply() << endl;
cout << "5.5 / 2.2 = " << doubleCalc.divide() << endl;
return 0;
}

Output

You might also like