JECA CODE REFERENCE NOTES
Short Codes with Line-by-Line Explanation | All Topics | Exam Ready
C PROGRAMMING — Essential Code Patterns
Pointers — Most Asked in JECA
int x = 10; int *p = &x; → p holds address of x
int *p = &x; // p stores address of x *p → dereference: get VALUE at address
printf("%d", *p); // prints 10 *p = 20 → changes original x through pointer
*p = 20; // changes x to 20 arr is same as &arr;[0]
// Array and pointer *(q+1) same as arr[1]
int arr[3] = {1,2,3}; TRICK: * means 'value at address'
int *q = arr; // q points to arr[0] & means 'address of variable'
printf("%d", *(q+1)); // prints arr[1]=2
Structures + typedef
struct Student { struct groups different data types
int roll; typedef creates alias: STU = Student
char name[20]; Access members with dot (.) operator
}; [Link] → accesses roll of s1
typedef struct Student STU; strcpy() → copy string (use for char[])
STU s1; TRICK: struct = custom data type
[Link] = 10; Union = same, but shared memory
strcpy([Link], "Ram");
printf("%d %s", [Link], [Link]);
File Handling in C
FILE *fp; FILE *fp → file pointer
fp = fopen("[Link]", "w"); fopen(name, mode) → opens file
fprintf(fp, "Hello %d", 10); modes: r=read, w=write, a=append
fclose(fp); fprintf → write formatted to file
// Reading fclose → always close file!
fp = fopen("[Link]", "r"); fscanf → read formatted from file
int n; feof(fp) → check end of file
fscanf(fp, "%d", &n;); TRICK: fopen returns NULL if fails → check!
fclose(fp);
POINTER TRICK: int *p = &x; | *p = value | &x; = address | arr = &arr;[0] | FILES: fopen(file, mode) | fprintf = write | fscanf = read | fclose = close | feof =
*(arr+i) = arr[i] end check
OOP & C++ — Core Code Patterns
Class, Constructor, Destructor
class Demo { class keyword to define blueprint
int x; // private by default private: only inside class
public: public: accessible everywhere
Demo() // default constructor Constructor: same name, no return type
{ x = 0; cout<<"Created"; } Auto-called when object created
Demo(int a) // parameterized Copy constructor: takes object reference
{ x = a; } Used when: Demo d3 = d2;
Demo(Demo &d;) // copy constructor Destructor: ~ prefix, auto-called on destroy
{ x = d.x; } Use for memory cleanup
~Demo() // destructor TRICK: Constructor = born | Destructor = died
{ cout<<"Destroyed"; } Multiple constructors = constructor overloading
void show(){ cout<<x; } Destructor CANNOT be overloaded!
};
// Usage:
Demo d1; // calls default
Demo d2(10); // calls parameterized
Demo d3(d2); // calls copy
Inheritance + Virtual Functions
class Animal { class Dog : public Animal
public: = Dog inherits Animal (public)
virtual void speak() { // virtual! virtual keyword → runtime binding
cout<<"Some sound"; Without virtual → 'Some sound' (wrong)
} With virtual → 'Woof' (correct!)
}; Animal *a = new Dog() → base pointer
class Dog : public Animal { pointing to derived object
public: THIS is runtime polymorphism!
void speak() { // override vtable behind the scenes decides
cout<<"Woof"; which function to call at runtime
} Pure virtual: virtual void f()=0;
}; Makes Animal an Abstract Class
// Runtime polymorphism:
Animal *a = new Dog();
a->speak(); // prints 'Woof' NOT 'Some sound'
Operator Overloading
class Complex { operator+ → overloads + for Complex type
int r, i; Syntax: returnType operator symbol(params)
public: c1 + c2 automatically calls
Complex(int a, int b) [Link]+(c2)
{ r=a; i=b; } Returns new Complex with added values
Complex operator+(Complex c) { CANNOT overload:
return Complex(r+c.r, i+c.i); ::(scope), .*(member ptr),
} .(dot), ?:(ternary), sizeof
void show() TRICK: operator keyword + symbol
{ cout<<r<<"+"<<i<<"i"; } Makes objects behave like int/float
};
// Usage:
Complex c1(2,3), c2(4,5);
Complex c3 = c1 + c2; // uses overload
[Link](); // prints 6+8i
Templates — Generic Programming
// Function Template template → T is placeholder type
template<class T> Compiler creates specific version when called
T add(T a, T b) { add(3,4) → T becomes int automatically
return a + b; add(1.5,2.5) → T becomes float
} WRITE ONCE, USE FOR ANY TYPE!
// Works for ANY type: Class template: Box means T=int
cout << add(3, 4); // 7 (int) Box means T=string
cout << add(1.5, 2.5); // 4.0 (float) Foundation of STL (vector, stack etc)
// Class Template vector → T=int
template<class T> vector → T=string
class Box { TRICK: T is just a placeholder name
T data; Could be written as 'class X' too
public:
Box(T d) { data = d; }
T get() { return data; }
};
Box<int> b1(10);
Box<string> b2("hi");
virtual = runtime poly | without virtual = compile-time (wrong binding) template → T is any type | write once work for all
Exception Handling + STL + SQL Codes
Exception Handling — try/catch/throw
int divide(int a, int b) { throw → sends error to nearest catch
if(b == 0) try block → surround risky code
throw "Divide by zero!"; // throw catch → handles specific error type
return a / b; throw "message" → throws string
} catch(const char* e) → catches string
int main() { catch(...) → catches ANY exception
try { = safety net at the end
cout << divide(10, 0); FLOW: try runs → error occurs → throw
} → matching catch runs → program continues
catch(const char* e) { // catch string Without try-catch → program CRASHES
cout << "Error: " << e; With try-catch → program handles gracefully
} TRICK: try=attempt | throw=alarm | catch=handle
catch(...) { // catch ANYTHING
cout << "Unknown error";
}
return 0;
}
STL — Vector, Map, Stack, Queue
#include<vector> vector = array that grows automatically
#include<map> push_back = add to end
#include<stack> pop_back = remove from end
#include<algorithm> v[i] = access by index
// VECTOR (dynamic array) [Link]() = number of elements
vector<int> v = {1,2,3}; Range-for: for(int x : v)
v.push_back(4); // add at end = modern C++ loop, very clean
v.pop_back(); // remove from end map stores key-value pairs
cout << [Link](); // 3 Automatically sorted by key
// Iterator traverse: m["key"] accesses value
for(int x : v) cout << x; // range-for stack = LIFO | top() = peek top
// MAP (key-value) push = add | pop = remove top
map<string,int> m; queue = FIFO | front() = peek front
m["Alice"] = 90; push = add | pop = remove front
cout << m["Alice"]; // 90 sort(begin, end) sorts in-place
// STACK (LIFO) STL = Containers + Iterators + Algorithms
stack<int> s;
[Link](10); [Link](20);
cout << [Link](); // 20
[Link](); // removes 20
// SORT algorithm
sort([Link](), [Link]());
SQL — Most Important Queries
-- CREATE TABLE CREATE TABLE → DDL command
CREATE TABLE Student( PRIMARY KEY → unique identifier, not null
roll INT PRIMARY KEY, INSERT INTO → DML command, adds row
name VARCHAR(20), SELECT → retrieves data
marks INT); WHERE → filter condition
-- INSERT ORDER BY → sort results
INSERT INTO Student VALUES(1,'Ram',85); DESC = descending, ASC = ascending
-- SELECT with WHERE GROUP BY → groups rows with same value
SELECT name, marks FROM Student HAVING → filter AFTER grouping
WHERE marks > 60 (WHERE filters before grouping)
ORDER BY marks DESC; JOIN → combines two tables
-- GROUP BY + HAVING ON → join condition (matching keys)
SELECT dept, AVG(marks) INNER JOIN = only matching rows
FROM Student LEFT JOIN = all left + matching right
GROUP BY dept UPDATE → modifies existing data
HAVING AVG(marks) > 70; DELETE → removes rows
-- JOIN DROP TABLE → removes entire table
SELECT [Link], [Link] TRICK: WHERE=before group | HAVING=after group
FROM Student S
JOIN Enroll E ON [Link]=[Link]
JOIN Course C ON [Link]=[Link];
-- UPDATE / DELETE
UPDATE Student SET marks=90
WHERE roll=1;
DELETE FROM Student WHERE roll=1;
SQL ORDER: SELECT→FROM→WHERE→GROUP BY→HAVING→ORDER DDL:CREATE/ALTER/DROP | DML:INSERT/UPDATE/DELETE |
BY DCL:GRANT/REVOKE
DATA STRUCTURES — Code Patterns
Stack Implementation (Array-based)
#define MAX 100 top = -1 means stack is EMPTY
int stack[MAX], top = -1; top = MAX-1 means stack is FULL
void push(int x) { push: first increment top (++top)
if(top == MAX-1) then store value at that position
printf("Stack Full!"); pop: return value, then decrement (top--)
else postfix -- means decrement AFTER use
stack[++top] = x; peek: just look at top, don't remove
} TRICK: Stack = plates pile
int pop() { Last plate placed = First plate taken
if(top == -1) = LIFO (Last In First Out)
printf("Stack Empty!"); Applications: Recursion, Undo, Brackets check
else
return stack[top--];
}
int peek() { return stack[top]; }
Linked List — Insert and Display
struct Node { Node = basic unit of linked list
int data; data = stores value
Node *next; next = pointer to next node
}; head = pointer to first node
Node *head = NULL; head = NULL means empty list
// Insert at front new Node() → creates node in heap memory
void insertFront(int val) { n->data → use arrow (->) for pointer access
Node *n = new Node(); [Link] → use dot (.) for direct object
n->data = val; insertFront: new node's next = old head
n->next = head; then head = new node
head = n; display: start at head, follow next
} until NULL (end of list)
// Display all nodes TRICK: -> = arrow for pointer to struct/class
void display() { . = dot for direct object access
Node *curr = head;
while(curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
}
Binary Search + Sorting Algorithms
// BINARY SEARCH (array must be sorted!) Binary Search = divide and conquer
int binarySearch(int arr[], int n, int key){ Start: lo=0, hi=last index
int lo=0, hi=n-1; mid = middle index
while(lo <= hi) { If arr[mid] = key → FOUND!
int mid = (lo+hi)/2; If arr[mid] < key → go RIGHT (lo=mid+1)
if(arr[mid]==key) return mid; If arr[mid] > key → go LEFT (hi=mid-1)
else if(arr[mid]<key) lo=mid+1; Return -1 if not found
else hi=mid-1; Time: O(log n) — very fast!
} MUST: array must be SORTED first
return -1; // not found Bubble Sort: compare neighbors, swap if wrong
} After each outer pass, largest goes to end
// BUBBLE SORT O(n2) time — slow but simple
void bubbleSort(int arr[], int n){ COMPLEXITY TRICK:
for(int i=0;i<n-1;i++) Linear=O(n) | Binary=O(log n)
for(int j=0;j<n-i-1;j++) Bubble/Selection/Insertion=O(n2)
if(arr[j]>arr[j+1]) Quick/Merge=O(n log n)
swap(arr[j],arr[j+1]);
}
Stack(LIFO): top=-1 empty | top=MAX-1 full | push:++top | pop:top-- Binary Search: MUST be sorted | lo=0, hi=n-1, mid=(lo+hi)/2 | O(log n)
OS Scheduling + Network + ML Concepts (Visual Code)
CPU Scheduling — Round Robin Example
// Round Robin with Quantum = 2 Round Robin = fair scheduling
// Processes: P1(burst=5), P2(burst=3), P3(burst=4) Each process gets quantum time
// Gantt Chart: Then goes back to queue end
// |P1|P2|P3|P1|P3|P1| TAT = Completion - Arrival
// 0 2 4 6 8 10 11 WT = TAT - Burst
// After execution: RT = Start - Arrival
// P1: AT=0, BT=5, CT=11 STEP-BY-STEP:
// TAT = CT - AT = 11-0 = 11 1. List processes with burst times
// WT = TAT - BT = 11-5 = 6 2. Draw Gantt Chart with quantum slices
// P2: AT=0, BT=3, CT=6 3. Find completion time from chart
// TAT = 6-0 = 6 4. Calculate TAT = CT - AT
// WT = 6-3 = 3 5. Calculate WT = TAT - BT
// P3: AT=0, BT=4, CT=10 6. Average = sum / number of processes
// TAT = 10-0 = 10 TRICK: RR is FAIR — no starvation
// WT = 10-4 = 6 SJF = no starvation but optimal wait
// Avg WT = (6+3+6)/3 = 5 Priority = starvation possible
// Avg TAT = (11+6+10)/3 = 9 FCFS = convoy effect (long job blocks all)
Banker's Algorithm — Deadlock Avoidance
// 3 Processes, 3 Resource Types Banker's Algorithm = Deadlock AVOIDANCE
// Max Matrix: Key formula:
// A B C Need[i] = Max[i] - Allocation[i]
// P0: [ 7 5 3 ] ALGORITHM:
// P1: [ 3 2 2 ] 1. Calculate Need for all processes
// P2: [ 9 0 2 ] 2. Check which process's Need
// Allocation Matrix: <= Available resources
// P0: [ 0 1 0 ] 3. 'Grant' those resources temporarily
// P1: [ 2 0 0 ] 4. Add released resources to Available
// P2: [ 3 0 2 ] 5. Repeat until all processes done
// Available: A=3, B=3, C=2 If ALL processes finish = SAFE STATE
// STEP 1: Calculate Need: If some stuck = UNSAFE (potential deadlock)
// Need = Max - Allocation TRICK: Banker gives loan only if
// P0: 7-0, 5-1, 3-0 = [7,4,3] he can still satisfy all clients
// P1: 3-2, 2-0, 2-0 = [1,2,2] = System grants resource only if
// P2: 9-3, 0-0, 2-2 = [6,0,0] safe state is maintained after
// STEP 2: Find safe sequence: Need to memorize: Need=Max-Alloc
// Available=[3,3,2]
// P1 needs [1,2,2] <= [3,3,2] YES
// After P1: Available=[3,3,2]+[2,0,0]=[5,3,2]
// P2 needs [6,0,0] <= [5,3,2] NO
// ... P0 can run, then P2
// Safe Sequence: P1 -> P0 -> P2
Machine Learning — Decision Tree Logic + K-Means Steps
// DECISION TREE CONCEPT: Decision Tree: each node is a question
// [Age > 18?] Leaf node = final answer (class)
// / \ Root node = best splitting attribute
// YES NO (highest information gain)
// | | Entropy = measure of impurity
// [Income > 50k?] [Reject] Pure node (all same class) = Entropy 0
// / \ Mixed node = Entropy 1 (maximum)
// Approve Reject Information Gain = how much entropy
// HOW IT DECIDES WHICH ATTRIBUTE TO SPLIT ON: REDUCES after the split
// Calculate Entropy BEFORE split: = pick feature that gives most order
// High entropy = more mixed data (bad) K-Means = unsupervised clustering
// Low entropy = more pure data (good) K = number of clusters to find
// Information Gain = Entropy(before) - Entropy(after) Centroid = center of a cluster
// Pick attribute with HIGHEST Info Gain STEPS TRICK: Choose→Assign→Update→Repeat
// K-MEANS CLUSTERING STEPS: Converges when centroids stop moving
// Step 1: Choose K (say K=2) Labels NOT available in clustering
// Step 2: Randomly place 2 centroids vs Decision Tree where labels ARE available
// Step 3: Assign each point to nearest centroid Supervised = has labels (DT, SVM, ANN)
// Step 4: Recalculate centroid = mean of cluster Unsupervised = no labels (K-Means, clustering)
// Step 5: Repeat 3-4 until centroids don't move
// Result: K groups of similar data points
OS: TAT=CT-AT | WT=TAT-BT | Need=Max-Alloc | Safe sequence = no ML: Entropy=impurity | Info Gain=best split | K-Means:
deadlock Choose-Assign-Update-Repeat
BEST OF LUCK FOR JECA! Code PDF Complete — All Topics Covered!