You are on page 1of 44

School of Electronics and

Communication Engineering
Program : B.Tech in ECE

Object Oriented Programming and


Data Structures using C++
LABORATORY MANUAL
B20EN0404

IV Semester

2020-24

Rukmini Educational
Charitable Trust
www.reva.edu.in
Vision of the University
‘’REVA University aspires to become an innovative university by developing excellent human
resources with leadership qualities, ethical and moral values, research culture and innovative skills
through higher education of global standards”

Mission of the University


• To create excellent infrastructure facilities and state-of-the-art laboratories and incubation
centres
• To provide student-centric learning environment through innovative pedagogy and education
reforms
• To encourage research and entrepreneurship through collaborations and extension activities
• To promote industry-institute partnerships and share knowledge for innovation and
development
• To organize society development programs for knowledge enhancement in thrust areas
• To enhance leadership qualities among the youth and enrich personality traits, promote
patriotism and moral values.

Vision of the School


The School of Electronics and Communication Engineering is envisioned to be a leading centre
of higher learning with academic excellence in the field of electronics and communication engineering
blended by research and innovation in tune with changing technological and cultural challenges
supported with leadership qualities, ethical and moral values.

Mission of the School


• Establish a unique learning environment to enable the students to face the challenges in the
field of Electronics and Communication Engineering and explore multidisciplinary which serve
the societal requirements.
• Create state-of-the-art laboratories, resources, and exposure to the current industrial trends
to enable students to develop skills for solving complex technological problems of current
times and provide a framework for promoting collaborative and multidisciplinary activities.
• Promote the establishment of Centres of Excellence in niche technology areas to nurture the
spirit of innovation and creativity among faculty and students.
• Offer ethical and moral value-based education by promoting activities which inculcate the
leadership qualities, patriotism and set high benchmarks to serve the society

Program Educational Objectives (PEOs)

The Program Educational Objectives of B. Tech in Electronics and Communication Engineering


are as follows:

PEO -1: To have successful professional careers in industry, government, academia, and military as
innovative engineers.
PEO -2: To successfully solve engineering problems associated with the lifecycle of Electronics and
Communication Systems either leading a team or as a team member.
PEO -3: To continue to learn and advance their careers through activities such as participation in
professional organizations, attainment of professional certification for lifelong
learning and seeking higher education.
PEO -4: To be active members ready to serve the society locally and internationally and will undertake
entrepreneurship for the growth of economy and to generate employment.
Program Outcomes (POs)

On successful completion of the program, the graduates of B. Tech. (Electronics and


Communication Engineering) program will be able to:

 PO-1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals for the solution of complex problems in Electronics and communication
Engineering.
 PO-2: Problem analysis: Identify, formulate, research literature, and analyze engineering
problems to arrive at substantiated conclusions using first principles of mathematics, natural,
and engineering sciences.
 PO-3: Design/development of solutions: Design solutions for complex engineering problems
and design system components, processes to meet the specifications with consideration for
the public health and safety, and the cultural, societal, and environmental considerations.
 PO-4: Conduct investigations of complex problems: Use research-based knowledge
including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
 PO-5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
 PO-6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal, and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
 PO-7: Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.
 PO-8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
 PO-9: Individual and team work: Function effectively as an individual, and as a member or
leader in teams, and in multidisciplinary settings.
 PO-10: Communication: Communicate effectively with the engineering community and with
society at large. Be able to comprehend and write effective reports documentation. Make
effective presentations, and give and receive clear instructions.
 PO-11: Project management and finance: Demonstrate knowledge and understanding of
engineering and management principles and apply these to one’s own work, as a member and
leader in a team. Manage projects in multidisciplinary environments.
 PO-12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.

Programme Specific Outcomes (PSOs)

On successful completion of the program, the graduates of B. Tech. (Electronics and


Communication Engineering) program will be able to:

PSO-1: Isolate and solve complex problems in the domains of Electronics and Communication
Engineering using latest hardware and software tools and technologies, along with analytical and
managerial skills to arrive at cost effective and optimum solutions either independently or as a team.

PSO-2: Implant the capacity to apply the concepts of electronics, communications, signal processing,
VLSI, embedded systems, etc. in the design, development and implementation of application oriented
engineering systems.

PSO-3: Design, Model, Analyze and Build Electronics and Communication Systems to solve real life
and industry problems.
REVA University School of ECE

CONTENTS

SL. List of programs Page No.


No.
Introduction to C++ language, Differences Between C and C++, How
4-8
To Compile and Execute The Programs:
a).Write a C++ program to generate all the prime numbers between1 to
20.
b).Write a C++ program to find both the largest and smallest number in
1 9-12
an array of size 10.
c).Write a Program to illustrate New and Delete Keywords for dynamic
memory allocation.
Write a C++ Program to display Names, Roll No., and grades of 3 students
who have appeared in the examination. Declare the class of name, Roll
2 13-14
No. and grade. Create an array of class objects. Read and display the
contents of the array.
Given that an EMPLOYEE class contains following members: data
3 members: Employee number, Employee name, Basic, DA, IT, Net Salary 15-16
and print data members.
a).C++ program to (calculate the area of a wall using of default
constructor).
b).C++ program to (calculate the area of a wall using of parameterized
4 17-19
constructor
c). C++ program to (calculate the area of a wall using of copy
constructor
a). Write C++ program to illustrate single Inheritance
5 20-21
b).Write C++ program to illustrate Multiple inheritance
a).Write C++ program to implement compile-time polymorphism.
6 b).Write C++ program to implement run-time polymorphism. 22-24

Write C++ program to implement Stack and perform push, pop, &
7 display operation on it. 25-27

Write C++ program to implement Queue and perform enqueue,


8 28-31
dequeue, & display operation on it.
a). Write C++ program to implement Singly Linked List and perform
operation adding new node at the beginning of Linked List’ & display
node values.
9 32-35
b). Write C++ program to implement Singly Linked List and perform
operation deleting a first node from the Linked List & display node
values.
a). Write C++ program to implement Singly Linked List and perform
operation adding new node at the end of Linked List’ & display node
values.
10 36-40
b). Write C++ program to implement Singly Linked List and perform
operation deleting a last node from the Linked List & display node
values.

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |1
REVA University School of ECE

Course Title Object Oriented Programming and Data Course Type HC(Integrated)
Structures using C++
Course Code B20EN0404 Credits 3 Class IV Semester
LTP Credits Contact Contact
Total Number of
Hours Hours Assessment in
Classes Per
Lecture 2 2 2 Weightage
Semester
Tutorial - - -
Practice 1 2 2 Theory Practical IA SEE
Total 3 4 4 28 28 50% 50%

COURSE OVERVIEW:
The purpose of this course is to provide the solid foundations in the basic concepts of data
structures algorithms and C++ programming language. The Data Structures and C++ Programming
Language are a very important to develop Application Software, System Software, Operating Systems,
and Network Simulators as it employees Object Oriented Programming (OOP) aspect. This course has
important features of OOP like Polymorphism, Inheritance which are not present in C Programming
Language. Survey of fundamental data structures (array, linked lists, queue, stack) and how to use
them in C++. This course then delves deeper into the design, analysis and implementation of such data
structures.
COURSE OBJECTIVES:
The objectives of this course are: 1. Provide insights into the role of programming
Languages like C and C++ in design and development. 2. Provide a concise but through introduction to
the fundamental concepts of Classes, Objects, Inheritance and polymorphism in C++. 3. Discuss insights
into the basic concepts of data structures and algorithms. 4. Implement basic concepts about arrays,
stacks, queues and linked lists.
COURSE OUTCOMES (COs)
On successful completion of this course; the student shall be able to: Index sheet.
CO# Course Outcomes POs PSOs

CO1 Explain C++ data types and operators 1,2,3,5 1,2,3

Explain object-oriented software engineering and Use concept of classes 1,2,3,5


CO2 and objects in writing object-based programs 1,2,3
Use concept of classes and objects in writing object-based programs.
CO3 Use the concept of inheritance in writing object-oriented programs. Apply 1,2,3,5 1,2,3
the concept of run time polymorphism

CO4 Identify and classify various types of data structures 1,2,3,,5 1,2,3

CO5 Write C++ programs to implement data structures like array, stack, queue 1,2,3,5 1,2,3
and linked list.

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |2
REVA University School of ECE

BLOOM’S LEVEL OF THE COURSE OUTCOMES

Bloom’s Level

CO#
Remember Understand Apply(L3) Analyze(L4) Evaluate Create(L6)
(L1) (L2) (L5)

CO1  

CO2  

CO3  

CO4 

CO5  

COURSE ARTICULATION MATRIX

CO#/
PO10

PO11

PO12

PSO1

PSO2

PSO3
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9

POs

CO1 3 3 2 2 2 2 1

CO2 4 3 2 3 3 2 1

CO3 3 3 2 3 3 3 2

CO4 3 4 3 3 3 3 2

CO5 3 3 4 2 3 2 3

Note: 1-Low, 2-Medium, 3-High

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |3
REVA University School of ECE

Introduction
You will learn about difference between C and C++ language i.e. C vs. C++. C programming
language was developed by Dennis Ritchie in the year 1972 while C++ programming language
was developed by Bjarne Stroustrup in the year 1983. C++ is a superset of C and contains all the
features of C language. Still there are some differences between C and C++. Below the list of
some main difference between C and C++ programming language.

Following are the differences Between C and C++ :

C C++

1. C++ is non Procedural i.e Object


1. C is Procedural Language.
oriented Language.

2. The concept of virtual Functions are used


2. No virtual Functions are present in C
in C++.

3. The concept of polymorphism is used in


In C, Polymorphism is not possible.
3. C++.
Polymorphism is the most Important
Feature of OOPS.

4. Operator overloading is one of the


4. Operator overloading is not possible in C.
greatest Feature of C++.

5. Top down approach is used in 5. Bottom up approach adopted in


ProgramDesign. ProgramDesign.

6. No namespace Feature is present in 6. Namespace Feature is present in C++ for


CLanguage. avoiding Name collision.

7. Multiple Declaration of global variables are 7. Multiple Declaration of global varioables


allowed. are not allowed.

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |4
REVA University School of ECE

8. In C In C++

• scanf() Function used for Input. • Cin>> Function used for Input.
• printf() Function used for output. • Cout<< Function used for output
9. Mapping between Data and Function is
difficult and complicated.
9. Mapping between Data and Function
canbe used using "Objects

10. In C, we can call main() Function through 10. In C++, we cannot call main() Function
other Functions through other functions.

11. C requires all the variables to be defined 11. C++ allows the declaration of variable
atthe starting of a scope. anywhere in the scope i.e at time of its
Firstuse.

12. No inheritance is possible in C. 12. Inheritance is possible in C++

13. In C, malloc() and calloc() Functions are 13. In C++, new and delete operators
used for Memory Allocation and free() areused for Memory Allocating and
function for memory Deallocating. Deallocating.

14. It supports built-in and primitive 14. It support both built-in and user
datatypes. definedata types.
15. In C, Exception Handling is not 15. In C++, Exception Handling is done
present. with Try and Catch block.

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |5
REVA University School of ECE

How To Compile and Execute The Programs:


 Double click on Dev C++ to open

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |6
REVA University School of ECE

 Click on Save as, and save file with your SRN other than C drive

 Click on file, Select New source and start typing the program.

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |7
REVA University School of ECE

 Click on Execute and select Compile and Run or press F11 in keyboard

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |8
REVA University School of ECE

1a. Write a C++ program to generate all the prime numbers between 1 to 20.

#include<iostream>
using namespace std;
int main()
{
int i, j, count = 0;
cout << "\n Prime Numbers Between 1 to 20 :\n";
for (i = 2; i <= 20; i++)
{
count = 0;
for (j = 2; j < i; j++)
{
if (I % j == 0)
{
count++;
break;
}
}
if (count == 0)
{
cout << i << "\n";
}
}
return 0;
}

OUTPUT:
Prime number between 1 to 20 :
2
3
5
7
11
13
17
19

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e |9
REVA University School of ECE

1b. Write a C++ program to find both the largest and smallest number in an array of size 10.

#include<iostream>
using namespace std;
int main ()
{
int arr[10], n, i, max, min;
cout << "Enter the size of the array : ";
cin >> n;
cout << "Enter the elements of the array : ";
for (i = 0; i < n; i++)
cin >> arr[i];

max = arr[0];
for (i = 0; i < n; i++)
{
if (max < arr[i])
max = arr[i];

}
cout << "Largest element : " << max;

min = arr[0];
for (i = 0; i < n; i++)

{
if (min > arr[i])
min = arr[i];
}
cout << "Smallest element : " << min;
return 0;
}

OUTPUT:
Enter the size of the array: 5
Enter the elements of the array: 1 2 3 4 5
Largest element: 5
Smallest element: 1

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 10
REVA University School of ECE

1c. Write a Program to illustrate New and Delete Keywords for dynamic memory allocation.

//for single memory


#include <iostream>
using namespace std;

int main() {
// declare an int & float pointer
int* pointInt;
float* pointFloat;

// dynamically allocate memory


pointInt = new int;
pointFloat = new float;

// assigning value to the memory


*pointInt = 45;
*pointFloat = 45.45f;
cout << *pointInt << endl;
cout << *pointFloat << endl;

// deallocate the memory


delete pointInt;
delete pointFloat;
return 0;
}

OUTPUT
45
45.45

//for a set of memories (Program to store SGPA of n number of students and display it)
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 11
REVA University School of ECE

// memory allocation of num number of floats


ptr = new float[num];
cout << "Enter SGPA of students." << endl;

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


cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}

cout << "\nDisplaying SGPA of students." << endl;


for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
}

// ptr memory is released


delete[] ptr;
return 0;
}
OUTPUT
Enter total number of students: 4
Enter SGPA of students.
Student1: 7.6
Student2: 7.1
Student3: 8.9
Student4: 7.9
Displaying SGPA of students.
Student1 : 7.6
Student2 : 7.1
Student3 : 8.9
Student4 : 7.9

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 12
REVA University School of ECE

2. Write a C++ Program to display Names, Roll No., and grades of 3 students who have appeared in
the examination. Declare the class of name, Roll No. and grade. Create an array of class objects. Read
and display the contents of the array.

#include <iostream>
using namespace std;

class Student_Info
{
int roll_number;
char student_name[50], grade[2];

public:
void read_data(int count)
{
cout << "Enter student " << count + 1 << " information ---------\n";
cout << "Name of the Student (Max. 50 characters only): ";
cin >> student_name;
cout << "Roll Number: ";
cin >> roll_number;
cout << "Grade (O, A+, A, B+, B, C, D, F): ";
cin >> grade;
cout << "\nStudent information with roll number " << roll_number << " has saved!";
}
void display_data(int count) {
cout << "\n\n******** Student " << count + 1 << " Information ********";
cout << "\nName of the Student: " << student_name;
cout << "\nRoll Number: " << roll_number;
cout << "\nGrade Secured: " << grade;
cout << "\n---------------------------------------\n";
}
};

int main() {
Student_Info stud[3];
int i;
for (i = 0; i < 3; i++)
stud[i].read_data(i);
cout << "\n\n+++++++++++++++++++++++++++++++++++++++++++++++\n";
cout << "The information of 3 students has been saved.";
cout << "\n+++++++++++++++++++++++++++++++++++++++++++++++\n";
for (i = 0; i < 3; i++)

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 13
REVA University School of ECE

stud[i].display_data(i);
return 0;
}

OUTPUT:
--------- Enter student 1 information ---------
Name of the Student (Max. 50 characters only): sri
Roll Number: 25
Grade (O, A+, A, B+, B, C, D, F): A

Student information with roll number 25 has saved!

--------- Enter student 2 information ---------


Name of the Student (Max. 50 characters only): bharath
Roll Number: 26
Grade (O, A+, A, B+, B, C, D, F): A+

Student information with roll number 26 has saved!

--------- Enter student 3 information ---------


Name of the Student (Max. 50 characters only): malini
Roll Number: 27
Grade (O, A+, A, B+, B, C, D, F): B

Student information with roll number 27 has saved!

+++++++++++++++++++++++++++++++++++++++++++++++
The information of 3 students has been saved.
+++++++++++++++++++++++++++++++++++++++++++++++

******** Student 1 Information ********


Name of the Student: sri
Roll Number: 25
Grade Secured: A
---------------------------------------
******** Student 2 Information ********
Name of the Student: bharath
Roll Number: 26
Grade Secured: A+
---------------------------------------
******** Student 3 Information ********
Name of the Student: malini
Roll Number: 27
Grade Secured: B
--------------------------------------

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 14
REVA University School of ECE

3. Given that an EMPLOYEE class contains following members: data members: Employee
number, Employee name, Basic, DA, IT, Net Salary and print data members.

#include <iostream>
#include<conio.h>

using namespace std;

class employee
{
int emp_number;
char emp_name[20];
float emp_basic;
float emp_da;
float emp_it;
float emp_net_sal;

public:
void get_emp_details ();
float find_net_salary (float basic, float da, float it);
void show_emp_details ();
};

void employee :: get_emp_details()


{
cout << "\nEnter employee number: ";
cin >> emp_number;
cout << "\nEnter employee name: ";
cin >> emp_name;
cout << "\nEnter employee basic: ";
cin >> emp_basic;
cout << "\nEnter employee DA: ";
cin >> emp_da;
cout << "\nEnter employee IT: ";
cin >> emp_it;
}

float employee :: find_net_salary(float basic, float da, float it)


{
return (basic + da) - it;
}

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 15
REVA University School of ECE

void employee :: show_emp_details()


{
cout << "\n\n**** Details of Employee ****";
cout << "\nEmployee Name : " << emp_name;
cout << "\nEmployee number : " << emp_number;
cout << "\nBasic salary : " << emp_basic;
cout << "\nEmployee DA : " << emp_da;
cout << "\nIncome Tax : " << emp_it;
cout << "\nNet Salary : " << find_net_salary(emp_basic, emp_da, emp_it);
cout << "\n-------------------------------\n\n";
}

int main()
{
employee emp;
emp.get_emp_details();
emp.show_emp_details();
return 0;
}

OUTPUT:
Enter employee number: 112
Enter employee name: SREENIVAS
Enter employee basic: 10000
Enter employee DA: 500
Enter employee IT: 200

**** Details of Employee ****


Employee Name : SREENIVAS
Employee number : 112
Basic salary : 10000
Employee DA : 500
Income Tax : 200
Net Salary : 10300

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 16
REVA University School of ECE

4. Write a C++ Program to illustrate default constructor, parameterized constructor and copy
constructors.

a) C++ program to (calculate the area of a wall using of default constructor)

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;

public:
// default constructor to initialize variable
Wall () {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};

int main () {
Wall wall1;
return 0;
}

OUTPUT:
Creating a Wall
Length = 5.5

b) C++ program to (calculate the area of a wall using of parameterized constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 17
REVA University School of ECE

public:
// parameterized constructor to initialize variables
Wall(double len, double hgt) {
length = len;
height = hgt;
}

double calculateArea() {
return length * height;
}
};

int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}

OUTPUT:
Area of Wall 1: 90.3
Area of Wall 2: 53.55

c) C++ program to (calculate the area of a wall using of copy constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:

// initialize variables with parameterized constructor


Wall(double len, double hgt) {
length = len;
height = hgt;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 18
REVA University School of ECE

// copy constructor with a Wall object as parameter


// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}

double calculateArea() {
return length * height;
}
};

int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2


Wall wall2 = wall1;

// print areas of wall1 and wall2


cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}

OUTPUT:
Area of Wall 1: 90.3
Area of Wall 2: 90.3

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 19
REVA University School of ECE

5a. Write C++ program to illustrate single Inheritance

#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter the value of x = "; cin >> x;
}
};

class derive : public base //single derived class


{
private:
int y;
public:
void readdata()
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
};

int main()
{
derive a; //object of derived class
a.getdata();
a.readdata();
a.product();
return 0;
}

OUTPUT:
Enter the value of x = 3
Enter the value of y = 4
Product = 12

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 20
REVA University School of ECE

5b. Write C++ program to illustrate Multiple inheritance


#include<iostream>
using namespace std;

class A
{
public:
A() {
cout << "A's constructor called" << endl;
}
};

class B
{
public:
B() {
cout << "B's constructor called" << endl;
}
};

class C: public B, public A // Note the order


{
public:
C() {
cout << "C's constructor called" << endl;
}
};

int main()
{
C c;
return 0;
}

OUTPUT:
B's constructor called
A's constructor called
C's constructor called

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 21
REVA University School of ECE

6a. Write C++ program to implement compile-time polymorphism.

This type of polymorphism is also referred to as static binding or early binding. It takes place
during compilation. We use function overloading and operator overloading to achieve compile-
time polymorphism.

Function Overloading

#include <iostream>
using namespace std;
int add(int a, int b)
{
return a + b;
}

int add(int a, int b, int c)


{
return a + b + c;
}

double add(double a, double b)


{
return a + b;
}

int main()
{
int x = 3, y = 7, z = 12;
double n1 = 4.56, n2 = 13.479;
cout << "x+y = " << add(x, y) << endl;
cout << "x+y+z = " << add(x, y, z) << endl;
cout << "n1+n2 = " << add(n1, n2);
return 0;
}

Output:
x+y = 10
x+y+z = 22
n1+n2 = 18.039

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 22
REVA University School of ECE

Operator Overloading

//Using + operator to add complex numbers

#include <iostream>
using namespace std;

class complex
{
private:
float real, imag;
public:
complex(float r = 0, float i = 0)
{
real = r;
imag = i;
}
complex operator + (complex const &obj)
{
complex result;
result.real = real + obj.real;
result.imag = imag + obj.imag;
return result;
}
void display()
{
cout << real << "+i" << imag << endl;
}
};

int main() {
complex c1(12.4, 6), c2(7.9, 8);
complex c3 = c1 + c2;
c3.display();
return 0;
}

OUTPUT:
20.3+i14

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 23
REVA University School of ECE

6b. Write C++ program to implement run-time polymorphism.


Run-time polymorphism takes place when functions are invoked during run time. It is also
known as dynamic binding or late binding. Function overriding is used to achieve run-time
polymorphism.

Function Overriding in C++


When a member function of a base class is redefined in its derived class with the same
parameters and return type, it is called function overriding in C++. The base class function is said
to be overridden.

Function Overriding

#include <iostream>
using namespace std;
class base
{
public:
virtual void display ()
{
cout << "Function of base class" << endl;
}
};

class derived: public base


{
public:
void display() {
cout << "Function of derived class" << endl;
}
};

int main ()
{
derived d1;
d1.display();
return 0;
}
Output:
Function of derived class

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 24
REVA University School of ECE

7. Write C++ program to implement Stack and perform push, pop, & display operation on it.

#include<iostream>
using namespace std;

int top = -1;


int i, n;

class stack
{
int s[20];
public:
int max;
void push();
void pop();
void display();
};

void stack::push()
{
int x;
if (top == (max - 1))
cout << "Stack is full"<<endl;
else
{
cout << "enter data:";
cin >> x;
top = top + 1;
s[top] = x;
}
}

void stack::pop()
{
if (top == -1)
cout << "stack is empty"<<endl;
else
{
cout << "poped element: " << s[top];
s[top--] = '\0';
}
}

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 25
REVA University School of ECE

void stack::display()
{
cout << "displaying the contents of stack:\n";
if (top == -1)
cout << "stack is empty" << endl;
else
{
for (i = 0; i <= top; i++)
cout << s[i] << "\t";
cout << "\n";
}
}

int main()
{
stack sa;
cout << "enter the range:";
cin >> sa.max;

while (1)
{
cout << "\n1.push \n2.pop \n3.display \n4.exit";
cout << "\n enter your choice:";
cin >> n;
switch (n)
{
case 1:
sa.push();
break;
case 2:
sa.pop();
break;
case 3:
sa.display();
break;
case 4:
exit(0);
default:
cout << "Invalid option";
}
}

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 26
REVA University School of ECE

Output:
enter the range:2

1.push
2.pop
3.display
4.exit
enter your choice:3
displaying the contents of stack:
stack is empty

1.push
2.pop
3.display
4.exit
enter your choice:2
stack is empty

1.push
2.pop
3.display
4.exit
enter your choice:

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 27
REVA University School of ECE

8. Write C++ program to implement Queue and perform enqueue, dequeue, & display
operation on it.
#include<iostream>
#define SIZE 5
using namespace std;
int items[SIZE], front = -1, rear = -1, element;

class Queue
{
public:
bool isFull();
bool isEmpty();
void enQueue();
void deQueue();
void display();
};

bool Queue:: isFull()


{
return (rear == SIZE - 1);
}

bool Queue:: isEmpty()


{

return (front == -1);


}

void Queue::enQueue()
{

if (Queue:: isFull())
{
cout << "Queue is full";
} else

{
if (front == -1)
front = 0;
cout << "Enter the elemented to be inserted: ";
cin >> element;
rear++;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 28
REVA University School of ECE

items[rear] = element;
}
}

void Queue:: deQueue()


{
if (Queue::isEmpty())
{
cout << "Queue is empty" << endl;
}
else
{
cout << "Deleted elemted : " << items[front];
items[front] = '\0';
front++;
if (front > rear) {
front = -1;
rear = -1;
}
}
}

void Queue:: display()


{
if (Queue::isEmpty())
{
cout << "Queue is empty" << endl;
//cout << "\n Front = " << front << "\t Rear = " << rear << endl;
}
else
{
cout << "Queue elements are :" << endl ;
for (int i = front; i <= rear; i++)
cout << items[i] << "\t";

cout << "\n Front = " << front << "\t Rear = " << rear << endl;
}
}

int main()
{
Queue q;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 29
REVA University School of ECE

int choice;

while (1)
{
cout << "\n1.Insert \n2.Delete \n3.Display \n4.Exit";
cout << "\n enter ur choice:";
cin >> choice;
switch (choice)
{
case 1:
q.enQueue();
break;
case 2:
q.deQueue();
break;
case 3:
q.display();
break;
case 4:
exit(0);
default:
cout << "Invalid Choice";
}
}
}

Output:

1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:1
Enter the elemented to be inserted: 25

1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:1
Enter the elemented to be inserted: 25

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 30
REVA University School of ECE

1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:2
Deleted elemted : 25
1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:3
Queue elements are :
25
Front = 1 Rear = 1

1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:1
Queue elements are :
25 27
Front = 1 Rear = 2

1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:1
Enter the elemented to be inserted: 22

1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:2
Deleted elemted : 25
1.Insert
2.Delete
3.Display
4.Exit
enter ur choice:

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 31
REVA University School of ECE

9a) Write C++ program to implement Singly Linked List and perform operation adding new
node at the beginning of Linked List’ & display node values.

9b) Write C++ program to implement Singly Linked List and perform operation deleting a first
node from the Linked List & display node values.

#include<iostream>
using namespace std;

class node //struct node


{
public:
char data;
node *next;//struct node *next;
};

node *start = NULL;

class SLL
{
public:
void insert_begin();
void delete_begin();
void display();
};

int main()
{
int choice;
SLL lo;
while (1)
{
cout << endl << "---------------------------------" << endl;
cout << endl << "Operations on singly linked list" << endl;
cout << endl << "---------------------------------" << endl;
cout << "1.Insert Node at beginning" << endl;
cout << "2.Delete Node at beginning" << endl;
cout << "3.Display Linked List" << endl;
cout << "4.Exit " << endl;

cout << "Enter your choice : ";


cin >> choice;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 32
REVA University School of ECE

switch (choice)
{
case 1:
cout << "Inserting Node at Beginning: " << endl;
lo.insert_begin();
break;

case 2:
cout << "Delete Node at Beginning: " << endl;
lo.delete_begin();
break;

case 3:
cout << "Display elements of link list" << endl;
lo.display();
break;

case 4:
cout << "Exiting..." << endl;
exit(1);
break;

default:
cout << "Wrong choice" << endl;
}
}
}

void SLL::insert_begin()
{
char value;
node *nib = NULL;
nib = new node;
//int i;
if (nib == NULL)
cout << "Memory not allocated";
else
{
cout << "Enter the value to be inserted: ";
cin >> value;

nib->data = value;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 33
REVA University School of ECE

nib->next = start;
start = nib;
nib = NULL;
}
}

void SLL::delete_begin()
{
char delValue;
node *ndb = NULL;
if (start == NULL)
{
cout << "List is empty" << endl;
return;
}
else
{
ndb = start;
delValue = ndb -> data;
start = ndb -> next;
delete ndb;

cout << "Element Deleted = " << delValue << endl;


}
}

void SLL::display()
{
node *ds;
if (start == NULL)
{
cout << "The List is Empty" << endl;
return;
}
else
{
for (ds = start; ds != NULL; ds = ds->next)
{
cout << ds->data << "\t";
}
}
}

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 34
REVA University School of ECE

OUTPUT

Operations on singly linked list

---------------------------------
1.Insert Node at beginning
2.Delete Node at beginning
3.Display Linked List
4.Exit
Enter your choice : 3
Display elements of link list
The List is Empty
---------------------------------
Operations on singly linked list
---------------------------------
1.Insert Node at beginning
2.Delete Node at beginning
3.Display Linked List
4.Exit
Enter your choice : 1
Inserting Node at Beginning:
Enter the value to be inserted:

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 35
REVA University School of ECE

10a) Write C++ program to implement Singly Linked List and perform operation adding new
node at the end of Linked List’ & display node values.

10b) Write C++ program to implement Singly Linked List and perform operation deleting a last
node from the Linked List & display node values.

#include<iostream>
using namespace std;

class node //struct node


{
public:
char data;
node *next;//struct node *next;
};

node *start = NULL;

class SLL
{
public:
void insert_begin();
void delete_begin();
void insert_end();
void delete_end();
void display();
};

int main()
{
int choice;
SLL lo;
while (1)
{
cout << endl << "---------------------------------" << endl;
cout << endl << "Operations on singly linked list" << endl;
cout << endl << "---------------------------------" << endl;
cout << "1.Insert Node at End" << endl;
cout << "2.Delete Node at End" << endl;
cout << "3.Display Linked List" << endl;
cout << "4.Exit " << endl;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 36
REVA University School of ECE

cout << "Enter your choice : ";


cin >> choice;
switch (choice)
{
case 1:
cout << "Inserting Node at End: " << endl;
lo.insert_end();
break;

case 2:
cout << "Delete Node at End: " << endl;
lo.delete_end();
break;

case 3:
cout << "Display elements of link list" << endl;
lo.display();
break;

case 4:
cout << "Exiting..." << endl;
exit(1);
break;

default:
cout << "Wrong choice" << endl;
}
}
}

void SLL::insert_end()
{
char insValue;
node *nie, *ck;
nie = new node;
if (nie == NULL)
cout << "Memory not allocated";
else
{
cout << "Enter the value to be inserted: ";
cin >> insValue;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 37
REVA University School of ECE

nie->data = insValue;
nie->next = NULL;

if (start == NULL)
{
start = nie;
}
else
{
for (ck = start; ck->next != NULL; ck = ck->next)
{}
ck->next = nie;
}

nie = NULL;
ck = NULL;
}
}

void SLL::delete_end()
{
char delValue;
node *nde, *pn;
if (start == NULL)
{
cout << "List is empty" << endl;
return;
}
else if (start->next == NULL) // one node
{
nde = start;
delValue = nde -> data;
start = nde -> next;
delete nde;
}
else
{
for (nde = start; nde->next != NULL; nde = nde->next)
{
pn = nde;
}
pn->next = NULL;

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 38
REVA University School of ECE

delValue = nde -> data;


delete nde;
}
cout << "Element Deleted = " << delValue << endl;
}

void SLL::display()
{
node *ds;
if (start == NULL)
{
cout << "The List is Empty" << endl;
return;
}
else
{
for (ds = start; ds != NULL; ds = ds->next)
{
cout << ds->data << "\t";
}
}
}

OUTPUT:
Operations on singly linked list
---------------------------------
1.Insert Node at End
2.Delete Node at End
3.Display Linked List
4.Exit
Enter your choice : 1
Inserting Node at End:
Enter the value to be inserted: 3

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at End
2.Delete Node at End
3.Display Linked List

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 39
REVA University School of ECE

4.Exit
Enter your choice : 2
Delete Node at End:
Element Deleted = 3

---------------------------------

Operations on singly linked list

---------------------------------
1.Insert Node at End
2.Delete Node at End
3.Display Linked List
4.Exit
Enter your choice :

Object Oriented Programming and Data Structures using C++ B20EN0404 Sem:IV P a g e | 40
Rukmini Knowledge Park, Kattigenahalli
Yelahanka, Bengaluru - 560 064
Karnataka, India.

Ph: +91- 90211 90211, +91 80 4696 6966


E-mail: admissions@reva.edu.in

Follow us on

/REVAUniversity www.reva.edu.in

You might also like