SEMESTER EXAM COMPLETE REFERENCE NOTES
PROGRAMMING FUNDAMENTALS
Complete Detailed Notes with Definitions, Theory & Code Examples
■ Unit 1 C LANGUAGE History · Structure · Data Types · Operators · Control Flow · Functions · Arrays · Pointers · Strings · File I
■ Unit 2 C++ LANGUAGE OOP Introduction · Classes · Objects · Constructors · Inheritance · Polymorphism · Overloading · Overrid
■ Unit 3 JAVA LANGUAGE JVM/JDK/JRE · Syntax · OOP in Java · Packages · Exception Handling · Collections · Multithreading · Ap
■ Unit 4 PYTHON Syntax · Data Types · Collections · Functions · Modules · File I/O · OOP in Python · Libraries (NumPy, Pa
■ Unit 5 DATA STRUCTURESArrays · Linked Lists · Stacks · Queues · Trees · Graphs · Hashing · All Algorithms with Complexity
■ Unit 6 OOP CONCEPTS 4 Pillars Deep Dive · Encapsulation · Abstraction · Inheritance · Polymorphism · Abstract Class vs Interfa
■ Unit 7 AI / ML / BLOCKCHAIN
AI Basics · ML Types · Neural Networks · Deep Learning · NLP · Blockchain · Cryptography · Cybersecur
UNIT 1: C PROGRAMMING LANGUAGE – COMPLETE
NOTES
■ 1.1 Introduction to C Language
■ C Language C is a general-purpose, procedural, structured, middle-level programming
language developed by Dennis M. Ritchie at Bell Telephone Laboratories in 1972.
It provides low-level memory access with high-level language constructs.
Key Facts about C:
• Developer: Dennis M. Ritchie (Bell Labs, 1972)
• Predecessor: BCPL → B → C
• Standard: ANSI C (C89/C90), C99, C11, C18
• File Extension: .c for source files, .h for header files
• Paradigm: Procedural / Structured programming
• Nature: Compiled language — javac translates entire source to machine code before execution
• Called: 'Mother of all programming languages' — C++, Java, Python all have C roots
• Portability: Highly portable — same code runs on different platforms with minor changes
■ EXAM TIP: C was originally developed to rewrite the UNIX operating system. The UNIX OS was first written in
Assembly; Ritchie rewrote it in C, making it the first OS written in a high-level language.
■ 1.2 Structure of a C Program
Every C program has a specific structure. Understanding each section is essential for writing and debugging
programs:
// Complete C Program Structure
/* Section 1: Documentation (Comments) */
/* Program: Hello World | Author: Your Name | Date: 2025 */
/* Section 2: Preprocessor Directives */
#include // Standard Input-Output header
#include // Standard Library header
#define MAX 100 // Symbolic constant (macro)
/* Section 3: Global Declarations */
int globalVar = 0; // Accessible from all functions
/* Section 4: Function Prototypes */
int add(int a, int b); // Declaration before main()
/* Section 5: Main Function */
int main() {
int x = 10, y = 20; // Local variables
printf("Sum = %d\n", add(x,y)); // Function call
return 0; // 0 = successful execution
}
/* Section 6: User-Defined Functions */
int add(int a, int b) {
return a + b; // Function definition
Section Purpose Example
Documentation Comments explaining the program /* Author: XYZ */
Preprocessor
Instructions to compiler before compilation #include, #define
Directives
Global Declarations Variables/functions accessible throughout int count = 0;
main() Function Entry point; execution starts here int main() { }
User Functions Custom reusable code blocks int square(int n)
■ 1.3 Data Types in C
■ Data Type A data type defines the type of value a variable can hold, the amount of memory it
occupies, and the range of values it can represent. In C, every variable must be
declared with a data type.
Primary (Built-in) Data Types:
Size Format
Data Type Range Example
(bytes) Specifier
-128 to 127 (signed) / 0 to 255
char 1 %c char grade = 'A';
(unsigned)
int 4 %d -2,147,483,648 to 2,147,483,647 int marks = 85;
short 2 %hd -32,768 to 32,767 short count = 100;
long 8 %ld Very large integers long pop = 1400000000L;
float 4 %f ~3.4×10^-38 to 3.4×10^38 (6-7 digits) float pi = 3.14f;
~1.7×10^-308 to 1.7×10^308 (15-16
double 8 %lf double price = 99.99;
digits)
long double 10-16 %Lf Extended precision long double x = 3.14L;
No value; used for functions returning
void 0 — void greet(){}
nothing
Derived & User-Defined Data Types:
Type Keyword Description Example
Collection of same-type
Array — elements in contiguous int arr[5];
memory
Type Keyword Description Example
Stores memory address of
Pointer * int *ptr;
another variable
Groups different data
Structure struct struct Student { };
types under one name
Like struct but all members
Union union share same memory union Data { };
location
User-defined set of named
Enumeration enum enum Color {RED,BLUE};
integer constants
Creates alias for existing
Typedef typedef typedef int INTEGER;
data type
■ 1.4 Variables, Constants & Literals
■ Variable A variable is a named memory location whose value can change during program
execution. It has a name (identifier), data type, and value. In C, all variables must
be declared before use.
■ Constant A constant is a value that cannot be changed during program execution.
Constants can be defined using #define preprocessor directive or const keyword.
// Variables, Constants & Literals
// Variable declaration and initialization
int age; // Declaration only (uninitialized - garbage value)
int age = 25; // Declaration + initialization
int x, y, z; // Multiple variable declaration
int a = 1, b = 2; // Multiple initialization
// Constants
#define PI 3.14159 // Preprocessor constant (no memory, text replacement)
const int MAX = 100; // Constant variable (has memory, type-checked)
// Literals (literal values written directly in code)
int a = 42; // Integer literal
float b = 3.14f; // Float literal
char c = 'A'; // Character literal (single quotes)
char s[] = "Hello"; // String literal (double quotes)
int h = 0xFF; // Hexadecimal literal
int o = 077; // Octal literal (starts with 0)
int bi = 0b1010; // Binary literal (C99 with some compilers)
■ 1.5 Operators in C – Complete Reference
■ Operator An operator is a symbol that tells the compiler to perform a specific mathematical,
relational, logical, or bitwise operation on operands. C has rich set of operators.
Category Operators Associativity Description & Example
Arithmetic +−*/% Left to Right Add, Sub, Mul, Div, Modulus → 5%2 = 1
Unary plus/minus, increment/decrement, logical
Unary + − ++ −− ! ~ Right to Left
NOT, bitwise NOT
= += −= *= /= %= &= |=
Assignment Right to Left x+=5 same as x=x+5
^= <<= >>=
Relational == != > < >= <= Left to Right Compare; return 1(true) or 0(false) → 5>3 = 1
Logical && || ! Left to Right Logical AND, OR, NOT → (a>0 && b>0)
Bitwise & | ^ ~ << >> Left to Right Bit-level operations → 5&3 = 1 (101 AND 011 = 001)
Conditional ?: Right to Left Ternary → (a>b) ? a : b returns larger of a,b
sizeof sizeof() Right to Left Returns size in bytes → sizeof(int) = 4
Address-of & Right to Left Returns address of variable → &x; gives address of x
Gets value at pointer address → *ptr gives value ptr
Dereference * Right to Left
points to
Evaluates expressions L to R, returns rightmost →
Comma , Left to Right
a=(1,2,3) gives a=3
Array subscript [] Left to Right Access array element → arr[2] = 3rd element
Function call () Left to Right Invokes function → printf()
Member access . Left to Right Access struct member → [Link]
Pointer member −> Left to Right Access struct via pointer → ptr->name
Operator Precedence (Highest to Lowest):
// Operator Precedence Chart
Highest: () [] -> . (Postfix operators)
! ~ ++ -- (type) sizeof & * (Unary/prefix - R to L)
* / % (Multiplicative)
+ - (Additive)
<< >> (Bitwise shift)
< <= > >= (Relational)
== != (Equality)
& (Bitwise AND)
^ (Bitwise XOR)
| (Bitwise OR)
&& (Logical AND)
|| (Logical OR)
?: (Ternary/Conditional - R to L)
= += -= *= /= etc. (Assignment - R to L)
Lowest: , (Comma)
■ 1.6 Control Flow Statements
Control flow statements determine the order in which program statements are executed. Without them,
execution is purely sequential (top to bottom).
1. Decision Making Statements:
// Decision Making in C
// if-else if-else chain
int marks = 75;
if (marks >= 90) {
printf("Grade A");
} else if (marks >= 75) {
printf("Grade B"); // This executes
} else if (marks >= 60) {
printf("Grade C");
} else {
printf("Fail");
// switch-case (for discrete values)
int day = 3;
switch(day) {
case 1: printf("Monday"); break; // break prevents fall-through
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break; // This executes
default: printf("Invalid");
// Ternary Operator (shorthand if-else)
int a=10, b=20;
int max = (a > b) ? a : b; // max = 20
2. Loop Statements:
// Loop Types in C
// for loop - when number of iterations is known
for (int i = 1; i <= 5; i++) {
printf("%d ", i); // Output: 1 2 3 4 5
}
// while loop - pre-test (condition checked BEFORE each iteration)
int n = 1;
while (n <= 5) {
printf("%d ", n); // Output: 1 2 3 4 5
n++;
// do-while loop - post-test (executes AT LEAST ONCE)
int x = 10;
do {
printf("%d ", x); // Output: 10 (runs once even though x>5)
x++;
} while (x <= 5); // condition FALSE, but body ran once
// Nested loops (multiplication table)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i*j);
printf("\n");
Feature for loop while loop do-while loop
Condition-based; may not
Use when Number of iterations known Must execute at least once
execute
Condition check Before iteration (pre-test) Before iteration (pre-test) After iteration (post-test)
Initialization In loop header Before loop Before loop
Update In loop header Inside body Inside body
Minimum executions 0 (if condition false initially) 0 (if condition false) 1 (always)
3. Jump Statements:
Statement Purpose Example
break Exit innermost loop or switch immediately break; // exits for/while/switch
continue Skip rest of current iteration; move to next continue; // skips to next loop cycle
return Exit from function; optionally return value return 0; // exits function
goto Unconditional jump to a label (avoid using) goto label; ... label: code;
exit() Terminate entire program (stdlib.h) exit(0); // normal exit, exit(1) = error
■ 1.7 Functions in C – Complete Guide
■ Function A function is a self-contained, reusable block of code that performs a specific
task. Functions provide modularity, code reuse, and reduce redundancy. C
programs consist of one or more functions; execution begins at main().
Function Components:
Component Description Example
Data type of value returned (or void if nothing
Return Type int, float, char, void
returned)
Function Name Identifier for the function; follows naming rules add, calculateArea, findMax
Inputs to the function (optional); declared in
Parameters (int a, int b)
parentheses
Function Body Code block enclosed in { } that executes when called { return a+b; }
return Statement Sends value back to caller; exits function return result;
Declaration before main(); tells compiler about
Function Prototype int add(int, int);
function signature
// Function Prototype, Call & Definition
// Function Prototype (declaration - before main)
float calculateArea(float length, float breadth);
int main() {
float l = 5.0, b = 3.0;
float area = calculateArea(l, b); // Function Call
printf("Area = %.2f\n", area); // Output: Area = 15.00
return 0;
// Function Definition (after main or in separate file)
float calculateArea(float length, float breadth) { // Header
float result = length * breadth; // Body
return result; // Return
Parameter Passing Methods:
Original Variable
Method Description Example
Changed?
Copy of argument passed to function; swap(a, b) — doesn't
Call by Value No
changes don't affect original actually swap!
Call by Reference Address of argument passed; function swap(&a;, &b;) — actually
Yes
(via Pointers) accesses original memory location swaps!
Original Variable
Method Description Example
Changed?
Array name (pointer to 1st element)
Call by Array Yes void sort(int arr[], int n)
passed; changes affect original array
// Call by Value vs Call by Reference + Recursion
// Call by Value — original NOT changed
void doubleValue(int x) {
x = x * 2; // only local copy changes
int main() { int a=5; doubleValue(a); printf("%d",a); } // Output: 5
// Call by Reference — original IS changed
void doubleValue(int *x) {
*x = *x * 2; // changes value at original address
int main() { int a=5; doubleValue(&a;); printf("%d",a); } // Output: 10
// Recursive Function — function calling itself
int factorial(int n) {
if (n == 0 || n == 1) return 1; // Base case (MUST have!)
return n * factorial(n - 1); // Recursive case
// factorial(5) = 5*4*3*2*1 = 120
■ IMPORTANT: Recursion requires a BASE CASE to stop, otherwise it causes infinite recursion → stack
overflow.
Types of recursion: Direct (f calls f), Indirect (f calls g, g calls f), Tail (recursive call is last statement).
■ 1.8 Arrays in C
■ Array An array is a collection of elements of the same data type stored in contiguous
memory locations. Each element is accessed using an index (subscript), starting
from 0. Array size is fixed at declaration and cannot change at runtime.
// Arrays – 1D, 2D, and Strings
// 1D Array
int marks[5]; // Declaration (uninitialized)
int marks[5] = {80, 75, 90, 65, 88}; // Declaration + initialization
int marks[] = {80, 75, 90, 65, 88}; // Size auto-determined (5)
marks[2] = 95; // Modify element at index 2
printf("%d", marks[0]); // Access first element → 80
printf("%d", marks[4]); // Access last element → 88
// marks[5] → undefined behavior (out of bounds!)
// Traversing array with loop
for (int i = 0; i < 5; i++) {
printf("%d ", marks[i]); // Print all elements
// 2D Array (Matrix)
int matrix[3][3] = { // 3 rows, 3 columns
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("%d", matrix[1][2]); // Row 1, Col 2 → 6
// String as character array
char name[] = "RSMSSB"; // Automatically adds '\0' at end
printf("%s", name); // Output: RSMSSB
printf("%d", strlen(name));// Output: 6 (not counting '\0')
Property Description
Index Starts at 0; last valid index = size−1
Memory Elements stored in contiguous (adjacent) memory locations
Access O(1) — direct access by index (random access)
Size Fixed at compile time; cannot be changed at runtime
Initialization Uninitialized arrays contain garbage values (local) or 0 (global)
Passing to Function Array name is pointer to first element; size must be passed separately
■ 1.9 Pointers in C – In Depth
■ Pointer A pointer is a special variable that stores the memory address of another variable
rather than a direct value. Pointers enable dynamic memory allocation, efficient
array handling, and passing variables by reference. They are one of C's most
powerful features.
// Pointer Basics & Arithmetic
int x = 42; // Normal integer variable
int *ptr; // Pointer declaration (* means 'pointer to int')
ptr = &x; // & operator: assigns address of x to ptr
printf("%d", x); // Direct access → 42
printf("%p", ptr); // Pointer value → memory address (e.g. 0x7ffee4b2c)
printf("%d", *ptr); // Dereference (*) → 42 (value AT that address)
*ptr = 100; // Modify x through pointer
printf("%d", x); // Now x = 100
// Pointer arithmetic
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // p points to arr[0]
printf("%d", *p); // 10
p++; // Move to next element (adds sizeof(int) bytes)
printf("%d", *p); // 20
printf("%d", *(p+2));// 40 (p+2 = arr[3])
Pointer Type Description Example
Null Pointer Pointer pointing to nothing; initialized to NULL/0 int *p = NULL;
Generic pointer; can point to any type; must cast
Void Pointer void *p; int *ip=(int*)p;
before use
Points to freed/deleted memory; accessing it =
Dangling Pointer Avoid by setting to NULL after free()
undefined behavior
Uninitialized pointer; contains garbage address;
Wild Pointer int *p; (don't use without init)
dangerous
Double Pointer Pointer to pointer; stores address of another pointer int **pp = &ptr;
Points to a function; allows calling function via
Function Pointer int (*fp)(int) = &add;
pointer
Constant Pointer Pointer address cannot change; value can int* const p = &x;
Pointer to Constant Value cannot change through pointer; address can const int *p = &x;
// Dynamic Memory Allocation: malloc, calloc, realloc, free
// Dynamic Memory Allocation (heap memory)
#include
int *arr = (int*)malloc(5 * sizeof(int)); // Allocate 5 ints on heap
if (arr == NULL) { printf("Memory failed"); exit(1); }
arr[0] = 10; arr[1] = 20; // Use like normal array
free(arr); arr = NULL; // MUST free to avoid memory leak
int *arr2 = (int*)calloc(5, sizeof(int)); // calloc: allocates + zero-initializes
arr2 = (int*)realloc(arr2, 10*sizeof(int));// Resize to 10 elements
free(arr2);
// malloc vs calloc vs realloc
// malloc(size) — allocates, does NOT initialize (garbage values)
// calloc(n, size) — allocates n elements, initializes ALL to 0
// realloc(ptr, new_size) — resizes previously allocated block
// free(ptr) — releases memory back to OS
■ 1.10 Strings in C
■ String In C, a string is a one-dimensional array of characters terminated by a null
character (\0). C does not have a built-in string data type. Strings are handled
using char arrays and functions from .
// String Declaration and I/O
char str1[10] = "Hello"; // Stored as: H e l l o \0 (6 chars used)
char str2[] = "World"; // Size auto-determined as 6 (5+null)
char str3[10]; // Uninitialized; don't use without assigning
// Reading and printing strings
printf("%s", str1); // Output: Hello
scanf("%s", str3); // Read string (stops at space!)
fgets(str3, 10, stdin); // Read string including spaces (safer)
puts(str1); // Print + automatic newline
Function Prototype Description Example
strlen() size_t strlen(char *s) Returns length (not counting \0) strlen("Hello") = 5
strcpy() char* strcpy(dest, src) Copies src to dest strcpy(s1, "Hi")
strncpy() char* strncpy(dest, src, n) Copy at most n characters (safer) strncpy(s1, s2, 5)
strcat() char* strcat(dest, src) Appends src to end of dest strcat("Hi", " All")
Compares strings; 0=equal,
strcmp() int strcmp(s1, s2) strcmp("abc","abc")→0
<0=s10=s1>s2
Finds first occurrence of char c in
strchr() char* strchr(s, c) strchr("Hello",'l')
string
Finds first occurrence of substring s2
strstr() char* strstr(s1, s2) strstr("Hello","ll")
in s1
strupr() char* strupr(s) Convert to uppercase (non-standard) strupr("hello")→"HELLO"
strlwr() char* strlwr(s) Convert to lowercase (non-standard) strlwr("HELLO")→"hello"
Reverse string (non-standard/Turbo
strrev() char* strrev(s) strrev("Hello")→"olleH"
C)
atoi() int atoi(char *s) Convert string to integer (stdlib.h) atoi("123") → 123
itoa() char* itoa(int, char*, base) Integer to string (non-standard) itoa(123, s, 10)
■ 1.11 Structures, Unions & Enumerations
■ Structure (struct) A structure is a user-defined data type that groups variables of different data
types under a single name. Each variable inside a structure is called a member.
Structures are used to represent real-world entities like Student, Employee, etc.
// Structure – Definition, Usage & Pointer
// Structure definition
struct Student {
int rollNo; // Member 1
char name[50]; // Member 2
float marks; // Member 3
};
// Creating structure variable and accessing members
struct Student s1; // Variable declaration
[Link] = 101; // Dot (.) operator to access member
strcpy([Link], "Ram Kumar");
[Link] = 85.5;
printf("%d %s %.1f", [Link], [Link], [Link]);
// Structure with typedef (cleaner syntax)
typedef struct {
int x, y;
} Point; // Now use Point instead of struct Point
Point p1 = {3, 4}; // Initialization
// Array of structures
struct Student class[60]; // Array of 60 students
class[0].rollNo = 1;
// Pointer to structure (arrow operator ->)
struct Student *sptr = &s1;
printf("%d", sptr->rollNo); // -> for pointer access (same as (*sptr).rollNo)
■ Union A union is like a structure but all members share the same memory location. Size
of union = size of its largest member. Only ONE member can hold a value at a
time. Used to save memory when only one member is needed at a time.
// Union – Shared Memory
union Data {
int i; // 4 bytes
float f; // 4 bytes
char c; // 1 byte
}; // Total size = 4 bytes (size of largest member)
union Data d;
d.i = 65;
printf("%d", d.i); // 65
printf("%c", d.c); // A (65 is ASCII for 'A') — same memory!
// Setting one member OVERWRITES others (they share memory)
Structure vs Union:
Feature Structure Union
Memory Each member has separate memory All members share same memory
Size Sum of all member sizes (+ padding) Size of largest member
Access All members can hold values simultaneously Only one member valid at a time
Use Case Represent entity with multiple attributes Save memory when only one attribute needed
Keyword struct union
■ 1.12 File Handling in C
■ File Handling File handling in C allows programs to read from and write to files stored on
secondary storage (disk). It enables persistent data storage beyond program
execution. C uses a FILE pointer and functions from for file operations.
// File Handling – Write and Read
#include
FILE *fp; // FILE pointer declaration
// Opening a file (modes: r, w, a, r+, w+, a+, rb, wb)
fp = fopen("[Link]", "w"); // Open for writing (creates if not exists)
if (fp == NULL) { // Always check for NULL!
printf("Error opening file");
return 1;
// Writing to file
fprintf(fp, "Name: %s, Marks: %d\n", "Ram", 85);
fputs("Hello File!\n", fp);
fputc('A', fp); // Write single character
fclose(fp); // ALWAYS close file when done
// Reading from file
fp = fopen("[Link]", "r"); // Open for reading
char line[100];
while (fgets(line, 100, fp) != NULL) { // Read line by line
printf("%s", line);
fclose(fp);
Mode Description File Exists File Not Exists
r Read only Opens for reading Error (returns NULL)
w Write only Truncates (erases) file Creates new file
a Append only Opens; writes at end Creates new file
r+ Read + Write Opens for both Error (returns NULL)
w+ Write + Read Truncates file Creates new file
a+ Append + Read Opens; reads all, writes at end Creates new file
rb/wb/ab Binary modes Same as above but for binary data —
UNIT 2: C++ PROGRAMMING – COMPLETE NOTES
■ 2.1 Introduction to C++
■ C++ C++ is a general-purpose, multi-paradigm programming language developed by
Bjarne Stroustrup at Bell Labs starting in 1979 (initially called 'C with Classes',
renamed C++ in 1983). It extends C with object-oriented, generic, and functional
programming capabilities.
// Basic C++ Program
// Basic C++ Program (compare with C)
#include // C++ I/O (not stdio.h)
#include
using namespace std; // Avoids writing std:: prefix
int main() {
string name; // string type (C++ class, not char array)
int age;
cout << "Enter name: "; // cout = output stream (like printf)
cin >> name; // cin = input stream (like scanf)
cout << "Hello, " << name << "!" << endl; // endl = newline+flush
return 0;
C vs C++ – Key Differences:
Feature C C++
Paradigm Procedural only Procedural + OOP + Generic + Functional
Developer & Year Dennis Ritchie, 1972 Bjarne Stroustrup, 1979/1983
I/O printf()/scanf() cout/cin (iostream library)
String char array (manual) std::string class (automatic)
Memory allocation malloc()/free() new/delete operators
Full support (classes, inheritance,
OOP Not supported
polymorphism)
Function overloading Not supported Supported
Operator overloading Not supported Supported
Templates Not supported Supported (generic programming)
Exception handling Not supported try-catch-throw
References Not supported Supported (int &ref; = var;)
Namespace Not supported Supported (namespace std { })
Feature C C++
inline functions Not standard Supported (inline keyword)
Default arguments Not supported Supported (void f(int x=0))
File extension .c .cpp
■ 2.2 Classes and Objects in C++
■ Class A class is a user-defined data type (blueprint/template) that encapsulates data
members (attributes/properties) and member functions (methods/behaviors) into
a single unit. It is the fundamental building block of OOP in C++.
■ Object An object is an instance of a class. When a class is defined, no memory is
allocated. Memory is allocated only when an object is created. Each object has its
own copy of data members but shares member functions with other objects of the
same class.
// Class and Objects – Complete BankAccount Example
// Class definition
class BankAccount {
private: // Hidden from outside (encapsulation)
string accountNo;
string owner;
double balance;
public: // Accessible from outside
// Constructor (auto-called when object created)
BankAccount(string no, string name, double initial) {
accountNo = no;
owner = name;
balance = initial;
void deposit(double amount) { // Member function
if (amount > 0) balance += amount;
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
return false;
}
void displayBalance() { // Accessor (getter)
cout << "Balance: " << balance << endl;
};
// Creating and using objects
int main() {
BankAccount acc1("SB001", "Ram Kumar", 5000.0); // Object creation
[Link](2000); // Method call via dot
[Link](1000);
[Link](); // Output: Balance: 6000
BankAccount *acc2 = new BankAccount("SB002", "Sita", 3000.0);
acc2->deposit(500); // Arrow for pointer
delete acc2; // Free heap memory
return 0;
■ 2.3 Constructors and Destructors
■ Constructor A constructor is a special member function with the same name as the class and
no return type (not even void). It is automatically called when an object is created.
Used to initialize data members.
■ Destructor A destructor is a special member function with the same name as the class
preceded by ~ (tilde). It is automatically called when an object goes out of scope
or is explicitly deleted. Used to release resources (memory, file handles).
// Constructors & Destructor
class Student {
int id; string name; float *marks;
public:
// 1. Default Constructor (no parameters)
Student() {
id = 0; name = "Unknown"; marks = nullptr;
cout << "Default constructor called" << endl;
// 2. Parameterized Constructor
Student(int i, string n, int size) {
id = i; name = n;
marks = new float[size]; // Dynamic allocation
}
// 3. Copy Constructor (creates copy of existing object)
Student(const Student &s;) {
id = [Link]; name = [Link];
// Deep copy needed if pointer members exist
// 4. Destructor
~Student() {
delete[] marks; // Release dynamic memory
cout << "Destructor called for " << name << endl;
};
Student s1; // Default constructor called
Student s2(1, "Ram", 5); // Parameterized constructor
Student s3 = s2; // Copy constructor
// Destructor auto-called when objects go out of scope
■ 2.4 Inheritance in C++
■ Inheritance Inheritance is an OOP mechanism where a derived class (child) acquires
properties and behaviors of a base class (parent). It promotes code reusability
and establishes an IS-A relationship. In C++: class Derived : access_specifier
Base { };
// Inheritance – Single & Virtual Dispatch
// Base class
class Animal {
protected: // accessible in derived class
string name;
int age;
public:
Animal(string n, int a) : name(n), age(a) {}
void eat() { cout << name << " is eating" << endl; }
void sleep(){ cout << name << " is sleeping" << endl; }
virtual void speak() { cout << name << " makes a sound" << endl; }
};
// Single Inheritance: Dog IS-A Animal
class Dog : public Animal {
string breed;
public:
Dog(string n, int a, string b) : Animal(n, a), breed(b) {}
void fetch() { cout << name << " is fetching" << endl; }
void speak() override { // Override base class method
cout << name << " says: Woof!" << endl;
};
// Multiple Inheritance: FlyingFish IS-A Fish AND Bird
class FlyingFish : public Fish, public Bird { };
int main() {
Dog d("Rex", 3, "German Shepherd");
[Link](); // Inherited from Animal
[Link](); // Overridden: Rex says: Woof!
[Link](); // Dog's own method
Animal *a = &d; // Base pointer to derived object (polymorphism!)
a->speak(); // Virtual dispatch → calls Dog::speak() → Woof!
Type Syntax Description Example
Single class B : public A One base → one derived Dog inherits Animal
Multiple class C : public A, public B Multiple bases → one derived FlyingFish : Fish, Bird
Chain: A is parent of B, B is
Multilevel A→B→C Animal→Mammal→Dog
parent of C
Animal→Dog,
Hierarchical A → B and A → C One base → multiple derived
Animal→Cat
Mix of multiple types; may cause
Hybrid Combo of above types Use virtual base class
Diamond problem
■ Diamond Problem: In multiple inheritance, if two parents inherit from same grandparent, derived class gets
duplicate grandparent copy. Solution: Virtual Base Class → class B : virtual public A { };
■ 2.5 Polymorphism in C++
■ Polymorphism Polymorphism means 'many forms'. It allows objects of different types to be
treated as objects of a common type, with each responding in its own way. It is
implemented via function overloading (compile-time) and virtual
functions/overriding (runtime).
// Function Overloading, Operator Overloading & Virtual Functions
// Compile-time polymorphism: Function Overloading
class Calculator {
public:
int add(int a, int b) { return a + b; }
float add(float a, float b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
// Same name 'add', different signatures → compiler picks at compile time
};
// Compile-time: Operator Overloading
class Complex {
float real, imag;
public:
Complex(float r, float i) : real(r), imag(i) {}
Complex operator+(const Complex& c) { // Overload + for Complex
return Complex(real+[Link], imag+[Link]);
void show() { cout << real << "+" << imag << "i"; }
};
Complex c1(1,2), c2(3,4);
Complex c3 = c1 + c2; // Calls operator+() → 4+6i
// Runtime polymorphism: Virtual Function + Overriding
class Shape {
public:
virtual float area() { return 0; } // virtual = can be overridden
virtual void draw() = 0; // pure virtual = MUST override (abstract)
};
class Circle : public Shape {
float r;
public:
Circle(float r) : r(r) {}
float area() override { return 3.14f * r * r; }
void draw() override { cout << "Drawing Circle"; }
};
Shape *s = new Circle(5);
cout << s->area(); // 78.5 — runtime decides which area() to call
UNIT 3: JAVA PROGRAMMING – COMPLETE NOTES
■ 3.1 Introduction & Architecture
■ Java Java is a high-level, class-based, object-oriented programming language
designed to have as few implementation dependencies as possible. Its principle is
Write Once Run Anywhere (WORA). Developed by James Gosling at Sun
Microsystems and released in 1995.
Compon
Full Form Role
ent
Complete toolkit: includes JRE + compiler (javac) + debugger + tools like jar,
JDK Java Development Kit
javadoc
Java Runtime
JRE JVM + Java class libraries needed to RUN Java programs (not develop)
Environment
JVM Java Virtual Machine Executes Java bytecode; platform-specific; provides platform independence
javac Java Compiler Compiles .java source code → .class bytecode (NOT machine code)
java Java Launcher Starts JVM and runs .class bytecode file
Bytecode .class file Intermediate platform-independent code; executed by JVM on any platform
Just-In-Time
JIT Part of JVM; converts bytecode to native machine code at runtime for speed
Compiler
ClassLoa
— JVM component that loads .class files into memory
der
GC Garbage Collector Automatically manages memory; frees objects no longer referenced
■ Java Execution Flow: [Link] → javac → [Link] (bytecode) → JVM → machine code execution
This is why Java is platform-independent: bytecode runs on any JVM regardless of OS/hardware.
■ 3.2 Java OOP Concepts
// Java OOP – Complete Class & Inheritance
// Java OOP Example – Full Class
public class Person {
// Instance variables (encapsulated)
private String name;
private int age;
// Constructor
public Person(String name, int age) {
[Link] = name; // 'this' refers to current object
[Link] = age;
}
// Getter methods (accessor)
public String getName() { return name; }
public int getAge() { return age; }
// Setter methods (mutator)
public void setName(String name) { [Link] = name; }
public void setAge(int age) {
if (age > 0) [Link] = age; // validation
// Method Overriding toString()
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
// Inheritance
public class Student extends Person {
private String rollNo;
private double gpa;
public Student(String name, int age, String roll, double gpa) {
super(name, age); // Call parent constructor (MUST be first)
[Link] = roll;
[Link] = gpa;
@Override
public String toString() {
return [Link]() + " Roll:" + rollNo + " GPA:" + gpa;
Important Java Keywords:
Keyword Description
class Defines a class
extends Establishes inheritance (single only)
implements Implements an interface (multiple allowed)
interface Defines an interface (100% abstract in Java 7)
Keyword Description
abstract Abstract class or method (method has no body)
final Variable = constant; method = cannot override; class = cannot inherit
static Belongs to class, not instance; shared by all objects
this Reference to current object; used to resolve name conflicts
super Reference to parent class; access parent constructor/methods
new Allocates memory and creates object on heap
null Represents absence of object (reference is null)
void Method returns no value
public/private/protect
Access modifiers controlling visibility
ed
try-catch-finally Exception handling blocks
throws Declares that method may throw checked exception
throw Explicitly throw an exception
instanceof Tests if object is instance of a class → if(obj instanceof String)
synchronized Ensures thread-safe access to method/block
volatile Variable may be modified by multiple threads; no caching
■ 3.3 Interfaces and Abstract Classes in Java
// Interface & Abstract Class in Java
// Interface definition
interface Drawable {
void draw(); // abstract by default
void resize(int factor); // abstract by default
default void print() { // Java 8: default method with body
[Link]("Printing shape...");
interface Colorable {
void setColor(String color);
// Class implementing MULTIPLE interfaces
class Circle implements Drawable, Colorable {
private double radius;
private String color;
public Circle(double r) { [Link] = r; }
@Override public void draw() {
[Link]("Drawing circle r=" + radius);
@Override public void resize(int f) { radius *= f; }
@Override public void setColor(String c) { color = c; }
// Abstract Class
abstract class Vehicle {
protected String brand;
protected int speed;
public Vehicle(String b, int s) { brand=b; speed=s; }
abstract void start(); // Must be overridden
void stop() { [Link](brand + " stopped"); } // Concrete
class Car extends Vehicle {
public Car(String b, int s) { super(b, s); }
@Override public void start() {
[Link](brand + " engine started at " + speed + " kmph");
■ 3.4 Exception Handling in Java
■ Exception An exception is an abnormal condition that disrupts normal program flow. In Java,
exceptions are objects of class Throwable (subclasses: Exception and Error).
Handling exceptions prevents program crashes and provides meaningful error
messages.
// Exception Handling with try-catch-finally + Custom Exception
// Exception Handling Syntax
try {
int[] arr = new int[5];
arr[10] = 50; // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array error: " + [Link]());
} catch (ArithmeticException e) {
[Link]("Math error: " + [Link]());
} catch (Exception e) { // Generic catch (must be last)
[Link]("Error: " + e);
} finally {
[Link]("This always runs (cleanup code)");
// Custom Exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String msg) { super(msg); }
void withdraw(double amt) throws InsufficientFundsException {
if (amt > balance) throw new InsufficientFundsException("Not enough funds");
balance -= amt;
Throwable Description
Serious system-level problems; usually unrecoverable: OutOfMemoryError,
Error
StackOverflowError
Exception Application-level issues; recoverable
Must handle or declare; checked at compile time: IOException, SQLException,
Checked Exception
ClassNotFoundException
Not required to handle; occur at runtime: NullPointerException,
Unchecked (RuntimeException)
ArrayIndexOutOfBoundsException, ArithmeticException, ClassCastException
UNIT 4: PYTHON PROGRAMMING – COMPLETE
NOTES
■ 4.1 Introduction to Python
■ Python Python is a high-level, interpreted, dynamically-typed, multi-paradigm,
general-purpose programming language. Created by Guido van Rossum and
released in 1991. Python emphasizes code readability using indentation as
syntax. Named after BBC comedy 'Monty Python's Flying Circus'.
// Python Basics – Variables, Types, I/O
# Python is concise: same task as C needs fewer lines
# Hello World
print('Hello, World!') # No semicolons, no main()
# Variables (no type declaration needed)
name = 'Mayank' # str
age = 21 # int
gpa = 8.5 # float
is_student = True # bool
# Type checking
print(type(name)) #
print(type(age)) #
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0 # All get same value
# Type conversion
x = int('42') # '42' → 42
s = str(3.14) # 3.14 → '3.14'
f = float('3.14') # '3.14' → 3.14
# f-string formatting (Python 3.6+)
print(f'Name: {name}, Age: {age}, GPA: {gpa:.2f}')
# Output: Name: Mayank, Age: 21, GPA: 8.50
■ 4.2 Python Data Collections
// Python Collections – List, Tuple, Dictionary, Set
# ■■ LIST ■■ ordered, mutable, allows duplicates
fruits = ['apple', 'banana', 'cherry', 'apple']
[Link]('mango') # Add at end
[Link](1, 'kiwi') # Add at index 1
[Link]('banana') # Remove by value
[Link](0) # Remove by index
[Link]() # Sort in place
print(fruits[0]) # Index access
print(fruits[-1]) # Last element
print(fruits[1:3]) # Slicing [start:stop]
print(len(fruits)) # Length
# ■■ TUPLE ■■ ordered, IMMUTABLE, allows duplicates
coords = (10.5, 20.3) # Cannot change after creation
x, y = coords # Tuple unpacking
single = (42,) # Single element tuple needs comma
# ■■ DICTIONARY ■■ key:value pairs, mutable, unique keys
student = {'name': 'Ram', 'age': 20, 'gpa': 8.5}
student['city'] = 'Jaipur' # Add new key
student['age'] = 21 # Update value
del student['gpa'] # Delete key
print([Link]('name')) # Safe access (no KeyError)
print([Link]()) # All keys
print([Link]()) # All values
for k, v in [Link](): # Iterate key-value pairs
print(f'{k}: {v}')
# ■■ SET ■■ unordered, mutable, NO DUPLICATES
nums = {1, 2, 3, 2, 1} # Stored as {1, 2, 3}
[Link](4) # Add element
[Link](2) # Remove (no error if missing)
a = {1,2,3}; b = {2,3,4}
print(a | b) # Union: {1,2,3,4}
print(a & b) # Intersection: {2,3}
print(a - b) # Difference: {1}
Collection Ordered? Mutable? Duplicates? Access Syntax
List Yes Yes Yes Index [1, 2, 3]
Tuple Yes No Yes Index (1, 2, 3)
Set No Yes No Iteration only {1, 2, 3}
Yes Keys: No, Values:
Dict Yes Key {'a':1, 'b':2}
(Py3.7+) Yes
String Yes No Yes Index 'hello'
■ 4.3 Functions in Python
// Python Functions – def, lambda, *args, **kwargs, Comprehensions
# Basic function
def greet(name, greeting='Hello'): # Default parameter
return f'{greeting}, {name}!'
print(greet('Ram')) # Hello, Ram!
print(greet('Sita', 'Namaste')) # Namaste, Sita!
# *args (variable positional args)
def add(*numbers):
return sum(numbers)
print(add(1, 2, 3, 4, 5)) # 15
# **kwargs (variable keyword args)
def student_info(**data):
for key, val in [Link]():
print(f'{key}: {val}')
student_info(name='Ram', age=20, city='Jaipur')
# Lambda function (anonymous, one-liner)
square = lambda x: x**2
add_two = lambda x, y: x + y
print(square(5)) # 25
print(add_two(3, 4)) # 7
# map(), filter(), reduce()
numbers = [1, 2, 3, 4, 5, 6]
squares = list(map(lambda x: x**2, numbers)) # [1,4,9,16,25,36]
evens = list(filter(lambda x: x%2==0, numbers)) # [2,4,6]
from functools import reduce
total = reduce(lambda x,y: x+y, numbers) # 21
# List Comprehension (Python's power feature!)
squares = [x**2 for x in range(1, 6)] # [1,4,9,16,25]
even_sq = [x**2 for x in range(10) if x%2==0] # [0,4,16,36,64]
matrix = [[i*j for j in range(3)] for i in range(3)] # 2D
■ 4.4 OOP in Python
// OOP in Python – Classes, Inheritance, Dunder Methods
class Animal:
species_count = 0 # Class variable (shared by all instances)
def __init__(self, name, age): # Constructor
[Link] = name # Instance variable
[Link] = age
Animal.species_count += 1
def speak(self): # Instance method (self = this object)
return f"{[Link]} makes a sound"
@classmethod # Class method
def get_count(cls):
return cls.species_count
@staticmethod # Static method (no self/cls)
def is_mammal(animal_class):
return animal_class in ['Dog', 'Cat', 'Human']
def __str__(self): # Magic/Dunder method (like toString())
return f"Animal({[Link]}, {[Link]}yrs)"
def __repr__(self):
return f"Animal(name='{[Link]}', age={[Link]})"
# Inheritance in Python
class Dog(Animal): # Dog extends Animal
def __init__(self, name, age, breed):
super().__init__(name, age) # Call parent __init__
[Link] = breed
def speak(self): # Override
return f"{[Link]} says: Woof!"
# Usage
a = Animal('Generic', 5)
d = Dog('Rex', 3, 'Labrador')
print([Link]()) # Rex says: Woof!
print(Animal.get_count()) # 2
print(str(a)) # Animal(Generic, 5yrs)
print(isinstance(d, Animal)) # True (Dog IS-A Animal)
UNIT 5: DATA STRUCTURES & ALGORITHMS –
COMPLETE
■ 5.1 Introduction to Data Structures
■ Data Structure A data structure is a systematic way of organizing, managing, and storing data in
a computer so that it can be accessed and modified efficiently. The choice of data
structure significantly affects the performance of algorithms.
Category Types Examples
Primitive Basic built-in types int, float, char, bool, pointer
Linear (Sequential) Elements arranged in sequence Array, Linked List, Stack, Queue, Deque
Non-Linear (Hierarchical) Elements in hierarchical relationship Tree (Binary, BST, AVL, Heap), Graph
Hash-Based Key-value pairs with hash function Hash Table, Hash Map, Hash Set
File-Based Data stored in files Sequential file, Indexed file, Direct access
Big O Notation – Algorithm Complexity:
■ Big O Notation Big O notation describes the upper bound (worst-case) time/space complexity of
an algorithm as input size n grows. It tells how the algorithm scales. Lower Big O
= more efficient.
Notation Name Example Explanation
O(1) Constant Array access arr[i] Same time regardless of input size
O(log n) Logarithmic Binary Search Halves problem each step
O(n) Linear Linear Search Time proportional to input size
O(n log n) Linearithmic Merge Sort, Quick Sort (avg) Most efficient for comparison sorts
O(n²) Quadratic Bubble Sort, nested loops Time squares as n doubles
O(n³) Cubic Matrix multiplication (naive) Three nested loops
O(2■) Exponential Recursive Fibonacci (naive) Doubles with each addition to n
Brute-force Travelling
O(n!) Factorial Extremely slow; impractical for large n
Salesman
■ 5.2 Linked List – In Depth
■ Linked List A linked list is a linear data structure where elements (nodes) are stored at
non-contiguous memory locations. Each node contains data and a pointer to the
next node. Unlike arrays, linked lists can grow/shrink dynamically.
// Singly Linked List – Node, Insert, Traverse
/* Node structure in C */
struct Node {
int data; // Data part
struct Node *next; // Pointer to next node
};
/* Creating and traversing a linked list */
struct Node *head = NULL; // Empty list
// Insert at beginning
void insertFront(int val) {
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = head; // New node points to old head
head = newNode; // Head now points to new node
// Traverse and print
void display() {
struct Node *temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
printf("NULL\n");
Type Description Extra Pointer Traversal
Each node has data + pointer to next One direction (forward
Singly Linked List next only
node only)
Each node has data + pointer to next Both directions (forward
Doubly Linked List prev + next
AND previous and backward)
Last node points back to first node (forms
Circular Singly next (last→first) Can traverse continuously
circle)
Doubly linked + last→first and first→last prev + next Both directions,
Circular Doubly
connections (circular) continuously
Array vs Linked List Comparison:
Operation Array Linked List
Random Access O(1) — direct by index O(n) — traverse from head
Insert at Beginning O(n) — shift all elements O(1) — just update pointers
Insert at End O(1) amortized O(n) without tail pointer; O(1) with tail
Operation Array Linked List
Insert at Middle O(n) O(n) to find, O(1) to insert
Delete O(n) — shift elements O(n) to find, O(1) to delete
Memory Contiguous block; may waste Non-contiguous; extra memory for pointers
Size Fixed (static) Dynamic (can grow/shrink)
Cache Performance Better (spatial locality) Poor (nodes scattered in memory)
■ 5.3 Stack – Complete
■ Stack A stack is a linear data structure that follows the LIFO (Last In First Out) principle.
The element inserted last is the first to be removed. Think of a stack of plates —
you add and remove from the top.
Stack Operations:
Operation Description Time Complexity
push(x) Insert element x at top of stack O(1)
pop() Remove and return top element O(1)
peek() / top() Return top element without removing O(1)
isEmpty() Return true if stack has no elements O(1)
isFull() Return true if stack is at capacity (array-based) O(1)
size() Return number of elements in stack O(1)
Stack Applications:
• Function Call Stack: OS maintains call stack; each function call pushes stack frame; return pops it
• Expression Evaluation: Evaluate postfix/prefix expressions using stack
• Expression Conversion: Infix → Postfix → Prefix using stack
• Undo/Redo: Text editors push operations to undo stack
• Browser History: Back button = pop from history stack
• Balanced Parentheses: Check if () {} [] are properly balanced
• Tower of Hanoi: Classic recursive problem using stack
• DFS Traversal: Depth-First Search uses explicit or recursive stack
■ 5.4 Queue – Complete
■ Queue A queue is a linear data structure that follows FIFO (First In First Out) principle.
The element inserted first is the first to be removed. Think of a line at a ticket
counter — first person in line is first served.
Type Description Use Case
Simple Queue Basic FIFO; insert at rear, remove from front Job scheduling, Print queue
Type Description Use Case
Rear and Front connected forming circle; overcomes
Circular Queue CPU scheduling, Traffic light control
simple queue's space waste
Dijkstra's algorithm, OS process
Priority Queue Element with highest priority removed first (not FIFO)
scheduling, A* search
Deque
Insert/delete from BOTH front and rear Sliding window, Palindrome check
(Double-Ended)
Thread blocks if queue empty (on dequeue) or full (on
Blocking Queue Producer-Consumer problem
enqueue)
Concurrent Queue Thread-safe queue for multi-threaded programs Message passing systems
■ 5.5 Trees – Complete
■ Tree A tree is a non-linear, hierarchical data structure consisting of nodes connected
by edges. It has one root node (top), internal nodes (with children), and leaf nodes
(no children). A tree with n nodes has exactly n-1 edges.
Term Definition
Root Topmost node; no parent
Parent Node with at least one child
Child Node directly below parent
Leaf/Terminal Node with no children
Sibling Nodes with same parent
Height of tree Number of edges on longest root-to-leaf path
Depth of node Number of edges from root to that node
Degree of node Number of children
Degree of tree Maximum degree of any node in tree
Level Depth + 1 (root is at level 1)
Subtree A node and all its descendants
Forest Collection of disjoint trees
Binary Search Tree (BST) Properties:
BST Rule: For every node, LEFT subtree values < NODE value < RIGHT subtree values
BST Inorder traversal always gives SORTED (ascending) output
BST Search/Insert/Delete: O(log n) average, O(n) worst case (skewed tree)
Balanced BST (AVL/Red-Black): guarantees O(log n) worst case
// BST Insert & Inorder Traversal
// BST Node in C
struct BSTNode {
int data;
struct BSTNode *left, *right;
};
// BST Insert
struct BSTNode* insert(struct BSTNode* root, int key) {
if (root == NULL) {
struct BSTNode* n = malloc(sizeof(struct BSTNode));
n->data = key; n->left = n->right = NULL;
return n;
if (key < root->data) root->left = insert(root->left, key);
else if (key > root->data) root->right = insert(root->right, key);
return root; // key already exists, return unchanged
// Inorder Traversal (gives sorted output for BST)
void inorder(struct BSTNode* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
■ 5.6 Sorting Algorithms – Detailed
Bubble Sort:
■ Bubble Sort Repeatedly compares adjacent elements and swaps them if they are in wrong
order. After each pass, the largest unsorted element 'bubbles up' to its correct
position. Simple but inefficient. Time: O(n²). Stable sort.
// Bubble Sort Implementation
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) { // n-1 passes
for (int j = 0; j < n-1-i; j++) { // Last i elements already sorted
if (arr[j] > arr[j+1]) { // Compare adjacent
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
// Trace: [5,3,8,1] → [3,5,8,1] → [3,5,1,8] → [3,1,5,8] → [1,3,5,8]
Insertion Sort:
■ Insertion Sort Builds sorted array one element at a time by picking each element and inserting it
in correct position among already-sorted elements (like sorting playing cards).
O(n) best case, O(n²) average/worst. Stable. Good for small/nearly-sorted data.
Selection Sort:
■ Selection Sort Finds minimum element from unsorted portion and places it at beginning. Repeat.
Always O(n²) regardless of input. Not stable. Minimum number of swaps: O(n).
Merge Sort:
■ Merge Sort Divide-and-Conquer algorithm: recursively divides array into halves, sorts each
half, then merges them. Guaranteed O(n log n) for all cases. Stable. Uses extra
O(n) space. Best for linked lists. External sorting for large datasets.
Quick Sort:
■ Quick Sort Divide-and-Conquer: selects a pivot element, partitions array around pivot
(smaller left, larger right), recursively sorts partitions. O(n log n) average, O(n²)
worst case (bad pivot). In-place (O(log n) space). Not stable. Fastest in practice
for random data.
Algorithm Best Average Worst Space Stable? Notes
Bubble Sort O(n) O(n²) O(n²) O(1) Yes Simplest; inefficient; educational
Selection Sort O(n²) O(n²) O(n²) O(1) No Fewest swaps; always O(n²)
Insertion Sort O(n) O(n²) O(n²) O(1) Yes Best for small/nearly sorted
Merge Sort O(n lg n) O(n lg n) O(n lg n) O(n) Yes Guaranteed; good for linked lists
Quick Sort O(n lg n) O(n lg n) O(n²) O(lg n) No Fastest avg; bad if sorted input
Heap Sort O(n lg n) O(n lg n) O(n lg n) O(1) No In-place; not cache-friendly
Counting Sort O(n+k) O(n+k) O(n+k) O(k) Yes Only integers in range [0,k]
Radix Sort O(nk) O(nk) O(nk) O(n+k) Yes Digit by digit; good for fixed-width
Tim Sort O(n) O(n lg n) O(n lg n) O(n) Yes Python's default sort (Merge+Insertion)
UNIT 6: OOP CONCEPTS – FOUR PILLARS IN DEPTH
■ 6.1 Object-Oriented Programming Overview
■ OOP Object-Oriented Programming (OOP) is a programming paradigm based on the
concept of 'objects' — entities that combine data (attributes) and behavior
(methods). OOP makes programs modular, reusable, and easier to maintain. The
four pillars are: Encapsulation, Abstraction, Inheritance, and Polymorphism.
Concept One-line Definition
Class Blueprint/template defining structure and behavior of objects
Object Instance of a class; occupies memory; has state and behavior
Attribute/Field Variable that holds data belonging to an object
Method Function belonging to a class that defines behavior
Constructor Special method called when object is created; initializes object state
Destructor Special method called when object is destroyed; releases resources
this/self Keyword referring to current object inside class methods
Instantiation Act of creating an object from a class
Message Passing Objects communicate by calling each other's methods
■ 6.2 Pillar 1: Encapsulation
■ Encapsulation Encapsulation is the mechanism of bundling data (variables) and methods that
operate on that data into a single unit (class), and restricting direct access to
some components using access modifiers (private, protected, public). It is also
called 'data hiding'.
Why Encapsulation?
• Data Hiding: Internal implementation details are hidden from outside world
• Controlled Access: Data can only be modified through well-defined methods (getters/setters)
• Validation: Setters can validate data before assignment (e.g., age cannot be negative)
• Flexibility: Internal implementation can change without affecting external code
• Modularity: Each class is a self-contained unit
// Encapsulation – Bad vs Good Example
// Bad: No encapsulation (public variables)
class BadStudent {
public: int age; // Anyone can set age = -500 !!
};
// Good: Encapsulated
class GoodStudent {
private:
int age; // Hidden
string name;
public:
void setAge(int a) { // Setter with validation
if (a > 0 && a < 150) age = a;
else cout << "Invalid age!";
int getAge() { return age; } // Getter (read-only access)
void setName(string n) { name = n; }
string getName() { return name; }
};
GoodStudent s;
[Link](20); // Valid → age = 20
[Link](-5); // Invalid age! (rejected by validation)
// [Link] = -5; // ERROR: 'age' is private
■ 6.3 Pillar 2: Abstraction
■ Abstraction Abstraction is the process of showing only essential features and hiding
implementation details. It focuses on 'what' an object does rather than 'how' it
does it. Users interact with a simplified interface without needing to know internal
workings.
Real-World Abstraction Examples:
• Car: You use steering wheel, pedals, gear shift. You don't see engine combustion, transmission
mechanics.
• ATM Machine: You see deposit/withdraw interface. You don't see database queries, encryption, bank
transactions.
• Smartphone: You tap apps. You don't see CPU instructions, memory management, radio signals.
• printf(): You call printf("Hello"). You don't see buffer management, syscall, terminal driver code.
Abstraction vs Encapsulation:
Aspect Abstraction Encapsulation
Concept Hiding complexity (HOW it works) Hiding data (protecting data)
Focus What object does (interface) How object protects its data (access control)
Mechanism Abstract classes, Interfaces Access modifiers (private/protected/public)
Level Design level (architecture) Implementation level (code)
Purpose Reduce complexity, increase clarity Data security and integrity
Example [Link]() — don't care how drawn private balance in BankAccount
■ 6.4 Pillar 3: Inheritance (Detailed)
■ Inheritance Inheritance is the mechanism by which one class (child/derived/sub) acquires all
properties and behaviors of another class (parent/base/super). It establishes an
IS-A relationship and promotes code reuse. Child class can add new features or
modify inherited ones.
Types of Inheritance:
Type Description Support in Languages
Single One parent → one child class C++, Java, Python (all)
C++, Python (YES); Java (NO — use
Multiple Multiple parents → one child class
interfaces)
Multilevel Grandparent → Parent → Child (chain) C++, Java, Python (all)
Hierarchical One parent → multiple children C++, Java, Python (all)
C++ (with virtual classes); not directly in
Hybrid Combination of multiple types
Java
Constructor Call Order in Inheritance:
When a derived class object is created, constructors are called from BASE to DERIVED (top-down).
When object is destroyed, destructors are called from DERIVED to BASE (bottom-up).
Example: if C extends B extends A, creation: A() → B() → C(); destruction: ~C() → ~B() → ~A()
■ 6.5 Pillar 4: Polymorphism (Detailed)
■ Polymorphism Polymorphism (Greek: 'many forms') allows the same interface to be used for
different underlying data types or classes. An object can behave differently based
on its actual type. Implemented through overloading (compile-time) and overriding
(runtime).
Aspect Method Overloading (Compile-time) Method Overriding (Runtime)
Dynamic polymorphism, Late binding, Virtual
Also called Static polymorphism, Early binding
dispatch
When resolved At compile time (compiler decides) At runtime (JVM/program decides)
Class relationship Same class (different signatures) Parent-child class relationship needed
Method name Same Same
Must be DIFFERENT (type, number, or
Parameters Must be SAME (exact match)
order)
Return type Can be same or different Must be same (or covariant in Java)
C++ keyword Not needed virtual in base; override in derived
Java annotation Not needed @Override recommended
Aspect Method Overloading (Compile-time) Method Overriding (Runtime)
Example add(int,int) vs add(float,float) [Link]() vs [Link]()
UNIT 7: AI / ML / BLOCKCHAIN – DETAILED NOTES
■ 7.1 Artificial Intelligence – Complete
■ Artificial Intelligence Artificial Intelligence is the simulation of human intelligence processes by
(AI) computer systems. These processes include learning (acquiring information),
reasoning (using rules), self-correction, and creativity. Coined by John McCarthy
in 1956 at Dartmouth Conference.
Category Description Examples
Chess engines (Deep Blue), Siri, AlphaGo,
Narrow AI / Weak AI Designed for specific task; current AI state
Image recognition
Human-level intelligence across all tasks;
General AI / Strong AI Not yet achieved; ongoing research
theoretical
Surpasses human intelligence in every
Super AI Science fiction; future concern
domain; hypothetical
Reactive AI No memory; reacts to current input only Deep Blue (chess), spam filters
Learns from historical data; current ML
Limited Memory AI Self-driving cars, ChatGPT
systems
Understands human emotions/beliefs;
Theory of Mind AI Social robots (experimental)
research stage
Self-Aware AI Conscious machines; hypothetical Purely theoretical
AI Branches:
Branch Full Name Description
ML Machine Learning Systems learn from data without explicit programming
DL Deep Learning ML using multi-layer neural networks; learns hierarchical features
Natural Language
NLP AI understanding/generating human language
Processing
CV Computer Vision AI interpreting visual data (images, video)
Robotics — Intelligent machines that can interact with physical world
Expert
— Encode human expert knowledge; rule-based reasoning (MYCIN, DENDRAL)
Systems
Fuzzy Logic — Handles imprecise/vague data; more than true/false
Genetic
— Optimization inspired by biological evolution
Algorithm
■ 7.2 Machine Learning – Complete
■ Machine Learning Machine Learning is a subset of AI that enables computers to learn from
experience (data) without being explicitly programmed. ML algorithms build
mathematical models from training data to make predictions or decisions. Term
coined by Arthur Samuel in 1959.
Types of Machine Learning:
Type Learning From Feedback Goal Algorithms
Linear Regression, Decision
Supervised Labeled data Direct (correct Learn mapping
Tree, SVM, Neural Networks,
Learning (input-output pairs) answers given) from input to output
KNN, Naive Bayes
K-Means Clustering,
Unsupervised Unlabeled data (input None (no correct Discover hidden DBSCAN, PCA,
Learning only) answers) patterns/structure Autoencoders, Association
Rules
Q-Learning, SARSA, Deep
Reinforcement Interaction with Reward/punishme Maximize
Q-Network (DQN), Policy
Learning environment nt signals cumulative reward
Gradient, PPO
Mix of labeled + Improve with Self-training, Label
Semi-supervised Partial
unlabeled limited labeled data Propagation
Unlabeled (creates Learn BERT, GPT, SimCLR,
Self-supervised Generated labels
labels from data) representations word2vec
ML Key Terms:
Term Definition
Feature Input variable/attribute used for prediction (e.g., age, salary)
Label/Target Output variable to predict (e.g., house price, spam/not-spam)
Training Data Data used to train (fit) the ML model
Test Data Unseen data used to evaluate model performance
Validation Data Subset of training data used to tune hyperparameters
Model Mathematical function learned from training data to make predictions
Overfitting Model memorizes training data but fails on new data (too complex)
Underfitting Model too simple; poor performance even on training data
Bias Error from oversimplified model (high bias = underfitting)
Variance Error from oversensitive model (high variance = overfitting)
Regularization Technique to reduce overfitting (L1/Lasso, L2/Ridge)
Cross-Validation k-fold CV; train/test on different data subsets; reduces overfitting bias
Hyperparameter Parameters set before training (learning rate, # of layers, k in KNN)
Epoch One complete pass through entire training dataset
Term Definition
Batch Size Number of training examples used in one iteration
Gradient Descent Optimization algorithm; adjusts weights to minimize loss function
Learning Rate Step size in gradient descent; too high→diverge; too low→slow
Loss Function Measures difference between predicted and actual output (MSE, Cross-Entropy)
Accuracy % correct predictions: (TP+TN)/(TP+TN+FP+FN)
Precision TP/(TP+FP) — of predicted positives, how many correct
Recall TP/(TP+FN) — of actual positives, how many detected
F1 Score Harmonic mean of Precision and Recall: 2*P*R/(P+R)
■ 7.3 Neural Networks & Deep Learning
■ Neural Network An Artificial Neural Network (ANN) is a computational model inspired by biological
neural networks in the brain. It consists of layers of interconnected nodes
(neurons) that process input signals through weighted connections and activation
functions.
// Neural Network Structure & Activation Functions
Neural Network Architecture:
Input Layer → Hidden Layers → Output Layer
[x1] [h1] [h2] [y1]
[x2] weights [h3] [h4] weights [y2]
[x3] ■■■■■■■■■> [h5] [h6] ■■■■■■■■■> [y3]
(activation
functions)
Each connection has a weight (w)
Each neuron: output = activation(sum(w*inputs) + bias)
Activation Functions:
Sigmoid: f(x) = 1/(1+e^-x) → output 0 to 1 (binary classification)
Tanh: f(x) = (e^x-e^-x)/(e^x+e^-x) → output -1 to 1
ReLU: f(x) = max(0, x) → most popular; solves vanishing gradient
Softmax: normalizes to probabilities summing to 1 (multiclass output)
DL
Full Name Used For
Architecture
ANN Artificial Neural Network General purpose; tabular data
Convolutional Neural
CNN Image recognition, Computer Vision (face/object detection)
Network
DL
Full Name Used For
Architecture
RNN Recurrent Neural Network Sequential data; time series; NLP (remembers previous input)
LSTM Long Short-Term Memory Long sequences; solves vanishing gradient in RNN; speech recognition
Generative Adversarial
GAN Image generation, DeepFakes, synthetic data creation
Network
Transformer — State-of-art NLP; powers BERT, GPT, ChatGPT
Autoencoder — Dimensionality reduction, anomaly detection, image denoising
ResNet Residual Network Very deep CNNs (152+ layers); skip connections solve vanishing gradient
■ 7.4 Natural Language Processing (NLP)
■ NLP Natural Language Processing is a branch of AI that deals with the interaction
between computers and human (natural) languages. It enables computers to
read, understand, interpret, and generate human language in a meaningful and
useful way.
NLP Application Description Examples
Google Translate, DeepL, Microsoft
Machine Translation Translate text between languages
Translator
Determine opinion/emotion in text
Sentiment Analysis Product reviews, Social media monitoring
(positive/negative/neutral)
Chatbot/Virtual Assistant Conversational AI systems ChatGPT, Siri, Alexa, Google Assistant
News summarizers, Document
Text Summarization Condense long text into key points
summarization tools
Named Entity Recognition Identify people, places, organizations in text Information extraction from news
Speech Recognition Convert spoken language to text Google Speech, Apple Siri, Cortana
Text Classification Categorize text into predefined classes Spam detection, Document categorization
Information Retrieval Find relevant documents for a query Search engines (Google, Bing)
■ 7.5 Blockchain – Complete Notes
■ Blockchain A blockchain is a distributed, decentralized, immutable digital ledger that records
transactions in a chain of blocks. Each block contains a list of transactions, a
timestamp, and a cryptographic hash of the previous block, making it
tamper-evident. Invented by Satoshi Nakamoto in 2008 with Bitcoin.
Block Structure:
// Blockchain Block Structure
Block {
Index: Block number in chain (0 = Genesis block)
Timestamp: When block was created
Data: Transactions (e.g., 'Alice pays Bob 1 BTC')
Previous Hash: Hash of previous block (creates the 'chain')
Hash: SHA-256 hash of this block's content
Nonce: Number used once; adjusted until hash meets difficulty target
Genesis Block (Block 0) has Previous Hash = '00000...0' (no predecessor)
If someone modifies Block 3, its hash changes, breaking link to Block 4!
→ All subsequent blocks become invalid → tampering detected immediately
Property Description
Decentralized No single central authority; data distributed across all nodes (peers)
Immutable Once data recorded, cannot be altered or deleted without invalidating entire chain
Transparent All participants can view transaction history (public blockchains)
Secure Cryptographic hashing makes tampering computationally infeasible
Trustless Parties can transact without trusting each other; code enforces rules
Distributed Thousands of copies of ledger exist across network nodes
Consensus Mechanisms:
Mechanism Description Used By
Miners solve complex math puzzle (hashing); high energy
Proof of Work (PoW) Bitcoin, Litecoin
consumption; secure
Validators stake (lock) cryptocurrency as collateral; energy
Proof of Stake (PoS) Ethereum 2.0, Cardano, Solana
efficient
Delegated PoS
Token holders vote for delegates who validate; faster EOS, TRON
(DPoS)
Proof of Authority Trusted validators; centralized but fast; for private
Hyperledger Besu
(PoA) blockchains
Byzantine Fault
System works even with some malicious nodes (< 1/3) Hyperledger Fabric, Tendermint
Tolerance (BFT)
Smart Contracts:
■ Smart Contract A smart contract is a self-executing program stored on a blockchain that
automatically enforces and executes the terms of an agreement when predefined
conditions are met. Code is law — no intermediary needed. Created by Nick
Szabo (1994). Deployed on Ethereum using Solidity programming language.
Blockchain Applications:
Domain Application Examples
Cryptocurrencies, DeFi, cross-border
Finance Bitcoin, Ethereum, Ripple
payments
Product tracking from manufacturer to
Supply Chain IBM Food Trust, VeChain
consumer
Healthcare Secure patient records, drug traceability MedRec, PharmaLedger
Voting Tamper-proof electronic voting systems Voatz, Follow My Vote
Decentralized digital identity
Identity Civic, SelfKey, uPort
management
Real Estate Property transfer records, smart contracts Propy, Harbor
Non-Fungible Tokens for digital
NFT / Art OpenSea, CryptoPunks
ownership
Land registry, public records, document
Government India's land records (pilot)
verification
■ 7.6 Cybersecurity & Cryptography
Term Definition
Cryptography Science of securing information by transforming it into unreadable form
Encryption Converting plaintext to ciphertext using an algorithm and key
Decryption Converting ciphertext back to plaintext using the correct key
Symmetric Encryption Same key for both encryption and decryption (AES, DES, 3DES, RC4) — fast
Asymmetric Encryption Public key encrypts, private key decrypts (RSA, ECC) — secure for key exchange
One-way function converting data to fixed-length hash (MD5=128bit, SHA-256=256bit) —
Hashing
no decryption
Salt Random data added before hashing passwords to prevent rainbow table attacks
Digital Signature Hash of message encrypted with sender's private key; verifies authenticity + integrity
PKI Public Key Infrastructure; framework for managing digital certificates and public keys
SSL/TLS Protocols encrypting web communication; TLS is updated SSL; used in HTTPS
Certificate Authority Trusted entity issuing digital certificates (VeriSign, DigiCert, Let's Encrypt)
Zero-Knowledge Proof Proving knowledge of information without revealing it
■ Unit 1: C Language ■ Unit 2: C++ Language ■ Unit 3: Java
■ Unit 4: Python ■ Unit 5: Data Structures ■ Unit 6: OOP Pillars
■ Unit 7: AI / ML / Blockchain
All the best for your Semester Exam! ■ Study Smart, Not Just Hard!