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

OOP Through C++ Lab Manual

Object oriented programming through c++ programs practice Lab manual . computer language programming

Uploaded by

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

OOP Through C++ Lab Manual

Object oriented programming through c++ programs practice Lab manual . computer language programming

Uploaded by

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

Vasavi College of Engineering

(Autonomous)
(Affiliated to Osmania University, Hyderabad, Approved by A.I.C.T.E.)
9-5-81, Ibrahimbagh , Hyderabad - 500 031 (T.S.)
www.vce.ac.in

LAB MANUAL
(Student Manual)

U23ES211EE –OBJECT ORIENTED


PROGRAMMING USING C++ LAB

For

BE EEE II-SEMESTER
2023-24

Department of Electrical and Electronics Engineering


Vasavi College of Engineering (A) 500 031 India
Vasavi College of Engineering(A)
Department of Electrical and Electronics Engineering

Name of the Student___________________ Roll No._____________


OBJECT ORIENTED PROGRAMMING USING C++ LAB BE II-Sem EEE
LIST OF EXPERIMENTS
Experiment Signature Remarks
Expt No Name of the experiment conducted of the
Date faculty
Basic programs with C++ (in
1 comparision with C)

Programs on matrix and


complex numbers using Objects
2
and classes.

Programs on OOP concept


3 Features

Programs on static data


4 members.

5 Programs on dynamic memory


allocation for arrays.
Programs on string
6 manipulations.

7 Programs to demonstrate friend


class.
Programs using constructors,
destructors and copy
8
constructors.

9 Programs to demonstrate
function overloading.
Programs to demonstrate
10 operator overloading.

Programs on exception handling


11
INDEX

Name of the program

1. Basic programs with C++ (in comparision with C)


a) Hello World
b) Sum of two numbers
c) Squareroot
d) Printing N natural numbers
e) Sum of N natural numbers
f) Prime number
2. Programs on matrix and complex numbers using Objects and classes.
a) Declare the class of name, Roll No. and marks. Create an array of class objects. Read
and display the contents of the array.
b) Adding of two complex numbers
c) Matrix operation
3. Programs on OOP concept Features
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction
4. Programs on static data members.
a. Allocating memory for static data members
b. Allocating memory for static data members and display
5. Programs on dynamic memory allocation for arrays.
a) Dynamic allocation of memory for the elements
b)) Dynamic allocation of memory for the array elements
6. Programs on string manipulations.
a) String Length
b) String Copy
c) String Comparison
d) String Conversion (string to an integer)
e) String Conversion (string to an doubler)
f) Numeric to String Conversion
g) String Concatenation
h) String Substring
i) String Padding
j) String Replacement

7. Programs to demonstrate friend class.


a) Maximum out of Two Numbers
b) Swap private data members
c) Sum of two complex numbers
8. Programs using constructors, destructors and copy constructors.
a) Constructor
b) Copy constructor
c) Class’s constructor.
d) Constructor and destructors

9. Programs to demonstrate function overloading.


a) Function overloading
b) Function overloading with different types of arguments.
10. Programs to demonstrate operator overloading.
11. Programs on exception handling.
a) Try, catch and throw in exception handling
b) Multiple Catch Block Exception
Before entering the lab the student should carry the following things
(MANDATORY)
1. Identity card issued by the college.
2. Class notes
3. Lab Manual
4. Lab Record
Student should need to follow:
➢ Student must sign in and sign out in the register provided when attending the lab
session without fail.
➢ Come to the laboratory in time. Students, who are late more than 15 min., will not
be allowed to attend the lab.
➢ Students need to maintain good attendance in lab if not a strict action will be taken.
➢ Foods, drinks are NOT allowed inside the lab.
➢ All bags must be left at the indicated place.
➢ shoes or chappals need to leave outside the lab at specified place.
➢ Workspace must be kept clean and tidy after experiment is completed.
➢ Read the Manual carefully before coming to the laboratory and be sure about what
you are supposed to do.
➢ Do the experiments as per the instructions given in the manual. Copy all the
programs to observation which are taught in class before attending the lab session.
➢ Students are not supposed to use floppy disks, pen drives without permission of lab-
in charge.
➢ Lab records need to be submit every week with completion of previous week
experiment.
ASCII characters along with their code.
Useful nomenclature

Symbol Name Symbol Name

! exclamation : colon

" double quotes ; semicolon

# number sign < less than sign


$ dollar sign = equal sign

% percent sign > greater than

& ampersand ? Question mark

' single quote [ opening bracket

( opening parenthesis \ backslash

) closing ] closing bracket


Parenthesis
* asterisk ^ caret

+ plus sign _ underscore

, comma { opening brace

- Minus/hyphen | vertical bar

. period } closing brace

/ slash ~ equivalency-tilde
Keywords:
Keywords are those words, whose meaning is already known to the C++ compiler i.e. they are
predefined words. The keywords cannot be used as variable names.

• asm: To declare that a block of code is to be passed to the assembler.


• auto: A storage class specifier that is used to define objects in a block.
• break: Terminates a switch statement or a loop.
• case: Used specifically within a switch statement to specify a match for
the statement’s expression.
• catch: Specifies actions taken when an exception occurs.
• char: Fundamental data type that defines character objects.
• class: To declare a user-defined type that encapsulates data members
and operations or member functions.
• const: To define objects whose value will not alter throughout the lifetime
of program execution.
• continue:- Transfers control to the start of a loop.
• default:- Handles expression values in a switch statement that are not
handled by case.
• delete: Memory deallocation operator.
• do: indicate the start of a do-while statement in which the sub-statement
is executed repeatedly until the value of the expression is logical-false.
• double: Fundamental data type used to define a floating-point number.
• else: Used specifically in an if-else statement.
• enum: To declare a user-defined enumeration data type.
• extern: An identifier specified as an extern has an external linkage to the
block.
• float:- Fundamental data type used to define a floating-point number.
• for: Indicates the start of a statement to achieve repetitive control.
• friend: A class or operation whose implementation can access the private
data members of a class.
• goto: Transfer control to a specified label.
• if: Indicate the start of an if statement to achieve selective control.
• inline: A function specifier that indicates to the compiler that inline
substitution of the function body is to be preferred to the usual function
call implementation.
• int: Fundamental data type used to define integer objects.
• long: A data type modifier that defines a 32-bit int or an extended double.
• new: Memory allocation operator.
• operator: Overloads a c++ operator with a new declaration.
• private: Declares class members which are not visible outside the class.
• protected: Declares class members which are private except to derived
classes
• public: Declares class members who are visible outside the class.
• register: A storage class specifier that is an auto specifier, but which also
indicates to the compiler that an object will be frequently used and should
therefore be kept in a register.
• return: Returns an object to a function’s caller.
• short: A data type modifier that defines a 16-bit int number.
• signed: A data type modifier that indicates an object’s sign is to be stored
in the high-order bit.
• sizeof: Returns the size of an object in bytes.
• static: The lifetime of an object-defined static exists throughout the
lifetime of program execution.
• struct: To declare new types that encapsulate both data and member
functions.
• switch: This keyword is used in the “Switch statement”.
• template: parameterized or generic type.
• this: A class pointer points to an object or instance of the class.
• throw: Generate an exception.
• try: Indicates the start of a block of exception handlers.
• typedef: Synonym for another integral or user-defined type.
• union: Similar to a structure, struct, in that it can hold different types of
data, but a union can hold only one of its members at a given time.
• unsigned: A data type modifier that indicates the high-order bit is to be
used for an object.
• virtual: A function specifier that declares a member function of a class
that will be redefined by a derived class.
• void: Absent of a type or function parameter list.
• volatile: Define an object which may vary in value in a way that is
undetectable to the compiler.
• while: Start of a while statement and end of a do-while statement.
Memory sizes

Type Size (in Bytes) Size (in Bits) Range


𝑠ℎ𝑜𝑟𝑡 i𝑛𝑡 𝑜𝑟 𝑠i𝑔𝑛𝑒𝑑 𝑠ℎ𝑜𝑟𝑡 1 8 −128 𝑡𝑜 127
i𝑛𝑡 Or char

i𝑛𝑡 𝑜𝑟 𝑠i𝑔𝑛𝑒𝑑 i𝑛𝑡 2 16 −32768 𝑡𝑜 32767

𝑢𝑛𝑠i𝑔𝑛𝑒𝑑 i𝑛𝑡 2 16 0 𝑡𝑜 65535


𝑙𝑜𝑛𝑔 i𝑛𝑡 4 32 −2147483648 𝑡𝑜 2147483647
ƒ𝑙𝑜𝑎𝑡 4 32 3.4𝐸 − 38 𝑡𝑜 3.4𝐸 + 38
𝑑𝑜𝑢𝑏𝑙𝑒 8 64 1.7𝐸 − 308 𝑡𝑜 1.7𝐸 + 308
𝑙𝑜𝑛𝑔 𝑑𝑜𝑢𝑏𝑙𝑒 10 80 3.4𝐸 − 4932 𝑡𝑜 1.1𝐸 + 4932

endl New line

C++ -Compilers
• Borland Turbo C/ Turbo C
• Tiny C Compiler
• Portable C Compiler
• GCC
• MinGW / GCC
• Borland c++
• Dev C++
• Embracadero
• Clang
• Visual C++
• Intel C++
• Code Block

Online Compilers
• Programiz: https://www.programiz.com/c-programming/online-compiler/
. GDB : https://www.onlinegdb.com/online_c_compiler
Web learning
https://www.geeksforgeeks.org/c-plus-plus/
https://leetcode.com/discuss/study-guide/
Shortcut Keys for Turbo C++

F1 For Help
F2 Save
F3 Open
F4 Go to Curser
F5 Zoom
F6 Next
F7 Trace Into
F8 Step Over
F10 Make
Alt+X Menu
Alt+Bksp Quit
Shift+Alt+Bksp Undo
Shift+Del Redo
Alt + F9 Compile
Ctrl+ F9 Run Code
Ctrl + Y Delete Line
Ctrl + Ins Copy
Shift + Del Cut
Shift + Ins Paste
Windows Exit
Ctrl + S Save
Alt + Bksp Undo
Alt + X Quit
Alt+F5 To check output
Alt+F For menu bar options
Alt+F3 Close
Introduction Programs:
➢ In the Turbo C++ compiler, all the header files should be include with .h Ex
#include<iostream.h>. In other compilers .h not required like #include<iostream> is
enough

➢ Don’t mention “//using namespace std;” in turbo C compiler.


➢ In other compilers use “//using namespace std;” this function for standard “cin>>” and
“cout<<” functions. or
std::cin>>
std:cout<< (without using “//using namespace std;”)

➢ In the Turbo C++ compiler, cin>> or cout<< is enough for input or output
operations(std:: or using namespace std not required)

INPUT/OUTPUT

• Use the C++ extraction operator (>>) to extract data from the input stream,
such as cin. cin is a standard input stream, which is usually the keyboad.

• Syntax: cin >> input variable;
Example: int x, y;

cin >>x>>y; //Accept two integer numbers entered from the keyboard. The
numbers are separated by at least one space.

• Use the C++ extraction operator (<<) to insert data into an output stream.
You can use the cout output stream. cout is a standard output stream, which
is a screen.

Example: cout <<"hello world"<<endl; //Display hello world on the screen


1.a) Write a program to print “Hello World.”
(Write a program to print Hello world using C)
#include <iostream> //in Dev C++ or online GDB
main(void)
{
std::cout<<"Hello World";
}
Or
#include <iostream> //in Dev C++ or online GDB
using namespace std;
main(void)
{
cout<<"Hello World";
}
Or
#include <iostream.h> //in turbo C++
main(void)
{
cout<<"Hello World";
}
Output:
Hello World
1.b) Write a program to take the two input numbers from the user and prints the sum
of the given number. (Write a program to print sum of two numbers using C)
#include <iostream.h>
int main()
{
int a, b;
cout << "Input two numbers:\n";
cin >> a >> b;
int sum = a + b; // Declaration of sum
cout << "Sum of " << a << " and " << b <<" is: " << sum << std::endl;
}
Output:
Input two numbers: 2 5
Sum of 2 and 5 is: 7
1.c) Write a program to print the N natural numbers using recursion
(Write a program to print the N natural numbers using recursion in C)

#include <iostream.h>
//using namespace std;
void printUptoN(int n) {
if (n > 1)
printUptoN(n - 1);
cout << n << " ";
}
int main() {
int n;
cout << "Enter the upper limit= ";
cin >> n;
cout << "First " << n << " natural numbers are : ";
printUptoN(n);
return 0;
}
Output: Enter the upper limit= 10
First 10 natural numbers are : 1 2 3 4 5 6 7 8 9 10

1.d) Write a program to print the square root of the given number
#include <iostream.h>
#include <cmath.h>
int main()
{
double x;
cout << "Input number:" << endl;
cin >> x;
double sqrt_x = sqrt(x);
cout << "Sq. Root of " << x;
cout << " is: " << sqrt_x << endl;
}
Outpu: Input number:
15
Sq. Root of 15 is: 3.87298
1.e) Write a program to print the sum N natural numbers
#include <iostream.h>
int main() {
int n;
int sum = 0;
cout << "Input Number limit:" << endl;
cin >> n;
for (int i = 0; i <= n; ++i) // Local Decl.
sum = sum + i;
cout << "Sum of " << n ;
cout << " numbers is: " << sum << endl;
}
Output:
Input Number limit:
10
Sum of 10 numbers is: 55
1.f) Write a program to check the given number is prime or not.
#include <iostream.h> cout << n << " is not a prime
//using namespace std; number";

int main() { goto end;

int i, n; }

cout << "Enter a positive integer: "; }

cin >> n; cout << n << " is a prime number";

if (n == 0 || n == 1) end:

{ return 0;

cout << n << " not defined"; }

goto end; Output:

} Enter a positive integer: 19

for (i = 2; i <= n/2; ++i) { 19 is a prime number

if (n % i == 0) Enter a positive integer: 20

{ 20 is not a prime number


2.a) Write a C++ Program to display Names, Roll No., and marks of 3 (N) students who
have appeared in the examination. Declare the class of name, Roll No. and marks.
Create an array of class objects. Read and display the contents of the array.
#include <iostream.h>
//using namespace std;
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
int N;
cout << "Enter the how many students information : " << endl;
cin>>N;
for(int i = 0; i < N; ++i)
{
s[i].roll = i+1;
cout << "For roll number" << s[i].roll << "," << endl;
cout << "Enter name: ";
cin >> s[i].name;
cout << "Enter marks: ";
cin >> s[i].marks;
cout << endl;
}
cout << "Displaying Information: " << endl;
for(int i = 0; i < N; ++i)
{
cout << "\nRoll number: " << i+1 << endl;
cout << "Name: " << s[i].name << endl;
cout << "Marks: " << s[i].marks << endl;
}
return 0;
}
Output:
Enter the how many students information:
3
For roll number1,
Enter name: Sachin
Enter marks: 90
For roll number2,
Enter name: dravid
Enter marks: 85
For roll number3,
Enter name: dhoni
Enter marks: 92
Displaying Information:

Roll number: 1
Name: Sachin
Marks: 90

Roll number: 2
Name: dravid
Marks: 85

Roll number: 3
Name: dhoni
Marks: 92

2.b) Write a C++ Program to Add Two Complex Numbers using Class.
#include<iostream>
//using namespace std;
class Complex{
public:
int real;
int imag;
void setvalue()
{
cin>>real;
cin>>imag;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
void sum(Complex c1, Complex c2)
{
real=c1.real+c2.real;
imag=c1.imag+c2.imag;
}
};
int main()
{
Complex c1,c2,c3;
cout<<"Enter real and imaginary part of first complex number"<<endl;
c1.setvalue();
cout<<"Enter real and imaginary part of second complex number"<<endl;
c2.setvalue();
cout<<"Sum of two complex numbers is"<<endl;
c3.sum(c1,c2);
c3.display();
return 0;
}
Output:
Enter real and imaginary part of first complex number
23
Enter real and imaginary part of second complex number
35
Sum of two complex numbers is
5+8i
2.C) Write C++ program to read, add and display matrix using class
#include<iostream>
#include<conio.h>
//using namespace std;
class matrix
{
int a;
int b;
int A[3][3];
public:
void readmatrix();
void displaymatrix();
};

void matrix::readmatrix()
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
cout<<"A["<<i<<"]["<<j<<"] : ";
cin>>A[i][j];
}
}
}

void matrix::displaymatrix()
{
cout<<"output matrix";
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
cout<<" "<<A[i][j]+A[i][j];
}
cout<<endl;
}
}

int main()
{
matrix m;
m.readmatrix();
m.displaymatrix();
getch();
return(0);
}
Output
A[1][1] : 2
A[1][2] : 3
A[1][3] : 4
A[2][1] : 5
A[2][2] : 6
A[2][3] : 7
A[3][1] : 8
A[3][2] : 9
A[3][3] : 10
Output matrix
468
10 12 14
16 18 20
3. Encapsulation

Encapsulation is the concept of bundling data (attributes) and behavior (methods)


within a single entity (object) and restricting access to the internal details of that object.
In other words, it refers to the process of hiding the implementation details of an object
and exposing only the necessary functionality. The encapsulation principle helps to
ensure that the object's data is protected and cannot be accidentally modified by other
parts of the program.

For example, let's consider a class named "BankAccount". This class may contain private
data such as "accountNumber", "balance", and "interestRate", and behavior such as
"deposit()", "withdraw()", and "calculateInterest()".

Encapsulation allows us to protect the data of the bank account object, so that it can
only be accessed through well-defined methods, such as "getBalance()" and "deposit()".
This ensures that the internal state of the bank account is maintained correctly and
prevents unauthorized access to its data.

3.a) Write C++ program on Encapsulation concept application in banking.


#include <iostream.h>
//using namespace std;
class BankAccount
{
private:
int accountNumber;
double balance;
double interestRate;
public:
BankAccount(int accNo, double bal, double intRate)
{
accountNumber = accNo;
balance = bal;
interestRate = intRate;
}
double getBalance()
{
return balance;
}
void deposit(double amount)
{
balance += amount;
}
void withdraw(double amount)
{
balance -= amount;
}
double calculateInterest()
{
return balance * interestRate;
}
};
int main()
{
BankAccount myAccount(1234, 1000, 0.05); // Object instantiation
cout << "Balance: " << myAccount.getBalance() << endl;
myAccount.deposit(500);
cout << "Balance after deposit: " << myAccount.getBalance() << endl;
myAccount.withdraw(200);
cout << "Balance after withdrawal: " << myAccount.getBalance() << endl;
cout << "Interest earned: " << myAccount.calculateInterest() << endl;
return 0;
}
Output:
Balance: 1000
Balance after deposit: 1500
Balance after withdrawal: 1300
Interest earned: 65
Inheritance

Inheritance is the process by which one class (the subclass) derives the properties and
methods of another class (the superclass). Inheritance allows subclasses to reuse the
code of their superclasses, thereby reducing code duplication and promoting code
reuse. Subclasses can also add their own unique properties and behaviors to the
inherited code.
For example, let's consider a class hierarchy consisting of a superclass named "Animal" and
two subclasses named "Cat" and "Dog". The Animal class may contain properties such as
"name" and "age", and methods such as "eat()" and "sleep()". The Cat subclass can inherit
these properties and methods from the Animal class and add its own unique properties and
behaviors, such as "meow()" and "climb()". Similarly, the Dog subclass can inherit from the
Animal class and add its own unique properties and behaviors, such as "bark()" and "fetch()".

3.b) Write C++ program on Inheritance concept


#include <iostream.h>
//using namespace std;
// Superclass
class Animal
{
protected:
string name;
int age;
public:
Animal(string n, int a)
{
name = n;
age = a;
}
void eat()
{
cout << "Eating..." << endl;
}
};
// Subclass
class Cat : public Animal
{
public:
Cat(string n, int a) : Animal(n, a) {}
void meow()
{
cout << "Meow..." << endl;
}
};
// Subclass
class Dog : public Animal
{
public:
Dog(string n, int a) : Animal(n, a) {}
void bark()
{
cout << "Bark..." << endl;
}
};
int main()
{
Cat myCat("Whiskers", 3);
Dog myDog("Rufus", 5);
myCat.eat();
myCat.meow();
myDog.eat();
myDog.bark();
return 0;
}
Output:
Eating...
Meow...
Eating...
Bark...
Polymorphism

Polymorphism refers to the ability of objects to take on multiple forms. It allows


different objects to be treated as if they were of the same type, as long as they share a
common interface. Polymorphism enables code to be more modular and flexible,
allowing it to be reused in different contexts.
For example, let's consider a class hierarchy consisting of a superclass named "Shape"
and two subclasses named "Circle" and "Rectangle". The Shape superclass implements
a virtual method for calculating the area, and both the Circle and Rectangle classes can
have different implementations of the virtual method, which calculates the area of the
shape. We can create a list of Shape objects, containing both Circle and Rectangle
objects, and then iterate through the list, calling the "area()" method on each object. The
code will be able to handle both Circle and Rectangle objects, even though they have
different implementations of the "area()" method.
3.c) Write C++ program on Polymorphism concept to calculate the area of circle and
rectangle.
#include <iostream.h>
//using namespace std;
class Shape
{
public:
virtual double area()
{
return 0;
}
};
class Rectangle : public Shape
{
private:
double length;
double breadth;
public:
Rectangle(double l, double b)
{
length = l;
breadth = b;
}
double area()
{
return length * breadth;
}
};
class Circle : public Shape
{
private:
double radius;
public:
Circle(double r)
{
radius = r;
}
double area()
{
return 3.14 * radius * radius;
}
};
int main()
{
Shape *shape;
Rectangle rect(10, 5);
Circle cir(5);
// Polymorphism
shape = &rect;
cout << "Area of rectangle: " << shape->area() << endl;
shape = &cir;
cout << "Area of circle: " << shape->area() << endl;
return 0;
}
Output:
Area of rectangle: 50
Area of circle: 78.5
Abstraction

Abstraction is the practice of focusing on the essential features of an object and ignoring
the non-essential ones. This allows for the creation of simple and easy-to-use interfaces
for complex systems.

For example, consider a car. A customer doesn't need to know how the engine works or
how the transmission shifts gears. Instead, they only need to know how to start and
drive the car.

In C++, abstraction can be achieved using abstract classes. An abstract class is a class
that cannot be instantiated but can be inherited by other classes. It defines a set of
methods that must be implemented by any class that inherits from it but does not
implement those methods itself.

3.d) Write C++ program on Abstraction concept

#include <iostream.h>
//using namespace std;
class Vehicle
{
public:
virtual void start() = 0; // pure virtual method
virtual void stop() = 0; // pure virtual method
};
class Car : public Vehicle
{
public:
void start()
{
cout << "Starting..." << endl;
}
void stop()
{
cout << "Stopping..." << endl;
}
};
int main()
{
Car myCar;
myCar.start();
myCar.stop();
return 0;
}
Output:
Starting...
Stopping...
Allocating memory
There are two ways that memory gets allocated for data storage:

1. Compile Time (or static) Allocation


o Memory for named variables is allocated by the compiler
o Exact size and type of storage must be known at compile time
o For standard array declarations, this is why the size has to be constant
2. Dynamic Memory Allocation
o Memory allocated "on the fly" during run time
o dynamically allocated space usually placed in a program segment
known as the heap or the free store
o Exact amount of space or number of items does not have to be known
by the compiler in advance.
o For dynamic memory allocation, pointers are crucial

4.A) )Write a C++ program on static data members.


#include<iostream>
//using namespace std;
class test
{
int code;
static int count;
public:
void setcode(void)
{
code = ++count;
}
void showcode(void)
{
cout<<"object number:"<<code<<"\n";
}
static void showcount(void)
{
cout<<"count:"<<count<<"\n";
}
};
int test :: count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test :: showcount();
test t3; t3.setcode();
test :: showcount(); t1.showcode(); t2.showcode(); t3.showcode();
return 0;
}
Output:
count:2
count:3
object number:1
object number:2
object number:3
4.B) Write a C++ program Allocating memory for static data members and display
#include <iostream>

#include<string.h>

using namespace std;

class Student {

private:

int rollNo;

char name[10];

int marks;

public:

static int objectCount;

Student() {

objectCount++;

void getdata() {

cout << "Enter roll number: "<<endl;

cin >> rollNo;


cout << "Enter name: "<<endl;

cin >> name;

cout << "Enter marks: "<<endl;

cin >> marks;

void putdata() {

cout<<"Roll Number = "<< rollNo <<endl;

cout<<"Name = "<< name <<endl;

cout<<"Marks = "<< marks <<endl;

cout<<endl;

};

int Student::objectCount = 0;

int main(void) {

Student s1;

s1.getdata();

s1.putdata();

Student s2;

s2.getdata();

s2.putdata();

Student s3;

s3.getdata();

s3.putdata();

cout << "Total objects created = " << Student::objectCount << endl;

return 0;

Enter roll number: 1


Enter name: Mark
Enter marks: 78
Roll Number = 1
Name = Mark
Marks = 78

Enter roll number: 2


Enter name: Nancy
Enter marks: 55
Roll Number = 2
Name = Nancy
Marks = 55

Enter roll number: 3


Enter name: Susan
Enter marks: 90
Roll Number = 3
Name = Susan
Marks = 90
Total objects created = 3
5.Dynamic Memory Allocation
• We can dynamically allocate storage space while the program is running, but we
cannot create new variable names "on the fly"
• For this reason, dynamic allocation requires two steps:
1. Creating the dynamic space.
2. Storing its address in a pointer (so that the space can be accesed)
• To dynamically allocate memory in C++, we use the new operator.
• De-allocation:
o Deallocation is the "clean-up" of space being used for variables or other data
storage
o Compile time variables are automatically deallocated based on their known
extent (this is the same as scope for "automatic" variables)
o It is the programmer's job to deallocate dynamically created space
o To de-allocate dynamic memory, we use the delete operator

5.A) Write a C++ program for the dynamic allocation of memory for the
elements

#include<iostream>

//using namespace std;

int main() {

int x, n;

cout << "Enter the number of items:" << "\n";

cin >>n;

int *arr = new int(n);

cout << "Enter " << n << " items" << endl;

for (x = 0; x < n; x++) {

cin >> arr[x];

cout << "You entered: ";

for (x = 0; x < n; x++) {

cout << arr[x] << " ";

return 0;

}
Output:

Enter the number of items:

Enter 5 items

78942

You entered: 7 8 9 4 2

5.B) Write a program for the dynamic allocation of memory for the array
elements

#include <iostream.h>
//using namespace std;
int main(void)
{
int x;
int *array{ new int[5]{ 10, 7, 15, 3, 11 } };
cout << "Array elements: " << endl;
for (x = 0; x < 5; x++) {
cout << array[x] << endl;
}
return 0;
}
Output:
Array elements:
10
7
15
3
11
6. Programs on string manipulations.
6.a) String Length: std::string::length

The string length function calculates the length (number of characters) of a string.

#include <iostream.h>
#include <string>
int main() {
std::string str = "Hello, World!";
int length = str.size(); // Returns the length of the string, which is 13
std::cout << "The length of the string is: " << length << std::endl;
return 0;
}

Output:

The length of the string is: 13

6.b) String Copy: std::strcpy

The string copy function copies a string from a source location to a destination

#include <iostream.h>
#include <cmath>
int main() {
char source[] = "Hello, World!"; // Source string
char destination[20]; // Destination character array
std::strcpy(destination, source); // Copy the source string to the destination
std::cout << "Source string: " << source << std::endl;
std::cout << "Copied string: " << destination << std::endl;
return 0;
}

Output:

Source string: Hello, World!


Copied string: Hello, World!

6.c) String Comparison: std::string::compare

The string comparison function compares two strings lexicographically and returns an integer
representing the result.

#include <iostream.h>
#include <string>
int main() {
std::string str1 = "apple";
std::string str2 = "banana";
int result = str1.compare(str2);
if (result == 0) {
std::cout << "The strings are equal." << std::endl;
} else if (result < 0) {
std::cout << "The string str1 is less than str2." << std::endl;
} else {
std::cout << "The string str1 is greater than str2." << std::endl;
}
return 0;
}

Output:

The string str1 is less than str2.

6.d) String Conversion to Integer: std::stoi

This function converts a string to an integer.

#include <iostream.h>
//using namespace std;
int main() {
string str = "123";
int num = stoi(str);
cout << num << endl;
return 0;
}

Output:

123

6.e) String Conversion to Double: std::stod

This function converts a string to a double.

#include <iostream.h>
//using namespace std;
int main() {
string str = "3.14";
double num = stod(str);
cout << num << endl;
return 0;
}

Output:

3.14
6.f) Numeric to String Conversion: std::to_string

This function converts a number to a string.

#include <iostream.h>
#include <string>
//using namespace std;
int main() {
int num = 42;
string str = to_string(num);
cout << str << endl;
return 0;
}

Output:

42

6.g). String Concatenation: std::string::operator+

This function concatenates two strings.

#include <iostream.h>
#include <string>
//using namespace std;
int main() {
string str1 = "Hello";
string str2 = " World!";
string result = str1 + str2;
cout << result << endl;
return 0;
}

Output:

Hello World!

6.h). String Substring: std::string::substr

The string substring function extracts a substring from a string, starting at a specified position
and with a specified length.

#include <iostream.h>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string substr = str.substr(7, 5); // Extracts "World" from the original string
std::cout << "The substring is: " << substr << std::endl;
return 0;
}
Output:

The substring is: World

6.i). String Padding: std::setw

The string padding function pads a string with a specified character or space to a certain
width.

#include <iostream.h>
#include <string>
//using namespace std;
int main() {
string str = "Hello";
cout << setw(10) << setfill(' ') << str << endl;
return 0;
}

Output:

Hello

6.j). String Replacement:

This function replaces a portion of a string with another string.

#include <iostream.h>
#include <string>
//using namespace std;
int main() {
string str = "Hello, World!";
str.replace(7, 5, "Universe"); // Replaces the substring "World" with "Universe"
cout << str << endl;=
return 0;
}

Output:

Hello, Universe!
7. Friend function

7.A) Write a Program to find Maximum out of Two Numbers using friend
function.

Note: Here one number is a member of one class and the other number is member
of some other class.

#include<iostream>

//using namespace std;

class ABC;

class XYZ

int x; public:

void setvalue(int i)

x=i;

friend void max(XYZ, ABC);

};

class ABC

int a; public:

void setvalue(int i)

a=i;

friend void max(XYZ, ABC);

};

void max (XYZ m, ABC n)

if(m.x>=n.a)

cout<<m.x;

else
cout<<n.a;

int main()

ABC abc; abc.setvalue(10);

XYZ xyz; xyz.setvalue(20);

max(xyz,abc);

return 0;

Output:

20

7.B) Write a Program to swap private data members of classes named as class_1,
class_2 using friend function.

#include<iostream>

//using namespace std;

class class_2;

class class_1

int value1; public:

void indata(int a)

value1=a;

void display(void)

cout<<value1<<"\n";

friend void exchange(class_1 &, class_2 &);

};

class class_2

{
int value2; public:

void indata(int a)

value2=a;

void display(void)

cout<<value2<<"\n";

friend void exchange(class_1 &, class_2 &);

};

void exchange(class_1 &x, class_2 &y)

int temp = x.value1; x.value1 = y.value2; y.value2 = temp;

int main()

class_1 C1; class_2 C2;

C1.indata(100);

C2.indata(200);

cout<<"Values before exchange"<<"\n";

C1.display();

C2.display(); exchange(C1, C2);

cout<<"Values after exchange"<<"\n"; C1.display();

C2.display(); return 0;

Output:

Values before exchange Values after exchange

100 200

200 100
7.C) Write a Program to design a class complex to represent complex numbers. The
complex class shuold use an external function (use it as a friend function) to add two
complex numbers.The function should return an object of type complex representing
the sum of two complex numbers.

#include<iostream>
//using namespace std;
class complex
{
float x; float y;
public:
void input(float real, float img)
{
x=real; y=img;
}
friend complex sum(complex, complex); void show(complex);
};
complex sum(complex c1, complex c2)
{
complex c3;
c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return (c3);
}
void complex :: show(complex c)
{
cout<<c.x<<"+j"<<c.y<<"\n";
}
int main()
{
complex A,B,C; A.input(3.1, 5.65);
B.input(2.75, 1.2);

C=sum(A,B);
cout<<"A=";
A.show(A);
cout<<"B=";
B.show(B);
cout<<"C=";
C.show(C);
return 0;
}
Output:
A=3.1+j5.65
B=2.75+j1.2
C=5.85+j6.85
8.A) Write a C++ program with simple example of construct
#include <iostream.h>
//using namespace std;

class construct {
public:
int a, b;
construct()
{
a = 10;
b = 20;
}
};
int main()
{
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 0;
}
Output:
a: 10
b: 20
8.B) Write a Program using copy constructor to copy data of an object to
another object.
#include<iostream>
//using namespace std;
class code
{
int id; public:
code(){} code(int a)
{
id = a;
}
code(code & x)
{
id = x.id;
}
void display(void)
{
cout<<id;
}
};
int main()
{
code A(100);
code B(A);
code C = A;
code D;
D = A;
cout<<"\n id of A:";
A.display();
cout<<"\n id of B:";
B.display();
cout<<"\n id of C:";
C.display();
cout<<"\n id of D:";
D.display();
return 0;
}
Output:
id of A:100
id of B:100
id of C:100
id of D:100
8.C) Write a Program to allocate memory dynamically for an objects of a
given class using class’s constructor.
#include<iostream.h>
#include<cstring>
//using namespace std;
class String
{
char *name; int length;
public:
String()
{
length = 0;
name = new char[length +1];
}
String (char *s)
{
length = strlen(s);
name= new char[length + 1]; strcpy(name, s);
}
void display(void)
{
cout<<name<<"\n";
}
void join(String &a, String &b);
};
void String :: join (String &a, String &b)
{
length = a.length + b.length; delete name;
name = new char [length + 1];
strcpy(name,a.name); strcat(name, b.name);
};
int main()
{
char *first = "Joseph";
String name1(first), name2("Louis "), name3("Lagrange"),s1,s2; s1.join(name1,
name2);
s2.join(s1, name3); name1.display(); name2.display(); name3.display(); s1.display();
s2.display();
return 0;
}
Output:
Joseph JosephLouis
Louis JosephLouis Lagrange
Lagrange
8.D) Write a C++ program to demonstrate the number of times constructor and
destructors are called
#include <iostream.h>
//using namespace std;
static int Count = 0;
class Test {
public:
Test()
{
Count++;
cout << "No. of Object created: " << Count << endl;
}
// User-Defined Destructor
~Test()
{
cout << "No. of Object destroyed: " << Count
<< endl;
Count--;
}
};
int main()
{
Test t, t1, t2, t3;
return 0;
}
9.A) Write a C++ program of function overloading when number of
arguments vary.
#include <iostream.h>
//using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C;
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
9.B) Write a C++ program of function overloading with different types of
arguments.
#include<iostream>
//using namespace std;
int mul(int,int);
float mul(float,int);
int mul(int a,int b)
{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}
Try the programs with different function overloading.

10) Write a C++ program to demonstrate operator overloading


#include <iostream.h>
//using namespace std;

class ComplexNumber {
private:
int real;
int imaginary;
public:
ComplexNumber(int real, int imaginary)
{
this->real = real;
this->imaginary = imaginary;
}
void print() { cout << real << " + i" << imaginary; }
ComplexNumber operator+(ComplexNumber c2)
{
ComplexNumber c3(0, 0);
c3.real = this->real + c2.real;
c3.imaginary = this->imaginary + c2.imaginary;
return c3;
}
};
int main()
{
ComplexNumber c1(3, 5);
ComplexNumber c2(2, 4);
ComplexNumber c3 = c1 + c2;
c3.print();
return 0;
}
Output: 5 + i9
Try the programs with different operator overloading.
11.A) Write a C++ program to demonstrate the use of try, catch and throw in exception
handling
#include <iostream.h>
#include <stdexcept>
//using namespace std;
int main()
{
try {
int numerator = 10;
int denominator = 0;
int res;
if (denominator == 0) {
throw runtime_error(
"Division by zero not allowed!");
}

res = numerator / denominator;


cout << "Result after division: " << res << endl;
}
catch (const exception& e) {
// print the exception
cerr << "Exception " << e.what() << endl;
}

return 0;
}
Output:
Exception Division by zero not allowed!
11.B) Write a C++ program to demonstrate Multiple Catch Block Exception Program
#include <iostream.h>
//using namespace std;
float divide(int x, int y) {
if (y == 0) {
throw y;
} else if (y < 0) {
throw "Negative Input";
}
return (x / y);
}
int main() {
int i, result;
cout << "Enter the Number :";
cin>>i;
try {
result = divide(100, i);
cout << result << endl;
} //catch block
catch (int exception_value) {
cout << "Exception Occurred : Exception Value : " << exception_value;
} catch (const char* excpection_str) {
cout << "Exception Occurred : Exception Value : " << excpection_str;
}
return 0;
}
Output:
Enter the Number :5
20
Enter the Number :0
Exception Occurred : Exception Value : 0
Enter the Number :-2
Exception Occurred : Exception Value : Negative Input

You might also like