0% found this document useful (0 votes)
32 views20 pages

include

# include

Uploaded by

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

include

# include

Uploaded by

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

6) #include <iostream>

#include <cstring> // For strcpy, strlen

using namespace std;

class Student {

private:

char *name; // Dynamically allocated memory for name

int age;

float gpa;

static int count; // Static member to track the number of students

public:

// Constructor with dynamic memory allocation

Student(const char *n = "Unknown", int a = 0, float g = 0.0) {

name = new char[strlen(n) + 1]; // Allocate memory for name

strcpy(name, n);

age = a;

gpa = g;

++count; // Increment static student count

cout << "Constructor called for: " << name << endl;

// Destructor to deallocate dynamic memory

~Student() {

cout << "Destructor called for: " << name << endl;

delete[] name; // Free allocated memory

--count;

// Inline function to display student details


inline void display() const {

cout << "Name: " << name << ", Age: " << age << ", GPA: " << gpa << endl;

// Static function to return the current count of students

static int getCount() {

return count;

// Friend function to modify student GPA

friend void updateGPA(Student &s, float newGPA);

};

// Initialize static member

int Student::count = 0;

// Friend function definition to modify the GPA

void updateGPA(Student &s, float newGPA) {

s.gpa = newGPA;

int main() {

// Dynamically allocate memory for a student object

Student *s1 = new Student("Sanika", 19, 9.4);

s1->display(); // Inline function call

// Use friend function to update GPA

updateGPA(*s1, 9.7);

cout << "After GPA update:" << endl;

s1->display();
// Display the count of students (static function)

cout << "Total students: " << Student::getCount() << endl;

// Deallocate memory for the student object

delete s1;

// Display the count after deallocation

cout << "Total students after deletion: " << Student::getCount() << endl;

return 0;

Output-
7) #include <iostream>

using namespace std;

class Complex {

private:

double real;

double imag;

public:

// 1. Constructors

Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} // Default and parameterized


constructor

// 2. Overloaded + operator for adding two complex numbers

Complex operator+(const Complex &other) const {

return Complex(real + other.real, imag + other.imag);

// 3. Overloaded - operator for subtracting two complex numbers

Complex operator-(const Complex &other) const {

return Complex(real - other.real, imag - other.imag);

// 4. Overloaded * operator for multiplying two complex numbers

Complex operator*(const Complex &other) const {

return Complex(real * other.real - imag * other.imag,

real * other.imag + imag * other.real);

// 5. Overloaded / operator for dividing two complex numbers

Complex operator/(const Complex &other) const {


double denominator = other.real * other.real + other.imag * other.imag;

return Complex((real * other.real + imag * other.imag) / denominator,

(imag * other.real - real * other.imag) / denominator);

// 6. Overloaded << operator for printing complex numbers

friend ostream& operator<<(ostream &out, const Complex &c) {

out << c.real << (c.imag >= 0 ? " + " : " - ") << abs(c.imag) << "i";

return out;

// 7. Overloaded >> operator for reading complex numbers

friend istream& operator>>(istream &in, Complex &c) {

cout << "Enter real part: ";

in >> c.real;

cout << "Enter imaginary part: ";

in >> c.imag;

return in;

};

int main() {

Complex c1, c2, result;

// Input two complex numbers

cout << "Enter first complex number:\n";

cin >> c1;

cout << "Enter second complex number:\n";

cin >> c2;

// Demonstrating addition
result = c1 + c2;

cout << "Sum: " << result << endl;

// Demonstrating subtraction

result = c1 - c2;

cout << "Difference: " << result << endl;

// Demonstrating multiplication

result = c1 * c2;

cout << "Product: " << result << endl;

// Demonstrating division

result = c1 / c2;

cout << "Quotient: " << result << endl;

return 0;

Output-
9) // Online C++ compiler to run C++ program online

#include <iostream>

using namespace std;

class Base {

public:

// Virtual function to achieve run-time polymorphism

virtual void show() {

cout << "Base class show function\n";

// Non-virtual function (cannot be overridden)

void display() {

cout << "Base class display function\n";

};

class Derived : public Base {

public:

// Overriding the show function (run-time polymorphism)

void show() override {

cout << "Derived class show function\n";

// New display function hides the base class display

void display() {

cout << "Derived class display function\n";

};

// Function overloading (compile-time polymorphism)


void print(int a) {

cout << "Integer: " << a << endl;

void print(double a) {

cout << "Double: " << a << endl;

void print(const string &a) {

cout << "String: " << a << endl;

// Operator overloading (compile-time polymorphism)

class Complex {

private:

double real, imag;

public:

Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

// Overload + operator

Complex operator+(const Complex &c) const {

return Complex(real + c.real, imag + c.imag);

// Display function

void display() const {

cout << real << " + " << imag << "i" << endl;

};
int main() {

// Demonstrating compile-time polymorphism (function overloading)

print(5);

print(3.14);

print("Hello");

// Demonstrating compile-time polymorphism (operator overloading)

Complex c1(2.3, 4.5), c2(1.2, 3.3);

Complex c3 = c1 + c2;

cout << "Sum of Complex Numbers: ";

c3.display();

// Demonstrating run-time polymorphism (virtual functions)

Base *basePtr;

Derived derivedObj;

basePtr = &derivedObj;

basePtr->show(); // Calls Derived's show (run-time polymorphism)

basePtr->display(); // Calls Base's display (non-virtual, static binding)

return 0;

}
10) #include <iostream>

#include <string>

#include <stdexcept>

using namespace std;

// Custom exception classes for Gmail login

class InvalidEmailException : public runtime_error {

public:

InvalidEmailException() : runtime_error("Invalid email format!") {}

};

class IncorrectPasswordException : public runtime_error {

public:

IncorrectPasswordException() : runtime_error("Incorrect password!") {}

};

// Custom exception class for ATM PIN verification

class IncorrectPinException : public runtime_error {

public:

IncorrectPinException() : runtime_error("Incorrect ATM PIN!") {}

};

// Gmail login function with exception handling

void gmailLogin(const string& email, const string& password) {

if (email.find('@') == string::npos || email.find(".com") == string::npos) {

throw InvalidEmailException();

if (password != "123456") { // Assuming 123456 is the correct password

throw IncorrectPasswordException();
}

cout << "Gmail login successful!" << endl;

// ATM PIN verification function with exception handling

void atmPinVerification(int pin) {

const int correctPin = 1234; // Assuming 1234 is the correct PIN

if (pin != correctPin) {

throw IncorrectPinException();

cout << "ATM PIN verified successfully!" << endl;

int main() {

try {

// Gmail login

string email, password;

cout << "Enter your Gmail email: ";

cin >> email;

cout << "Enter your password: ";

cin >> password;

gmailLogin(email, password);

// ATM PIN verification

int pin;

cout << "\nEnter your ATM PIN: ";

cin >> pin;

atmPinVerification(pin);

}
catch (const InvalidEmailException& e) {

cout << "Error: " << e.what() << endl;

catch (const IncorrectPasswordException& e) {

cout << "Error: " << e.what() << endl;

catch (const IncorrectPinException& e) {

cout << "Error: " << e.what() << endl;

catch (...) {

cout << "An unknown error occurred!" << endl;

return 0;

}
11) #include <iostream>

using namespace std;

const int MAX_SIZE = 100; // Maximum size of the stack

// Class template for stack

template <typename T>

class Stack {

private:

T arr[MAX_SIZE]; // Array to store stack elements

int top; // Index of the top element

public:

// Constructor to initialize the stack

Stack() : top(-1) {}

// Function to push an element onto the stack

void push(T element) {

if (top >= MAX_SIZE - 1) {

cout << "Stack Overflow! Cannot push " << element << endl;

return;

arr[++top] = element;

// Function to pop an element from the stack

T pop() {

if (top < 0) {

cout << "Stack Underflow! Cannot pop element.\n";

return 0; // Returning 0 as a default value (for integer stack)

}
return arr[top--];

// Function to peek the top element of the stack

T peek() {

if (top < 0) {

cout << "Stack is empty.\n";

return 0; // Returning 0 as a default value (for integer stack)

return arr[top];

// Function to check if the stack is empty

bool isEmpty() {

return (top == -1);

// Function to display all elements of the stack

void display() {

if (isEmpty()) {

cout << "Stack is empty.\n";

return;

cout << "Stack elements: ";

for (int i = top; i >= 0; --i) {

cout << arr[i] << " ";

cout << endl;

};
// Main function to demonstrate the stack for integers and characters

int main() {

// Stack of integers

Stack<int> intStack;

cout << "Integer Stack Operations:\n";

intStack.push(10);

intStack.push(20);

intStack.push(30);

intStack.display();

cout << "Popped element: " << intStack.pop() << endl;

intStack.display();

// Stack of characters

Stack<char> charStack;

cout << "\nCharacter Stack Operations:\n";

charStack.push('A');

charStack.push('B');

charStack.push('C');

charStack.display();

cout << "Popped element: " << charStack.pop() << endl;

charStack.display();

return 0;

}
12) #include <iostream>

#include <map>

#include <string>

using namespace std;

// Function to display the currency chart

void displayCurrencyChart(const map<string, string>& currencyMap) {

cout << "------------------------------------\n";

cout << "| Country | Currency |\n";

cout << "------------------------------------\n";

for (const auto& entry : currencyMap) {

cout << "| " << entry.first << " | " << entry.second << " |\n";

cout << "------------------------------------\n";

int main() {

// Creating a map to store country-currency pairs

map<string, string> currencyMap;

// Adding some countries and their currencies

currencyMap["United States"] = "USD - US Dollar";

currencyMap["India"] = "INR - Indian Rupee";

currencyMap["United Kingdom"] = "GBP - British Pound";

currencyMap["Japan"] = "JPY - Japanese Yen";

currencyMap["Canada"] = "CAD - Canadian Dollar";

currencyMap["Australia"] = "AUD - Australian Dollar";

currencyMap["China"] = "CNY - Chinese Yuan";

currencyMap["Germany"] = "EUR - Euro";

currencyMap["Brazil"] = "BRL - Brazilian Real";

currencyMap["South Africa"] = "ZAR - South African Rand";


// Display the currency chart

displayCurrencyChart(currencyMap);

// Search for a specific country’s currency

string searchCountry;

cout << "\nEnter the name of the country to get its currency: ";

getline(cin, searchCountry);

auto it = currencyMap.find(searchCountry);

if (it != currencyMap.end()) {

cout << "Currency of " << searchCountry << " is: " << it->second << endl;

} else {

cout << "Country not found in the chart.\n";

return 0;

}
13) ss#include <iostream>

#include <fstream>

#include <string>

using namespace std;

class Student {

private:

string name;

int id;

public:

Student() : name(""), id(0) {}

Student(string name, int id) : name(name), id(id) {}

void display() const {

cout << "Name: " << name << ", ID: " << id << endl;

void writeToFile(ofstream &out) const {

out << name << endl;

out << id << endl;

void readFromFile(ifstream &in) {

getline(in, name);

in >> id;

in.ignore();

};
int main() {

ofstream outFile("students.txt");

if (!outFile) {

cerr << "Error creating file!" << endl;

return 1;

Student s1("Alice", 101);

Student s2("Bob", 102);

Student s3("Charlie", 103);

s1.writeToFile(outFile);

s2.writeToFile(outFile);

s3.writeToFile(outFile);

outFile.close();

ifstream inFile("students.txt");

if (!inFile) {

cerr << "Error opening file for reading!" << endl;

return 1;

Student students[3];

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

students[i].readFromFile(inFile);

inFile.close();
cout << "Student details from the file:" << endl;

for (const auto &student : students) {

student.display();

return 0;

You might also like