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

C++_and_Data_Structure_Study_Material_Updated

The document provides a comprehensive overview of C++ programming concepts, including data structures, classes, functions, and file handling. It covers essential topics such as tokens, operators, control structures, inheritance, polymorphism, and various data structures like stacks, queues, and trees. Additionally, it discusses file handling techniques and asymptotic notations for analyzing algorithm efficiency.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C++_and_Data_Structure_Study_Material_Updated

The document provides a comprehensive overview of C++ programming concepts, including data structures, classes, functions, and file handling. It covers essential topics such as tokens, operators, control structures, inheritance, polymorphism, and various data structures like stacks, queues, and trees. Additionally, it discusses file handling techniques and asymptotic notations for analyzing algorithm efficiency.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

C++ and Data Structure (438C2A) - Study Material class Student {

public:
int rollNo;
void display() {
.UNIT 1 - Detailed Topic Breakdown cout << "Roll No: " << rollNo;
}
Tokens, Keywords, Identifiers, Variables };
Tokens are the smallest units in a C++ program. They include:
- Keywords: Reserved words like int, float, class. ✅ Object
- Identifiers: User-defined names like age, main.
- Constants: Fixed values like 10, 3.14.
- Operators: Symbols like +, -, *, /.  Instance of a class.
- Punctuators: Symbols like ;, {}, ().
cpp
Variables are named storage used to hold data, declared using CopyEdit
types such as int, float, etc. Student s1;
Example: int age = 21; s1.rollNo = 101;
s1.display(); // Output: Roll No: 101

Operators & Manipulators


Operators are symbols used to perform operations. Categories
include arithmetic (+, -, *), relational (==, !=), logical (&&, ||), and 🔹 2. Constructors and Destructors
bitwise (&, |).
Manipulators like setw and setprecision are used with cout to
format output.

Example:
✅ Constructor
#include <iomanip>
cout << setw(10) << setprecision(2) << 3.14159;
 Special function that initializes objects.
Expressions and Control Structures  Same name as class.
Expressions combine variables, constants, and operators to  No return type (not even void).
produce a value.  Invoked automatically.
Control structures include:
- Conditional: if, if-else, switch
cpp
- Looping: for, while, do-while
CopyEdit
- Branching: break, continue, return class Book {
public:
Example: string title;
if (a > b) { cout << "a is greater"; } Book(string t) {
title = t;
}
Functions in C++ };
Functions modularize code. The main() function is the entry point. Book b1("C++ Basics");

Function prototyping: int add(int, int);


Call by value vs call by reference affects whether changes affect
original data. ✅ Types of Constructors
Inline functions are expanded at compile-time.
Type Description Example Syntax
Friend functions access private class members. Default No parameters Book() {}
Virtual functions allow runtime polymorphism. Book(string)
Parameterized Takes arguments
Copy Constructor Copies another object Book(Book &b)
Example of virtual function: cpp
class Base { virtual void show(); }; CopyEdit
class Derived : public Base { void show() override; }; Book b2 = b1; // Calls copy constructor

UNIT 2 – Classes, Objects, Inheritance & Polymorphism


✅ Destructor
🔹 1. Classes and Objects
 Cleans up resources (opposite of constructor).
✅ Class  Same name as class, prefixed with ~.

 A blueprint to define a data type with variables cpp


(attributes) and functions (methods). CopyEdit
 Declared using the class keyword. ~Book() {
cout << "Book destroyed";
}
cpp
CopyEdit
🔹 3. Function Overloading cpp
CopyEdit
class Base {
public: int x;
};
class Derived : public Base {
✅ Function Overloading void show() { cout << x; } // Inherited
};

 Multiple functions with same name but different


parameter list.
✅ Types of Inheritance
cpp
CopyEdit Type Description Diagram
int add(int a, int b) { return a + b; }
Single One base, one derived A→B
float add(float x, float y) { return x + y; }
Multilevel Chain of inheritance A→B→C
Multiple Multiple bases to one derived A, B → C
Hierarchical One base, multiple derived A → B, C
🔹 4. Operator Overloading & Type Conversion Hybrid Combination of above types Complex

🔹 6. Pointers, Virtual Functions & Polymorphism

✅ Operator Overloading

 Redefine operators for user-defined types.


✅ Pointers to Objects
cpp
CopyEdit
class Complex {
 Can access members via -> operator.
public:
int real, imag; cpp
Complex operator + (Complex c) { CopyEdit
Complex temp; Student s1;
temp.real = real + c.real; Student* ptr = &s1;
temp.imag = imag + c.imag; ptr->rollNo = 123;
return temp;
}
};

✅ Virtual Functions

✅ Type Conversion  Declared in base class using virtual.


 Supports runtime polymorphism.
 Implicit: Automatic type change
 Explicit: Manual using cast operator cpp
CopyEdit
class Shape {
cpp public:
CopyEdit virtual void draw() { cout << "Drawing
float f = (float)5 / 2; // 2.5 Shape"; }
};

class Circle : public Shape {


🔹 5. Inheritance public:
void draw() override { cout << "Drawing
Circle"; }
};

Shape* s = new Circle();


✅ Concept s->draw(); // Outputs: Drawing Circle

 One class derives from another.


 Enables code reuse and hierarchical classification. ✅ Polymorphism

 Means many forms.


 Compile-time: Function/operator overloading
 Runtime: Virtual functions and inheritance
✅ Syntax
#include <fstream>
ofstream file("data.txt");
file << "Hello, File!";
file.close();
🔹 7. Managing Console I/O

✅ Opening and Closing Files

✅ Standard Streams
cpp
CopyEdit
ifstream fin;
 cin → standard input
fin.open("input.txt");
 cout → standard output if (!fin) {
 cerr → unbuffered error cout << "File not found!";
}
 clog → buffered error
fin.close();

You can also open files using constructor:

✅ Formatting with iomanip cpp


CopyEdit
ifstream fin("input.txt");
cpp
CopyEdit
#include <iomanip>
cout << setw(10) << setprecision(3) << 45.6789;
✅ Detecting End-of-File (EOF)

cpp
📊 Diagrams CopyEdit
while (!fin.eof()) {
string line;
🔸 Types of Inheritance (Example: Multilevel) getline(fin, line);
cout << line << endl;
}
plaintext
CopyEdit
Class A

Class B ✅ File Pointers & Their Manipulation

Class C
 seekg() – move get pointer
 seekp() – move put pointer
🔸 Polymorphism (Virtual Function Dispatch)
 tellg() – get current get pointer position
 tellp() – get current put pointer position
plaintext
CopyEdit
Base* ptr → [ Derived Object ] cpp
CopyEdit
|→ virtual table → fin.seekg(0, ios::end);
int length = fin.tellg();
Derived::show()UNIT 3 – File Handling & Basic Data
Structures

✅ Updating File Content

🔹 1. File Handling in C++


cpp
CopyEdit
fstream file("data.txt", ios::in | ios::out);
file.seekp(0);
file << "Updated Content";
✅ File Streams file.close();

To handle files, C++ provides the <fstream> library with three


classes: ✅ Error Handling

Stream Purpose cpp


ifstream Input file stream CopyEdit
ofstream Output file stream if (!fin) {
fstream Both input and output cerr << "File could not be opened";
}
cpp
CopyEdit
✅ Command-Line Arguments Notation Meaning Example
Θ(n) Average-case time Balanced Algorithms
Used to pass input filenames at runtime.

cpp ✅ Examples with Graph Shapes


CopyEdit
int main(int argc, char* argv[]) {
ifstream fin(argv[1]);  O(n²) – Nested loops
string word;
while (fin >> word) {  O(log n) – Binary search
cout << word << endl;  O(1) – Constant time access (like accessing array by
} index)
}

🔹 2. Introduction to Data Structures


🔹 4. Arrays and Ordered Lists

✅ What is a Data Structure?


✅ Array Declaration

 A way of organizing and storing data to perform


cpp
operations efficiently. CopyEdit
int numbers[5] = {1, 2, 3, 4, 5};

✅ Types of Data Structures ✅ Basic Operations

Type Examples Operation Code Example


Primitive int, float, char, bool for (int i = 0; i < 5; i++) cout <<
Traversal numbers[i];
Composite Array, Structure, Class, Union
Insertion Add value at a specific index
Deletion Shift elements to remove an index
Search Linear or binary search
✅ Operations on Data Structures

 Traversal – Visit each element ✅ Ordered List


 Insertion – Add new element
 Deletion – Remove element  A sorted array or list where elements follow an order.
 Searching – Find an element  Searching is faster (Binary Search)
 Sorting – Arrange in order

cpp
CopyEdit
int sortedArr[] = {10, 20, 30, 40};

🔹 3. Asymptotic Notations

📊 Diagrams

🔸 File Pointer Movement


✅ Purpose
plaintext
CopyEdit
 To describe time and space complexity of algorithms. File: data.txt
-----------------------
H e l l o W o r l d !
^ ^
seekg(0) seekg(end)

✅ Types of Notation
🔸 Time Complexity Graphs

Notation Meaning Example


O(n) Worst-case time Linear Search plaintext
CopyEdit
Ω(n) Best-case time Linear Search |
T(n) |
| O(n^2)
| /
| /
✅ Recursion Using Stack
| / O(n)
|----------
n Recursive calls are pushed onto the call stack automatically.

cpp
CopyEdit
int factorial(int n) {
if (n == 0) return 1;
📘 UNIT 4 – Stacks, Queues & Linked Lists
return n * factorial(n - 1);
}

🔹 1. Stacks 🔹 2. Queues

✅ Definition ✅ Definition

 A LIFO (Last In, First Out) data structure.  A FIFO (First In, First Out) data structure.
 Access is only at one end: top of the stack.  Insertion at rear, deletion from front.

✅ Basic Operations ✅ Operations

Operation Purpose Operation Description


push(x) Add element on top enqueue(x) Insert at rear
pop() Remove top element dequeue() Remove from front
top() Get top element cpp
CopyEdit
isEmpty() Check if stack is empty
queue<int> q;
cpp q.push(10); // enqueue
CopyEdit q.pop(); // dequeue
stack<int> st;
st.push(10);
st.pop();
int x = st.top();
✅ Applications

✅ Applications
 Job scheduling
 CPU & printer queues
 Breadth-first search
 Reversing strings
 Expression evaluation
 Recursion
 Infix to Postfix conversion
 Maze solving / Backtracking ✅ Circular Queue

 Wraps around to reuse space.

cpp
✅ Infix to Postfix Conversion
CopyEdit
rear = (rear + 1) % size;
 Convert: A + B * C → Postfix: A B C * +

plaintext 🔹 3. Singly Linked List


CopyEdit
Steps:
1. Read operand → output
2. Read operator → push (obey precedence)
3. On '(', push; on ')', pop until '('
✅ Structure
cpp ✅ Operations
CopyEdit
struct Node {
int data;  Insert at front/end
Node* next;
};
 Delete node
 Forward/backward traversal

✅ Operations

✅ Applications
 Insertion (beginning, middle, end)
 Deletion (by value or position)
 Traversal  Browser forward/back buttons
 Music playlist navigation
cpp  Undo/redo functionality
CopyEdit
Node* head = new Node{10, nullptr};
head->next = new Node{20, nullptr};

📊 Diagrams
✅ Applications
🔸 Stack (LIFO)
 Dynamic memory use
 Implementing stack/queue plaintext
CopyEdit
 Polynomial representation | 40 | <- top
| 30 |
| 20 |
|____|

✅ Polynomial Representation & Addition 🔸 Queue (FIFO)

Each node holds a term: plaintext


CopyEdit
Front → [10][20][30] ← Rear
cpp
CopyEdit
struct Term { 🔸 Singly Linked List
int coeff;
int expo;
Term* next; plaintext
}; CopyEdit
[10|*] → [20|*] → [30|NULL]

For addition:
🔸 Doubly Linked List

 Match terms with same exponent plaintext


 Add coefficients CopyEdit
NULL ← [10] ↔ [20] ↔ [30] → NULL

🔹 4. Doubly Linked List


📘 UNIT 5 – Trees, Graphs & Hashing

✅ Structure
🔹 1. Binary Trees

cpp
CopyEdit
struct Node {
int data;
Node* prev; ✅ Definition
Node* next;
};
 A tree structure where each node has at most two
children: left and right.
 The top node is the root. 2. Take all subsequent siblings as the right child of the
previous one.

plaintext
CopyEdit
Forest:
✅ Node Structure A B
/ \ \
C D E
cpp
CopyEdit
Binary Tree:
struct Node {
A
int data;
/
Node* left;
C
Node* right;
\
};
D

✅ Tree Traversals
🔹 3. Graphs

Type Order
Inorder Left → Root → Right
Preorder Root → Left → Right
Postorder Left → Right → Root ✅ Definition
cpp
CopyEdit
void inorder(Node* root) {  A graph is a collection of vertices (nodes) and edges
if (root) { (connections).
inorder(root->left);
cout << root->data << " ";
inorder(root->right); ✅ Types
}
}
Type Description
Directed Edges have direction
Undirected No direction in edges
✅ Example Tree Structure Weighted Edges have weights
Unweighted All edges are equal
plaintext
CopyEdit
10
/ \ ✅ Representations
5 15

1. Adjacency Matrix
Inorder: 5 10 15
Preorder: 10 5 15
cpp
Postorder: 5 15 10
CopyEdit
int adj[5][5]; // 2D array

2. Adjacency List

🔹 2. Conversion of Forest to Binary Tree


cpp
CopyEdit
vector<int> graph[10];
graph[1].push_back(2);

✅ Forest: A set of disjoint trees.

🔹 4. Graph Traversals
To convert into a binary tree:

 The left child represents the first child.


 The right child represents the next sibling.
✅ Depth-First Search (DFS)

 Uses stack or recursion.

✅ Steps
cpp
CopyEdit
1. Take the first child as the left child.
void DFS(int v, vector<bool>& visited, pq.push({dist[v], v});
vector<int> graph[]) { }
visited[v] = true; }
for (int u : graph[v]) }
if (!visited[u]) }
DFS(u, visited, graph);
}

🔹 6. Hashing

✅ Breadth-First Search (BFS)

 Uses queue.
✅ Definition
cpp
CopyEdit
void BFS(int start, vector<int> graph[]) {
 Technique to map data (key) to a fixed size table
(index) using a hash function.
queue<int> q;
vector<bool> visited(10, false);
q.push(start);
visited[start] = true;

while (!q.empty()) {
int v = q.front(); q.pop(); ✅ Hash Function Example
for (int u : graph[v]) {
if (!visited[u]) { cpp
visited[u] = true; CopyEdit
q.push(u); int hashFunction(int key, int size) {
} return key % size;
} }
}
}

✅ Collision Handling
🔹 5. Dijkstra’s Algorithm – Shortest Path
Method Description
Linear Probing Search next available spot
Chaining Use linked list at each index

✅ Purpose

✅ Chaining Example
 Finds shortest paths from a source vertex to all other
vertices in a weighted graph with non-negative edges.
cpp
CopyEdit
vector<int> hashTable[10];

void insert(int key) {


int index = hashFunction(key, 10);
✅ Basic Idea hashTable[index].push_back(key);
}
 Use priority queue (min-heap) and greedy approach.

cpp 📊 Diagrams
CopyEdit
void dijkstra(int V, int src, vector<pair<int,
int>> graph[]) { 🔸 Binary Tree Traversals
vector<int> dist(V, INT_MAX);
priority_queue<pair<int, int>,
plaintext
vector<pair<int, int>>, greater<>> pq;
CopyEdit
A
dist[src] = 0;
/ \
pq.push({0, src});
B C
Inorder: B A C
while (!pq.empty()) {
Preorder: A B C
int u = pq.top().second;
Postorder: B C A
pq.pop();

for (auto edge : graph[u]) { 🔸 Graph (Adjacency List)


int v = edge.first;
int wt = edge.second;
plaintext
if (dist[v] > dist[u] + wt) { CopyEdit
dist[v] = dist[u] + wt; 1 -> 2 -> 3
2 -> 4
3 -> 4

🔸 Hash Table (Chaining)

plaintext
CopyEdit
Index | Elements
------|---------
0 |
1 | 11 → 21
2 | 12 → 22

You might also like