Basic Data Structures using C++ __ 23CSH-103
Basic Data Structures using C++ __ 23CSH-103
(23CSH-103)
Compiled by : Subhayu
1. Fundamentals of C++
Features of Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that uses
objects and classes. The key features of OOP are:
○ Data and functions are separate, and the main focus is on the
sequence of tasks.
○ Examples: C, Pascal.
Example: In C++, we define a class Car with properties and methods, while in C,
we would write functions to perfor m operations on car-related data.
class Car {
public:
string model;
int year;
};
In a Procedure-Oriented language like C, you'd write a function that manipulates
data directly, without encapsulating it in objects.
struct Car {
char model[50];
int year;
};
● Cin: The cin stream is used to take input from the user.
Example:
#include <iostream>
int main() {
int age;
retur n 0;
Introduction to Namespace
A namespace in C++ is used to a void name conflicts by grouping identifiers (like
functions, classes, variables) under a unique name.
#include <iostream>
namespace MyNamespace {
void greet() {
int main() {
MyNamespace::greet();
retur n 0;
}
In the above example, the greet() function is part of the MyNamespace namespace,
and we call it using the scope resolution operator ::.
class Car {
public:
string model;
int year;
};
Creating Objects
An object is an instance of a class. You can c reate an object using the class name.
myCar.model = "Toyota";
myCar.year = 2020;
myCar.dri ve();
● Outside the class: Functions can be defined outside the class definition using
the scope resolution operator ::.
Example:
class Car {
public:
string model;
};
Access Specifiers
C++ provides three access specifiers for class members:
● Public: Members are accessible from anywhere.
● Protected: Members are accessible within the class and deri ved classes.
class Car {
public:
string model;
pri vate:
int year;
};
Inline Function
An inline function is defined using the keyword inline. It suggests to the compiler
to replace the function call with the function's body.
class Car {
public:
};
class Car {
public:
string model;
Car(string m) { // Constructor
model = m;
};
class Car {
public:
~Car() { // Destructor
};
3. Inheritance
Concept of Inheritance
Inheritance is the mechanism by which one class can inherit properties and
beha viors from another class. This allows code reuse and organization.
● Base class: The class whose properties and methods are inherited.
● Derived class: The class that inherits the properties and methods of the base
class.
Example:
class Vehicle {
public:
void start() {
};
public:
};
Modes of Inheritance
C++ supports se veral modes of inheritance:
● Single Inheritance: A deri ved class inherits from a single base class.
● Multiple Inheritance: A deri ved class inherits from more than one base
class.
● Multilevel Inheritance: A deri ved class inherits from another deri ved class.
● Hierarchical Inheritance: Multiple deri ved classes inherit from the same
base class.
Examples:
● Single Inheritance:
● Multiple Inheritance:
Types of Inheritance
● Public Inheritance: Inherited members remain accessible in the deri ved
class as they are in the base class.
● Protected Inheritance: Inherited members are accessible within the deri ved
class, but not outside it.
Example:
class Car : public Vehicle { // Public inheritance
};
Question Bank for Unit 1 : Fundamentals of C++
2-Mark Questions (Revised):
1. Define Object-Oriented Programming (OOP) and explain how
encapsulation is implemented in C++.
2. Explain the difference bet ween the cin and cout streams in C++, including
their purpose and usage with examples.
3. What are the ad vantages of using a namespace in C++? Illustrate with an
example of a potential naming conflict and how a namespace resol ves it.
4. What are the different access specifiers a vailable in C++? Provide a brief
example demonstrating each access specifier.
5. What is the role of a constructor in C++? Differentiate bet ween a default
constructor and a parameterized constructor with an example.
2. Create a C++ class Student that contains the attributes name, age, and
marks. Write a constructor to initialize these values and a method to display
the student details. Discuss how the constructor and destructor work in this
context.
3. What is inheritance in C++? Explain the concept of multile vel inheritance
and provide a C++ program example demonstrating multile vel inheritance
in vol ving classes Animal, Mammal, and Dog.
4. Explain the difference bet ween a function declared inside a class and a
function declared outside a class. In your answer, desc ribe how member
functions can be defined inside and outside a class in C++, and when each
approach is prefer red.
5. What is an inline function in C++? Discuss the scenarios where an inline
function is beneficial, and explain how the compiler decides whether to
actually inline a function. Provide an example of defining and using an
inline function.
10-Mark Questions :
1. Write a detailed C++ program that demonstrates the c reation and use of
classes and objects. Define a Car class with data members like model, year,
and price. Implement multiple constructors, member functions to set and
get values, and a function to display car details. Ensure the program
includes at least t wo objects of the Car class and displays their details.
5. Explain in detail how namespaces are used to organize code and pre vent
clashes bet ween identifiers. Provide a comprehensi ve C++ example
demonstrating the c reation and use of namespaces, and show how it can
a void name conflicts in a program with multiple libraries or modules.
UNIT-2: Elementary Data Structures
Contact Hours: 10
2. Arrays
Basic Terminology
● Array: An ar ray is a collection of elements, all of the same data type, stored
in contiguous memory locations.
● Index: The position of an element in the ar ray. Ar ray indices typically start
from 0.
Example of an ar ray:
int ar r[5] = {10, 20, 30, 40, 50}; // Declaring and initializing an ar ray
In this ar ray, the element 10 is at index 0, 20 at index 1, and so on.
cout << ar r[i] << " "; // Outputs all elements of the ar ray
Example of Insertion:
int ar r[5] = {10, 20, 30, 40, 50};
Searching in Arrays
● Linear Search: In a linear search, each element of the ar ray is checked one
by one until the desired element is found.
if (ar r[mid] == key) retur n mid; // Retur n the index if key is found
Sorting in Arrays
● Bubble Sort: Bubble sort compares adjacent elements and swaps them if they
are in the wrong order. This process is repeated for each element until the
ar ray is sorted.
}
● Insertion Sort: In insertion sort, elements are picked one by one and inserted
into their cor rect position in the sorted portion of the ar ray.
int j = i - 1;
j--;
● Selection Sort: In selection sort, the smallest element is selected from the
unsorted part and swapped with the first unsorted element.
int minIndex = i;
for (int j = i + 1; j < size; j++) {
minIndex = j;
swap(ar r[i], ar r[minIndex]); // Swap the smallest element with the first
unsorted element
● Declaration:
● Initialization:
● Traversing 2D Array:
cout << ar r[i][j] << " "; // Output each element in the 2D ar ray
3. Pointers
Introduction to Pointers
A pointer is a variable that stores the memory address of another variable.
Pointers are essential for dynamic memory allocation, ar rays, and data
structures like linked lists.
2. Next: A pointer that points to the next node in the list.
Linked lists allow efficient insertions and deletions but require extra memory for
pointers.
CopyEdit
struct Node {
int data;
};
A singly linked list is where each node points to the next node, and the last node
points to NULL.
Question Bank for Unit 2 : Elementary Data Structures
2-Mark Questions
1. What is the difference bet ween static and dynamic data structures? Provide
an example of each type and explain their use cases.
2. Define the concept of time complexity in algorithms. What is the time
complexity of a linear search algorithm, and why is it considered inefficient
for large data sets?
3. What is the significance of using a pointer in C++? How does a pointer
help in managing dynamic memory allocation in the context of a linked
list?
4. Explain what a 2D ar ray is. How are elements accessed in a 2D ar ray in
C++? Illustrate with a simple example of initializing and printing a 2D
ar ray.
5. Desc ribe the insertion sort algorithm. How does it work? What is its time
complexity in the worst case, and how does it compare to bubble sort?
5-Mark Questions
1. Write a detailed explanation of the differences bet ween linear and
non-linear data structures. Create a real-life scenario where each type
would be used, explaining the ad vantages of using one over the other in
your example.
3. Desc ribe the binary search algorithm. How does it compare to linear search
in ter ms of perfor mance? Write a C++ program that implements binary
search on a sorted ar ray, and explain the steps with sample data.
4. Create a C++ program that demonstrates the use of a linked list. Implement
functions to insert and delete elements at the beginning, middle, and end of
the list. Provide a clear explanation of how pointers are used to manage the
linked list structure.
5. Write and explain a C++ program to implement bubble sort on a list of
integers. After sorting the list, analyze its time complexity and compare it
with the time complexities of other sorting algorithms like insertion sort and
quicksort. Which one would be more efficient for large data sets?
10-Mark Questions
1. Explain the concept of algorithm complexity in detail. Discuss both time
complexity and space complexity, comparing different sorting algorithms
like bubble sort, insertion sort, and selection sort. Write C++ programs to
demonstrate each sorting algorithm, and analyze their efficiency by
running them on data sets of different sizes. Include a conclusion on when
to use each sorting technique based on your analysis.
4. Design a program that reads a list of integers and perfor ms the following
tasks:
○ Sort the ar ray using any one sorting algorithm (e.g., bubble sort,
quicksort).
5. Discuss how sorting and searching algorithms impact the overall
perfor mance of the program and how different algorithms beha ve as the
input size inc reases.
6. Discuss the use of pointers in C++ for dynamic memory management.
Write a program that c reates a dynamic 2D ar ray using pointers.
Implement functions to initialize the ar ray, assign values, and print the
ar ray. Afterward, explain how memory is managed in this scenario, how
memory leaks can occur, and how to pre vent them using proper memory
deallocation techniques.
UNIT-3: Stack, Queue, Linked List
Contact Hours: 10
1. Linked List
A linked list is a collection of elements (called nodes) that are connected using
pointers. Unlike ar rays, where data is stored in contiguous memory locations,
linked lists use non-contiguous memory locations and ha ve the ability to grow or
shrink dynamically, making them more flexible for certain types of data
management.
1. Data: The infor mation stored in the node (could be integers, strings, etc.).
2. Next Pointer: A reference or pointer to the next node in the list. In the last
node, this pointer points to NULL (or nullptr in C++).
};
○ Structure: Each node has data and a pointer to the next node.
2. Doubly Linked List: Each node contains t wo pointers: one pointing to the
next node and another pointing to the pre vious node. This allows tra versal
in both directions, making certain operations easier (e.g., deletion from both
ends).
○ Structure: Each node has data, a pointer to the next node, and a
pointer to the pre vious node.
○ Example: NULL <- Head <-> Node1 <-> Node2 -> NULL
3. Circular Linked List: In this type of list, the last node points back to the first
node, for ming a circular structure. It can be either singly or doubly linked.
○ Structure: The last node points back to the head or first node.
Memory Representation:
● Singly Linked List: The nodes are scattered in memory, and each node's next
pointer holds the memory address of the next node.
● Doubly Linked List: Each node has t wo pointers: one for the next node and
one for the pre vious node. This makes it easier to tra verse both ways but
requires more memory per node.
○ At the beginning: You c reate a ne w node and make its next pointer
point to the cur rent head. Then, the head pointer is updated to point
to the ne w node.
○ At the end: You tra verse to the last node, and then add the ne w node
by making the last node's next pointer point to the ne w node.
○ At a specific position: You tra verse the list until the desired position
and adjust the pointers to insert the ne w node at that position.
ne wNode->data = value;
2. Deletion:
○ From the beginning: The head pointer is moved to the next node,
effecti vely removing the first node.
○ From the end: Tra verse the list to find the second-to-last node and set
its next pointer to NULL.
○ At a specific position: Tra verse the list to the node before the one you
want to delete, adjust the pointers to exclude the node, and free the
memory.
if (head != NULL) {
3. Traversal: To visit all nodes in the list, you start from the head and follow the
next pointers until you reach NULL.
Example of traversal:
void tra verse(Node* head) {
}
}
2. Stacks
A stack is a linear data structure that follows the Last In, First Out (LIFO)
principle, where the last element added to the stack is the first one to be removed.
Basic Terminology:
● Push: Adds an element to the top of the stack.
● Top/Peek: Retur ns the top element of the stack without removing it.
int stack[MAX];
// Push operation
if (top == MAX - 1) {
} else {
stack[++top] = value;
// Pop operation
int pop() {
if (top == -1) {
retur n -1;
} else {
retur n stack[top--];
// Peek operation
int peek() {
if (top == -1) {
retur n -1;
} else {
retur n stack[top];
Node* next;
};
ne wNode->data = value;
ne wNode->next = top;
top = ne wNode;
// Pop operation
int pop() {
if (top == NULL) {
retur n -1;
} else {
top = top->next;
delete temp;
retur n value;
}
Applications of Stacks:
1. Expression Evaluation: Stacks are widely used for e valuating postfi x and
prefi x expressions.
2. Infix to Postfix Conversion: When expressions are written in infi x notation
(like (a + b)), stacks can be used to con vert them into postfi x for m (like a b +),
which is easier to e valuate programmatically.
3. Queue
A queue is a linear data structure that follows the First In, First Out (FIFO)
principle, meaning the first element added to the queue is the first one to be
removed.
Types of Queues:
1. Linear Queue: A basic queue where elements are added at the rear and
removed from the front.
2. Circular Queue: In a circular queue, the last element points to the first
element, for ming a circular structure. This a voids the problem of wasted
space in linear queues when elements are dequeued from the front.
Operations on Queue:
1. Enqueue: Adds an element to the rear of the queue.
2. Dequeue: Removes an element from the front of the queue.
3. Front: Retur ns the element at the front without removing it.
int queue[MAX];
// Enqueue operation
if (rear == MAX - 1) {
} else {
// Dequeue operation
int dequeue() {
retur n -1;
} else {
retur n queue[front++];
int queue[MAX];
// Enqueue operation
void enqueue(int value) {
} else {
queue[rear] = value;
// Dequeue operation
int dequeue() {
if (front == -1) {
retur n -1;
} else {
if (front == rear) {
} else {
}
retur n value;
Applications of Queues:
1. Scheduling: Queues are often used in scheduling problems (e.g., CPU
scheduling, printer queues).
2. Buffering: In systems with buffer management (like I/O operations), queues
help in managing the flow of data.
Question Bank for Unit 3 : Linked Lists, Stacks & Queues
2-MARK QUESTIONS:
1. Define a stack data structure and explain the concept of LIFO (Last In, First
Out) with a simple example.
2. How does a queue implement the FIFO (First In, First Out) principle? Gi ve
an example of its real-world application.
3. What is a linked list? How is it different from an ar ray in ter ms of memory
allocation and access?
4. Explain the difference bet ween a linear queue and a circular queue. When
is a circular queue prefer red over a linear queue?
5. What are the key operations associated with a stack? Briefly explain the
purpose of each operation (Push, Pop, Peek).
5-MARK QUESTIONS:
1. Compare the structure and operations of a stack with that of a queue.
Provide real-world scenarios where each data structure is useful.
2. Explain the process of tra versing a singly linked list. How would you
tra verse it iterati vely and recursi vely? Provide examples.
5. How can a stack be used to e valuate postfi x expressions? Illustrate the
process with an example of a postfi x expression and explain step-by-step
how the stack is utilized.
10-MARK QUESTIONS:
1. Compare and contrast the stack and queue data structures in ter ms of their
structure, operations, and use cases. Discuss scenarios where one would be
prefer red over the other, and include examples like expression e valuation,
undo operations, and scheduling tasks.
4. Implement a C++ program that con verts an infi x expression to a postfi x
expression using a stack. Provide detailed step-by-step examples to
demonstrate the con version process.
5. Design and implement a double-ended queue (Deque) using both an ar ray
and a doubly linked list. Compare both implementations, highlighting the
ad vantages and disad vantages of each with respect to operations like
insertion, deletion, and accessing elements from both ends.