0% found this document useful (0 votes)
21 views

Lab Manual01 A

Uploaded by

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

Lab Manual01 A

Uploaded by

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

SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

Program 1:
To implement Classes, Constructors, Inheritance, Polymorphism, Dynamic Memory
Allocation, Class Templates, Exception Handling.
Aim : C++ Programs to implement: Classes, Constructors, Inheritance, Polymorphism,
Dynamic Memory Allocation, Class Templates, Exception Handling.

Description :
1.A) Classes: A class in C++ is the building block, that leads to Object-Oriented
programming. It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A C++ class
is like a blueprint for an object.
Syntax to Define Class in C++

class className {
// some data
// some functions
};
C++ Objects
When a class is defined, only the specification for the object is defined; no memory or storage
is allocated.To use the data and access functions defined in the class, we need to create
objects.
Syntax to Define Object in C++
classNameobjectVariableName;

Aim :Write a C++ program to add two times using classes


#include<iostream.h>
class Time
{
int hours;
int minutes;
int seconds;
public:
void getTime();
void displayTime();
void addTime(Time t1, Time t2);
}
void Time::getTime()
{

Page 1
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

cin>>hours;

cin>>minutes;

cin>>seconds;
}
void Time::displayTime()
{

}
void Time::addTime(Time t1,Time t2)
{

this-> seconds=t1.seconds+t2.seconds;
this->minutes=t1.minutes+t2.minutes+this->seconds/60;
this->hours=t1.hours+t2.hours+this->minutes/60;
this->minutes=this->minutes%60;
this->seconds=this -> seconds%60;
}
int main()
{
Time t1,t2,t3;
t1.getTime();
t2.getTime();
t3.addTime(t1,t2);
t3.displayTime();
return 0;
}

Expected Output:

Enter hours
3
Enter minutes
45
Enter seconds34
Enter hours
4
Enter minutes
56
Enter seconds46
HH:MM:SS8:42:20

1.B) Constructors: A constructor is a special member function of a class which initializes


objects of a class. In C++, Constructor is automatically called when object(instance of class)
is created.

class MyClass{
public:
MyClass() {

Page 2
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

cout<< "Hello World!";


}
};

int main() {
MyClassmyObj; // Create an object of MyClass (this will call the constructor)
return 0;
}

A constructor is different from normal functions in following ways:


Constructor has same name as the class itself
Constructors have return type
A constructor is automatically called when an object is created.
If we do not specify a constructor, C++ compiler generates a defaultconstructor for us
(expects no parameters and has an empty body).

Types of Constructors

1. Default Constructors: Default constructor is the constructor take any


argument. It has no parameters.

2. Parameterized Constructors: It is possible to pass arguments toconstructors. Typically,


these arguments help initialize an object when it iscreated. To create a parameterized
constructor, simply add parameters to
it the way you would to any other function. When you define body, use the
parameters to initialize the object.

3. Copy Constructor: A copy constructor is a member function whichinitializes an object


using another object of the same class.

Aim:Write a Program to create a default constructor, Parameterized constructor, copy


constructor

#include<iostream>
using namespace std;
class rectangle
{
int l;
int b;
public:
rectangle() // Default Constructor
{
l=5;
b=6;
}
rectangle(int l1,int b1) //Parameterized Constructor
{
l=l1;
b=b1;
}
rectangle(rectangle &r1) //copy constructor
{

Page 3
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

l=r1.l;
b=r1.b;

}
int area()
{
return(l*b);
}
};
int main()
{
rectangle r; //default constructor is called
rectangle r1(6,3); // parameterized constructor is called
rectangle r2(r1); //copy constructor is called
cout<<"Area of rectangle is"<<r.area();
cout<<"\n Area of rectangle is"<<r1.area();
cout<<"\n Area of rectangle is"<<r2.area();
return 0;
}

Expected Output:
Area of rectangle is30
Area of rectangle is18
Area of rectangle is18

1.C) Inheritance:The capability of a class to derive properties and characteristics from


anotherclass is called Inheritance. Inheritance is one of the most important feature ofObject
Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub classor Derived
Class.
Super Class:The class whose properties are inherited by sub class is called BaseClass or Super
class.
Modes of Inheritance:

Public mode: If we derive a sub class from a public base class. Thenthe public
member of the base class will become public in thederived class and protected
members of the base class will becomeprotected in derived class.
Protected mode: If we derive a sub class from a Protected baseclass. Then both public
member and protected members of thebase class will become protected in derived
class.
Private mode: If we derive a sub class from a Private base class.Then both public
member and protected members of the base classwill become Private in derived class.

Note : The private members in the base class cannot be directly accessed in thederived class,
while protected members can be directly accessed.
Syntax:

class subclass_name :access_modebase_class_name


{
//body of subclass
};

Page 4
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

subclass_name is the name of the sub class,


access_mode is the mode in which we want to inherit this sub class for example:public,
private etc.
base_class_name is the name of the base class from which we want to inheritthe sub class.

Types of Inheritance

C++ supports five types of Inheritance

Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance

Single inheritance is defined as the inheritance in which a derived class isinherited from the
only one base class.
Syntax:
class base_class
{

};
class base_class :access_modederived_class
{

};
Multilevel Inheritance

If a class is derived from another derived class then it is called multilevel inheritance.

Syntax:
class A
{

};
class B: access_specifier class A
{

};
lass C: access_specifier class B
{
/
};
Multiple InheritanceIf a class is derived from two or more base classes then it is called
multiple inheritance.
Syntax
class A
{

};

Page 5
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

class B
{

};
class C :access_specifier A, access_specifier B
{

};
Hierarchical InheritanceWhen several classes are derived from common base class it is
called hierarchical inheritance.

Syntax:
class A
{

};
class B :access_specifier A
{

};
class C :access_specifier A
{

};
class D :access_specifier A
{

};
Hybrid Inheritance The inheritance in which the derivation of a class involves more than
one form of any inheritance is called hybrid inheritance. Basically C++ hybrid inheritance is
combination of two or more types of inheritance.
Syntax:
class A
{

};
class B :access_specifier A
{

};
class C
{

};
class D :access_specifierB, access_specifier C
{

};

Page 6
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

Aim:Write a Program in c++to create a base class shape and a derived class rectangle to
calculate the area of rectangle.

#include <iostream>

using namespace std;

// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout<< "Total area: " <<Rect.getArea() << endl;
return 0;
}

Expected Output:

Total area: 35

1.D) Polymorphism:Polymorphism is an important concept of object-oriented programming.


It simply means more than one form. That is, the same entity (function or operator) behaves
differently in different scenarios.
For example, The + operator in C++ is used to perform two specific functions. When it is
used with numbers (integers and floating-point numbers), it performs addition.
int a = 5;
int b = 6;
int sum = a + b; // sum = 11

Page 7
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

And when we use the + operator with strings, it performs string concatenation.

For example,
stringfirstName = "hello ";
stringlastName = "world";

// name = "hello world"


string name = firstName + lastName;

We can implement polymorphism in C++ using the following ways:


Function overloading
Operator overloading
Function overriding
Virtual functions

1.E) C++ Function Overloading

In C++, we can use two functions having the same name if they have different parameters
(either types or number of arguments).
And, depending upon the number/type of arguments, different functions are called. It's
a compile-time polymorphism because the compiler knows which function to execute before
the program is compiled.

Aim:Program to implement concept of function overloading

#include<iostream>
usingnamespacestd;
intsum(int num1, int num2){
return num1 + num2;
}
doublesum(double num1, double num2){
return num1 + num2;
}
intsum(int num1, int num2, int num3){
return num1 + num2 + num3;
}
intmain(){
// Call function with 2 int parameters
cout<<"Sum 1 = "<<sum(5, 6) <<endl;
// Call function with 2 double parameters
cout<<"Sum 2 = "<<sum(5.5, 6.6) <<endl;
// Call function with 3 int parameters
cout<<"Sum 3 = "<<sum(5, 6, 7) <<endl;
return0;
}

Expected Output:
Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18

Page 8
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

1.F) C++ Operator Overloading

In C++, we can change the way operators work for user-defined types like objects and
structures. This is known as operator overloading.
For example,
Suppose we have created three objects c1, c2 and result from a class named Complex that
represents complex numbers.
Since operator overloading allows us to change how operators work, we can redefine how
the + operator works and use it to add the complex numbers of c1 and c2 by writing the
following code:

Result = c1+c2;

Instead of:

Result = c1.addnumbers(c2);

Note: We cannot use operator overloading for fundamental data types like int, float, char and
so on.
Syntax for C++ Operator Overloading

To overload an operator, we use a special operator function.


class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};
Where
returnType is the return type of the function.
operator is a keyword.
symbol is the operator we want to overload. Like: +, <, -, ++, etc.
arguments is the arguments passed to the function.

Operator Overloading in Unary Operators

Unary operators operate on only one operand. The increment operator ++ and decrement
operator -- are examples of unary operators.

Aim:Program to Overload ++ when used as prefix and postfix

#include<iostream>
usingnamespacestd;

classCount {
private:
int value;
public:
// Constructor to initialize count to 5
Count() : value(5) {}

Page 9
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

// Overload ++ when used as prefix


voidoperator ++ () {
++value;
}
// Overload ++ when used as postfix
voidoperator ++ (int) { // Here (int) inside the parenthesis is used as
++value; //dummy to differentiate between postfix and prefix
}
voiddisplay(){
cout<<"Count: "<< value <<endl;
}
};
intmain(){
Count count1;
// Call the "void operator ++ (int)" function
count1++;
count1.display();
// Call the "void operator ++ ()" function
++ count1;
count1.display();
return0;
}

Expected Output:
Count: 6
Count: 7

Aim:Program to implement binary operator overloading to add two complex numbers

#include<iostream>
usingnamespacestd;

classComplex {
private:
float real;
floatimag;
public:
// Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}
voidinput(){
cout<<"Enter real and imaginary parts respectively: ";
cin>> real;
cin>>imag;
}
// Overload the + operator
Complex operator + (const Complex&obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}

Page 10
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

voidoutput(){
if (imag<0)
cout<<"Output Complex number: "<< real <<imag<<"i";
else
cout<<"Output Complex number: "<< real <<"+"<<imag<<"i";
}
};
intmain(){
Complex complex1, complex2, result;
cout<<"Enter first complex number:\n";
complex1.input();
cout<<"Enter second complex number:\n";
complex2.input();
result = complex1 + complex2; // complex1 calls the operator function
// complex2 is passed as an argument to the function

result.output();
return0;
}

Expected Output:

Enter first complex number:


Enter real and imaginary parts respectively: 9 5
Enter second complex number:
Enter real and imaginary parts respectively: 7 6
Output Complex number: 16+11i
Things to Remember in C++ Operator Overloading

1. Two operators = and & are already overloaded by default in C++. For
example, to copy objects of the same class, we can directly use the = operator. We do not
need to create an operator function.
2. Operator overloading cannot change the precedence and associativity of
operators. However, if we want to change the order of evaluation, parentheses should be used.
3. There are 4 operators that cannot be overloaded in C++. They are:
1. :: (scope resolution)
2. . (member selection)
3. .* (member selection through pointer to function)
4. ?: (ternary operator)

1.G) Templates:Templates are powerful features of C++ which allows us to write generic
programs. In simple terms, we can create a single function or a class to work with different
data types using templates.Templates are often used in larger codebase for the purpose of
code reusability and flexibility of the programs.
The concept of templates can be used in two different ways:
Function Templates
Class Templates
Function Templates
A function template works in a similar to a normal function, with one key difference.

Page 11
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

A single function template can work with different data types at once but, a single normal
function can only work with one set of data types.
Normally, if you need to perform identical operations on two or more types of data, you use
function overloading to create two functions with the required function declaration.
However, a better approach would be to use function templates because you can perform the
same task writing less and maintainable code.
How to declare a function template?
A function template starts with the keyword template followed by template parameter/s
inside <> which is followed by function declaration.

template<class T>
T someFunction(T arg)
{
... .. ...
}

Aim:Program to display largest among two numbers using function templates.

#include<iostream>
usingnamespacestd;

// template function
template<classT>
TLarge(Tn1, Tn2)
{
if (n1 > n2)
return(n1);

else
return(n2);
}

intmain()
{
int i1, i2;
float f1, f2;
char c1, c2;

cout<<"Enter two integers:\n";


cin>> i1 >> i2;
cout<<Large(i1, i2) <<" is larger."<<endl;
cout<<"\nEnter two floating-point numbers:\n";
cin>> f1 >> f2;
cout<<Large(f1, f2) <<" is larger."<<endl;

cout<<"\nEnter two characters:\n";


cin>> c1 >> c2;
cout<<Large(c1, c2) <<" has larger ASCII value.";

return0;
}

Page 12
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

Expected Output:
Enter two integers:
5
10
10 is larger.

Enter two floating-point numbers:


12.4
10.2
12.4 is larger.

Enter two characters:


z
Z
z has larger ASCII value.

Class Templates
Like function templates, we can also create class templates for generic class
operations.Sometimes, we need a class implementation that is same for all classes,
only the data types used are different.
Normally, we would need to create a different class for each data type OR create
different member variables and functions within a single class.
This will unnecessarily bloat our code base and will be hard to maintain, as a change is
one class/function should be performed on all classes/functions.
However, class templates make it easy to reuse the same code for all data types.

How to declare a class template?


template<classT>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
In the above declaration, T is the template argument which is a placeholder for the data type
used. Inside the class body, a member variable var and a member
function someOperation() are both of type T.

How to create a class template object?


To create a class template object, we need to define the data type inside a <> when creation.
className<dataType>classObject;
For example:
className<int>classObject;
className<float>classObject;
className<string>classObject;

Aim:Program to add, subtract, multiply and divide two numbers using class template
#include<iostream>
Usingnamespacestd;

Page 13
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

template<classT>
classCalculator
{
private:
T num1, num2;

public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}

voiddisplayResult()
{
cout<<"Numbers are: "<< num1 <<" and "<< num2 <<"."<<endl;
cout<<"Addition is: "<<add() <<endl;
cout<<"Subtraction is: "<<subtract() <<endl;
cout<<"Product is: "<<multiply() <<endl;
cout<<"Division is: "<<divide() <<endl;
}
T add(){ return num1 + num2; }
T subtract(){ return num1 - num2; }
T multiply(){ return num1 * num2; }
T divide(){ return num1 / num2; }
};

intmain()
{
Calculator<int>intCalc(2, 1);
Calculator<float>floatCalc(2.4, 1.2);
cout<<"Int results:"<<endl;
intCalc.displayResult();
cout<<endl<<"Float results:"<<endl;
floatCalc.displayResult();
return0;
}
Expected Output:
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2

Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2

Page 14
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

1.H) Dynamic memory Allocation

Explicitly done by the programmer.


Programmers explicitly requests the system to allocate the memory and return starting
address of the memory allocated. This address is used by the programmer to access the
allocated memory.
When usage of memory is done , it has to be freed explicitly.

Explicitly Allocating memory in C++:


The operator
Used to allocate memory dynamically.
Can be used to allocate single variable / object or an array of variables / objects.
The new operator returns pointer to the type allocated.
Examples:-
char *ptr = new char;
int *myint = new int[20];
rectangle *r = new rectangle(4,5);
Before the assignment, the pointer may or may not point to a legitimate memory.
After the assignment, the pointer points to a legitimate memory.
Explicitly freeing memory in C++:
The operator
Is used to free the memory allocated with the new operator.
The delete operator must be called on a pointer to dynamically allocated memory
when it is no longer needed.
1. Can delete a single variable /object or an array
2. delete pointer_name;
3. delete [] Arrayname;

After delete is called on a memory region, that region should no longer be accessed by the
program.

Aim :Write a program to create an array dynamically , read the elements in an array
and print an array.

include <iostream>
using namespace std;
int main ()
{
int i,n;
int * p;
cout<< "How many numbers would you like to type? ";
cin>>i;
p= new (nothrow) int[i];
if (p == 0)
cout<< "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout<< "Enter number: ";

Page 15
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

cin>> p[n];
}
cout<< "You have entered: ";
for (n=0; n<i; n++)
cout<< p[n] << ", ";
delete[] p;
}
return 0;
}
Expected Output:
How many numbers would you like to type? 5
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
You have entered: 1, 2, 3, 4, 5,

1.I) Exception Handling

Exceptions are runtime anomalies or unusual conditions that a program may encounter
while executing.
Exception handling mechanism provides a means to detect and report an exception
circumstances.
Find the problem (Hit the exception)
Inform that an error has occurred(Throw the exception)
Receive the error information(Catch the exception)
Take corrective actions(Handle the exception)
The exception handling mechanism is built upon three keywords:
1. Try
Is used to preface a block of statements which may generate exceptions.
2. Throw
When an exception is detected, it is thrown using a throw statement in the try block
3. Catch
A catch block defined by the keyword catch catches the exception thrown by the throw
statement in the try block and handles it appropriately.

Aim:Write a Program to raise divide by zero exception

#include<iostream>
using namespace std;
int main()
{
int a=10,b=0;
try
{
if (b==0)
{
throw "division by zero not possible";
}
}
catch (const char *ex)

Page 16
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL

{
cout<<ex;
}
return 0;
}

Expected Output:
division by zero not possible

Page 17

You might also like