0% found this document useful (0 votes)
5 views24 pages

C++ Class Examples: Area, Banking, Employee

The document contains multiple C++ programming examples demonstrating various concepts such as function overloading, operator overloading, inheritance, and template functions. Key examples include calculating areas of different shapes, managing complex numbers, creating a simple banking system, and implementing a vehicle hierarchy with multiple inheritance. Each example is self-contained with a main function to execute and display results.

Uploaded by

swethakousi1996
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)
5 views24 pages

C++ Class Examples: Area, Banking, Employee

The document contains multiple C++ programming examples demonstrating various concepts such as function overloading, operator overloading, inheritance, and template functions. Key examples include calculating areas of different shapes, managing complex numbers, creating a simple banking system, and implementing a vehicle hierarchy with multiple inheritance. Each example is self-contained with a main function to execute and display results.

Uploaded by

swethakousi1996
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

Set B lab

[Link] overloading to calculate the area.


#include <iostream.h> // For older compilers, include .h header
#include <conio.h> // For getch() function

#define PI 3.141592653589793

class AreaCalculator {
public:
// Function to calculate the area of a square
double calculateArea(double side) {
return side * side;
}

// Function to calculate the area of a rectangle


double calculateArea(double length, double width) {
return length * width;
}

// Function to calculate the area of a circle


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

// Function to calculate the area of a triangle


double calculateArea(double base, double height) {
return 0.5 * base * height;
}
};

int main() {
clrscr(); // Clear the screen

AreaCalculator calculator;

// Calculate and display the area of a square


cout << "Area of square: " << [Link](5.0) << endl;

// Calculate and display the area of a rectangle


cout << "Area of rectangle: " << [Link](4.0, 6.0) << endl;

// Calculate and display the area of a circle


cout << "Area of circle: " << [Link](3.0) << endl;

// Calculate and display the area of a triangle


cout << "Area of triangle: " << [Link](4.0, 7.0) << endl;

getch(); // Wait for a key press before exiting


return 0;
}
[Link] operator overloading in complex number Addition and Multiplication.
#include <iostream.h>

class Complex {
private:
double real;
double imaginary;

public:
// Constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imaginary(i) {}

// Overload the + operator for complex number addition


Complex operator+(const Complex& other) const {
return Complex(real + [Link], imaginary + [Link]);
}

// Overload the * operator for complex number multiplication


Complex operator*(const Complex& other) const {
return Complex(
real * [Link] - imaginary * [Link],
real * [Link] + imaginary * [Link]
);
}

// Display the complex number


void display() const {
cout << real << " + " << imaginary << "i" << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create two complex numbers


Complex c1(2.0, 3.0);
Complex c2(1.0, -2.0);

// Display the original complex numbers


cout << "Complex Number 1: ";
[Link]();

cout << "Complex Number 2: ";


[Link]();

// Perform addition and display the result


Complex sum = c1 + c2;
cout << "\nSum (Addition): ";
[Link]();

// Perform multiplication and display the result


Complex product = c1 * c2;
cout << "Product (Multiplication): ";
[Link]();

getch(); // Wait for a key press before exiting


return 0;
}
[Link] banking system.
#include <iostream.h>
#include <conio.h>
#include <string.h>

class BankAccount {
private:
char accountNumber[20];
char accountHolderName[50];
double balance;

public:
// Constructor
BankAccount(const char* accNum, const char* accHolder, double initialBalance) {
strcpy(accountNumber, accNum);
strcpy(accountHolderName, accHolder);
balance = initialBalance;
}

// Deposit funds into the account


void deposit(double amount) {
balance += amount;
cout << "Deposit successful. New balance: $" << balance << endl;
}

// Withdraw funds from the account


void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
cout << "Withdrawal successful. New balance: $" << balance << endl;
} else {
cout << "Insufficient funds. Withdrawal failed." << endl;
}
}

// Get the account balance


double getBalance() const {
return balance;
}

// Display account information


void display() const {
cout << "Account Number: " << accountNumber << endl;
cout << "Account Holder: " << accountHolderName << endl;
cout << "Balance: $" << balance << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create Gokul's account


BankAccount gokulAccount("987654", "Gokul", 1500.0);

// Display Gokul's account information


cout << "Gokul's Account Information:" << endl;
[Link]();
cout << "------------------------" << endl;

// Perform transactions on Gokul's account


[Link](500.0);
[Link](200.0);
cout << "Gokul's Account Balance: $" << [Link]() << endl;

getch(); // Wait for a key press before exiting


return 0;
}
[Link] class-copy constructor.
#include <iostream.h>
#include <conio.h>
#include <string.h>

class Student {
private:
char* name;
int age;

public:
// Constructor
Student(const char* studentName, int studentAge) : age(studentAge) {
// Allocate memory for the name and copy it
name = new char[strlen(studentName) + 1];
strcpy(name, studentName);
}

// Copy constructor
Student(const Student& other) : age([Link]) {
// Allocate memory for the name and copy it
name = new char[strlen([Link]) + 1];
strcpy(name, [Link]);
}

// Destructor
~Student() {
delete[] name;
}

// Display student information


void display() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create a student named Gokul


Student originalStudent("Gokul", 22);

// Use the copy constructor to create another student


Student copiedStudent = originalStudent;

// Display information for both students


cout << "Original Student:" << endl;
[Link]();

cout << "\nCopied Student:" << endl;


[Link]();

getch(); // Wait for a key press before exiting


return 0;
}
[Link] records in an organization. Overload << ,+,>operators.
#include <iostream.h>
#include <conio.h>
#include <string.h>

class Employee {
private:
char* name;
int employeeId;
double salary;

public:
// Constructor
Employee(const char* employeeName, int id, double initialSalary) : employeeId(id),
salary(initialSalary) {
// Allocate memory for the name and copy it
name = new char[strlen(employeeName) + 1];
strcpy(name, employeeName);
}

// Destructor
~Employee() {
delete[] name;
}

// Overload the << operator for output


friend ostream& operator<<(ostream& os, const Employee& employee) {
os << "Employee ID: " << [Link] << ", Name: " << [Link] << ", Salary: $"
<< [Link];
return os;
}

// Overload the + operator for salary addition


Employee operator+(double amount) const {
Employee newEmployee(*this); // Create a copy of the current employee
[Link] += amount;
return newEmployee;
}

// Overload the > operator for salary comparison


bool operator>(const Employee& other) const {
return salary > [Link];
}
};

int main() {
clrscr(); // Clear the screen

// Create an employee named Gokul


Employee gokul("Gokul", 101, 50000.0);

// Display Gokul's information


cout << "Employee Information:" << endl;
cout << gokul << endl;

// Perform salary addition


Employee newGokul = gokul + 2000.0;
cout << "\nAfter Salary Addition:" << endl;
cout << newGokul << endl;

// Compare salaries
Employee ram("Ram", 102, 55000.0);
if (gokul > ram) {
cout << "\nGokul has a higher salary than Ram." << endl;
} else {
cout << "\nGokul does not have a higher salary than Ram." << endl;
}

getch(); // Wait for a key press before exiting


return 0;
}
[Link] class -Payroll calculation.
#include <iostream.h>
#include <conio.h>
#include <string.h>

class Employee {
private:
char* name;
int employeeId;
double hourlyRate;
int hoursWorked;

public:
// Constructor
Employee(const char* employeeName, int id, double rate) : employeeId(id), hourlyRate(rate),
hoursWorked(0) {
// Allocate memory for the name and copy it
name = new char[strlen(employeeName) + 1];
strcpy(name, employeeName);
}

// Destructor
~Employee() {
delete[] name;
}

// Record hours worked


void recordHours(int hours) {
hoursWorked += hours;
}

// Calculate payroll
double calculatePayroll() const {
return hourlyRate * hoursWorked;
}

// Overload the << operator for output


friend ostream& operator<<(ostream& os, const Employee& employee) {
os << "Employee ID: " << [Link] << ", Name: " << [Link]
<< ", Hourly Rate: $" << [Link] << ", Hours Worked: " << [Link];
return os;
}
};

int main() {
clrscr(); // Clear the screen

// Create an employee named Gokul


Employee gokul("Gokul", 101, 15.0);

// Record hours worked


[Link](40); // Gokul worked 40 hours

// Display Gokul's information


cout << "Employee Information:" << endl;
cout << gokul << endl;

// Calculate and display payroll for Gokul


cout << "\nPayroll for Gokul: $" << [Link]() << endl;
getch(); // Wait for a key press before exiting
return 0;
}

[Link] Account-Inheritance.
#include <iostream.h>
#include <conio.h>
#include <string.h>

class BankAccount {
private:
char* accountHolder;
double balance;

public:
// Constructor
BankAccount(const char* holder, double initialBalance) : balance(initialBalance) {
// Allocate memory for the account holder's name and copy it
accountHolder = new char[strlen(holder) + 1];
strcpy(accountHolder, holder);
}

// Destructor
~BankAccount() {
delete[] accountHolder;
}

// Display account information


void display() const {
cout << "Account Holder: " << accountHolder << ", Balance: $" << balance << endl;
}
};

class SavingsAccount : public BankAccount {


private:
double interestRate;

public:
// Constructor
SavingsAccount(const char* holder, double initialBalance, double rate) : BankAccount(holder,
initialBalance), interestRate(rate) {}

// Calculate interest
double calculateInterest() const {
return getBalance() * interestRate / 100;
}

// Display account information including interest


void displayWithInterest() const {
display();
cout << "Interest Rate: " << interestRate << "%, Interest: $" << calculateInterest() << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create a savings account for Gokul


SavingsAccount gokulAccount("Gokul", 1000.0, 5.0);

// Display Gokul's account information


cout << "Savings Account Information for Gokul:" << endl;
[Link]();

getch(); // Wait for a key press before exiting


return 0;
}
[Link] hierarchy -Multiple inheritance.
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Base class representing an engine


class Engine {
protected:
int horsepower;

public:
Engine(int power) : horsepower(power) {}

void displayEngine() const {


cout << "Horsepower: " << horsepower << " HP" << endl;
}
};

// Base class representing a vehicle


class Vehicle {
protected:
char* brand;

public:
Vehicle(const char* vehicleBrand) {
// Allocate memory for the brand and copy it
brand = new char[strlen(vehicleBrand) + 1];
strcpy(brand, vehicleBrand);
}

virtual ~Vehicle() { // Virtual destructor for polymorphism


delete[] brand;
}

void displayVehicle() const {


cout << "Brand: " << brand << endl;
}
};

// Derived class representing a car


class Car : public Vehicle, public Engine {
private:
int numDoors;

public:
Car(const char* carBrand, int power, int doors) : Vehicle(carBrand), Engine(power), numDoors(doors)
{}

void displayCar() const {


displayVehicle();
displayEngine();
cout << "Number of Doors: " << numDoors << endl;
}
};

// Derived class representing a bike


class Bike : public Vehicle, public Engine {
private:
bool hasBasket;

public:
Bike(const char* bikeBrand, int power, bool basket) : Vehicle(bikeBrand), Engine(power),
hasBasket(basket) {}

void displayBike() const {


displayVehicle();
displayEngine();
cout << "Has Basket: " << (hasBasket ? "Yes" : "No") << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create a car
Car myCar("Toyota", 200, 4);

// Create a bike
Bike myBike("Honda", 50, true);

// Display information for the car and bike


cout << "Car Information:" << endl;
[Link]();

cout << "\nBike Information:" << endl;


[Link]();

getch(); // Wait for a key press before exiting


return 0;
}
[Link] overloading and inheritance- library's collection of books.
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Base class representing a Book


class Book {
protected:
char* title;
char* author;
int yearPublished;

public:
// Constructor with parameters
Book(const char* bookTitle, const char* bookAuthor, int publishedYear)
: yearPublished(publishedYear) {
// Allocate memory for the title and author and copy them
title = new char[strlen(bookTitle) + 1];
strcpy(title, bookTitle);

author = new char[strlen(bookAuthor) + 1];


strcpy(author, bookAuthor);
}

// Destructor
~Book() {
delete[] title;
delete[] author;
}

// Display book information


void displayBook() const {
cout << "Title: " << title << ", Author: " << author << ", Year Published: " << yearPublished << endl;
}
};

// Derived class representing a ReferenceBook


class ReferenceBook : public Book {
private:
char* topic;

public:
// Constructor with parameters, calling base class constructor
ReferenceBook(const char* bookTitle, const char* bookAuthor, int publishedYear, const char*
bookTopic)
: Book(bookTitle, bookAuthor, publishedYear) {
// Allocate memory for the topic and copy it
topic = new char[strlen(bookTopic) + 1];
strcpy(topic, bookTopic);
}
// Destructor
~ReferenceBook() {
delete[] topic;
}

// Display reference book information


void displayReferenceBook() const {
displayBook();
cout << "Topic: " << topic << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create a regular book


Book regularBook("The Catcher in the Rye", "J.D. Salinger", 1951);

// Create a reference book


ReferenceBook referenceBook("Encyclopedia of Science", "Various Authors", 2000, "Science");

// Display information for both books


cout << "Regular Book Information:" << endl;
[Link]();

cout << "\nReference Book Information:" << endl;


[Link]();

getch(); // Wait for a key press before exiting


return 0;
}
[Link] function -Maximum amount of 3 values.
#include <iostream.h>
#include <conio.h>

// Template function to find the maximum among three values


template <typename T>
T findMax(T a, T b, T c) {
T maxVal = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
return maxVal;
}

// Overload the template function for char


char findMax(char a, char b, char c) {
char maxVal = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
return maxVal;
}

int main() {
clrscr(); // Clear the screen

// Example with integers


int intResult = findMax(10, 5, 8);
cout << "Maximum Integer Value: " << intResult << endl;

// Example with floating-point numbers


float floatResult = findMax(3.14, 2.5, 4.2);
cout << "Maximum Float Value: " << floatResult << endl;

// Example with characters


char charResult = findMax('a', 'b', 'c');
cout << "Maximum Char Value: " << charResult << endl;

getch(); // Wait for a key press before exiting


return 0;
}
11.C++ program to find the sum and average arrays.
#include <iostream.h>
#include <conio.h>

int main() {
// Declare an array
const int size = 5; // Change the size as needed
int numbers[size];

// Input elements into the array


clrscr(); // Clear the screen
cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; ++i) {
cout << "Enter element " << i + 1 << ": ";
cin >> numbers[i];
}

// Calculate the sum


int sum = 0;
for (int i = 0; i < size; ++i) {
sum += numbers[i];
}

// Calculate the average


double average = static_cast<double>(sum) / size;

// Display the sum and average


cout << "Sum: " << sum << endl;
cout << "Average: " << average << endl;

getch(); // Wait for a key press before exiting


return 0;
}

[Link] Functions -addition.


#include <iostream.h>
#include <conio.h>
#include <string.h>
// Function to add two integers
int add(int a, int b) {
return a + b;
}

// Function to add two double values


double add(double a, double b) {
return a + b;
}

// Function to concatenate two strings


char* add(const char* str1, const char* str2) {
char* result = new char[strlen(str1) + strlen(str2) + 1];
strcpy(result, str1);
strcat(result, str2);
return result;
}

int main() {
clrscr(); // Clear the screen

// Add two integers


int resultInt = add(5, 10);
cout << "Sum of integers: " << resultInt << endl;

// Add two double values


double resultDouble = add(3.14, 2.5);
cout << "Sum of doubles: " << resultDouble << endl;

// Concatenate two strings


const char* str1 = "Hello, ";
const char* str2 = "World!";
char* resultString = add(str1, str2);
cout << "Concatenated String: " << resultString << endl;
delete[] resultString; // Free the memory

getch(); // Wait for a key press before exiting


return 0;
}
[Link]- bubble sort .
#include <iostream.h>
#include <conio.h>

// Template function to perform Bubble Sort for any type


template <typename T>
void bubbleSort(T arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
// Swap if the element found is greater than the next element
if (arr[j] > arr[j + 1]) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Template function to display an array for any type


template <typename T>
void displayArray(T arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
clrscr(); // Clear the screen

const int sizeInt = 8;


int numbersInt[sizeInt] = {64, 25, 12, 22, 11, 1, 90, 88};

cout << "Original Int Array: ";


displayArray(numbersInt, sizeInt);

// Perform Bubble Sort for integers


bubbleSort(numbersInt, sizeInt);

cout << "Sorted Int Array: ";


displayArray(numbersInt, sizeInt);

const int sizeDouble = 6;


double numbersDouble[sizeDouble] = {3.14, 2.71, 1.1, 2.5, 0.5, 4.0};

cout << "\nOriginal Double Array: ";


displayArray(numbersDouble, sizeDouble);

// Perform Bubble Sort for doubles


bubbleSort(numbersDouble, sizeDouble);

cout << "Sorted Double Array: ";


displayArray(numbersDouble, sizeDouble);

const int sizeChar = 5;


char characters[sizeChar] = {'d', 'a', 'c', 'b', 'e'};

cout << "\nOriginal Char Array: ";


displayArray(characters, sizeChar);

// Perform Bubble Sort for chars


bubbleSort(characters, sizeChar);
cout << "Sorted Char Array: ";
displayArray(characters, sizeChar);

getch(); // Wait for a key press before exiting


return 0;
}
[Link] bill-Class.
#include <iostream.h>
#include <conio.h>

class ElectricityBill {
private:
char customerName[50];
int unitsConsumed;

public:
// Constructor to initialize member variables
ElectricityBill(const char* name, int units) {
strcpy(customerName, name);
unitsConsumed = units;
}

// Member function to calculate total bill amount


double calculateBill() const {
const double unitRate = 5.0; // Change the unit rate as needed
return unitsConsumed * unitRate;
}

// Member function to display bill details


void displayBill() const {
cout << "Customer Name: " << customerName << endl;
cout << "Units Consumed: " << unitsConsumed << " units" << endl;
cout << "Total Bill Amount: $" << calculateBill() << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create an ElectricityBill object for Gokul


ElectricityBill gokulBill("Gokul", 200);

// Display the bill details for Gokul


cout << "Electricity Bill Details for Gokul:" << endl;
[Link]();

getch(); // Wait for a key press before exiting


return 0;
}
[Link] constructor -Person class
#include <iostream.h>
#include <conio.h>
#include <string.h>

class Person {
private:
char* name;
int age;

public:
// Constructor to initialize member variables
Person(const char* personName, int personAge) {
name = new char[strlen(personName) + 1];
strcpy(name, personName);
age = personAge;
}

// Copy constructor
Person(const Person& otherPerson) {
// Allocate memory for the name and copy it
name = new char[strlen([Link]) + 1];
strcpy(name, [Link]);

// Copy age
age = [Link];
}

// Destructor
~Person() {
delete[] name;
}

// Member function to display person details


void displayPerson() const {
cout << "Name: " << name << ", Age: " << age << " years" << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create a Person object for Gokul


Person gokul("Gokul", 25);

// Display the details of the original person (Gokul)


cout << "Original Person Details:" << endl;
[Link]();

// Use the copy constructor to create another person (Gokul)


Person gokulCopy = gokul;

// Display the details of the copied person (Gokul)


cout << "\nCopied Person Details:" << endl;
[Link]();
getch(); // Wait for a key press before exiting
return 0;
}
[Link] handling -positive integers.
#include <iostream.h>
#include <conio.h>

// Function to get a positive integer from the user


int getPositiveInteger() {
int num;

while (true) {
cout << "Enter a positive integer: ";
cin >> num;

// Check if the input is a positive integer


if ([Link]() || num <= 0) {
cout << "Invalid input. Please enter a positive integer." << endl;

// Clear the input buffer to handle incorrect input types


[Link]();
[Link](numeric_limits<streamsize>::max(), '\n');
} else {
// Valid input, break out of the loop
break;
}
}

return num;
}

int main() {
clrscr(); // Clear the screen

// Get a positive integer from the user


int positiveInt = getPositiveInteger();

// Display the positive integer


cout << "You entered: " << positiveInt << endl;

getch(); // Wait for a key press before exiting


return 0;
}

In this example:

• The getPositiveInteger function repeatedly prompts the user to enter a positive integer
until a valid input is provided.
• It uses [Link]() to check if the input is of the correct type (integer) and num <= 0 to
check if it is positive.
• If the input is invalid, the program displays an error message, clears the input buffer, and prompts
the user again.
• The main function demonstrates using getPositiveInteger to get a positive integer from
the user and then displays the entered value.

[Link] series.
#include <iostream.h>
#include <conio.h>

// Function to generate the Fibonacci series


void generateFibonacci(int n) {
int firstTerm = 0, secondTerm = 1, nextTerm;

cout << "Fibonacci Series up to " << n << " terms:" << endl;

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


cout << firstTerm << " ";

nextTerm = firstTerm + secondTerm;


firstTerm = secondTerm;
secondTerm = nextTerm;
}
}

int main() {
clrscr(); // Clear the screen

// Get the number of terms from the user


int numTerms;
cout << "Enter the number of terms for the Fibonacci series: ";
cin >> numTerms;

// Check if the input is valid


if ([Link]() || numTerms <= 0) {
cout << "Invalid input. Please enter a positive integer." << endl;
} else {
// Generate and display the Fibonacci series
generateFibonacci(numTerms);
}

getch(); // Wait for a key press before exiting


return 0;
}
[Link] of squares between 1 to N.
#include <iostream.h>
#include <conio.h>

// Function to calculate the sum of squares


int sumOfSquares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i;
}

return sum;
}

int main() {
clrscr(); // Clear the screen

// Get the value of N from the user


int N;
cout << "Enter the value of N: ";
cin >> N;

// Check if the input is valid


if ([Link]() || N <= 0) {
cout << "Invalid input. Please enter a positive integer." << endl;
} else {
// Calculate and display the sum of squares
int result = sumOfSquares(N);
cout << "Sum of squares between 1 and " << N << ": " << result << endl;
}

getch(); // Wait for a key press before exiting


return 0;
}
[Link] an Array Element at a Specific Position.
#include <iostream.h>
#include <conio.h>

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

// Function to insert an element at a specific position in the array


void insertElement(int arr[], int& size, int position, int element) {
// Check if the position is valid
if (position < 0 || position > size) {
cout << "Invalid position. Please enter a position between 0 and " << size << "." << endl;
return;
}

// Shift elements to make space for the new element


for (int i = size; i > position; i--) {
arr[i] = arr[i - 1];
}

// Insert the new element at the specified position


arr[position] = element;

// Increment the size of the array


size++;
}
// Function to display the elements of the array
void displayArray(const int arr[], int size) {
cout << "Array Elements: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
clrscr(); // Clear the screen

int arr[MAX_SIZE];
int size = 0;

// Get initial elements of the array


cout << "Enter the initial elements of the array (enter -1 to stop):" << endl;
int element;
do {
cin >> element;
if (element != -1) {
arr[size++] = element;
}
} while (element != -1 && size < MAX_SIZE);

// Display the original array


displayArray(arr, size);

// Get the position and element to insert


int position, newElement;
cout << "Enter the position to insert the new element: ";
cin >> position;
cout << "Enter the new element to insert: ";
cin >> newElement;

// Insert the new element at the specified position


insertElement(arr, size, position, newElement);

// Display the modified array


cout << "Array after insertion:" << endl;
displayArray(arr, size);

getch(); // Wait for a key press before exiting


return 0;
}
• The insertElement function is used to insert a new element at a specific position in the array.
• The displayArray function is used to display the elements of the array.
• The program prompts the user to enter the initial elements of the array, displays the original array,
and then asks for the position and new element to insert.
[Link] management system- Class concept.
#include <iostream.h>
#include <conio.h>
#include <cstring>

const int MAX_BOOKS = 100;

class Book {
private:
char title[50];
char author[50];
int year;

public:
// Constructor to initialize book details
Book(const char* bookTitle, const char* bookAuthor, int publicationYear) {
strcpy(title, bookTitle);
strcpy(author, bookAuthor);
year = publicationYear;
}

// Display book details


void displayBook() const {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Year of Publication: " << year << endl;
}
};

class Library {
private:
Book books[MAX_BOOKS];
int numBooks;

public:
// Constructor to initialize the library
Library() {
numBooks = 0;
}

// Add a book to the library


void addBook(const Book& newBook) {
if (numBooks < MAX_BOOKS) {
books[numBooks++] = newBook;
cout << "Book added to the library." << endl;
} else {
cout << "Library is full. Cannot add more books." << endl;
}
}

// Display all books in the library


void displayLibrary() const {
cout << "Library Catalog:" << endl;
for (int i = 0; i < numBooks; i++) {
books[i].displayBook();
cout << "---------------------" << endl;
}
}
};

int main() {
clrscr(); // Clear the screen

// Create books
Book book1("The Catcher in the Rye", "J.D. Salinger", 1951);
Book book2("To Kill a Mockingbird", "Harper Lee", 1960);
Book book3("1984", "George Orwell", 1949);

// Create a library
Library library;

// Add books to the library


[Link](book1);
[Link](book2);
[Link](book3);

// Display all books in the library


[Link]();

getch(); // Wait for a key press before exiting


return 0;
}
1. Book Class:

• Represents a book with title, author, and year of publication.


• Constructor initializes book details.
• displayBook function shows book details.
2. Library Class:

• Represents a library that stores an array of books.


• Constructor initializes the number of books.
• addBook function adds a book to the library.
• displayLibrary function shows details of all books.
3. Main Function:

• Creates instances of the Book class for three books.


• Creates an instance of the Library class.
• Adds books to the library and displays the library catalog.

You might also like