đ University Curriculum & Practical Lab Manuals
Computer Science Practical Labs Catalog
Explore 14 standardized computer science practical laboratory categories. Every experiment includes formal Aims, Learning Objectives, Algorithms, Verified Source Code, Sample Inputs/Outputs, Test Cases, and Viva Voce Q&As.
Categories: 14 Subjects (A to N)
Format: 18-Point Standard
Execution: Client-Side & 100% Free
Direct: 1-Click Open in IDE
To ensure strict adherence to university academic grading criteria and accreditation bodies, every engineering practical laboratory experiment on VAB-CODE follows the standardized 18-point documentation structure:
Points 1 to 9: Formulation & Design
1. Experiment Title & Date: Clear curricular identifier.
2. Aim / Problem Statement: Concise statement of technical objective.
3. Apparatus & Software Environment: Compiler versions (GCC, Java 17, Python 3.11, MySQL).
4. Learning Objectives: Specific skills and competencies acquired.
5. Theoretical Background: Underlying mathematical or algorithmic foundations.
6. Mathematical Equations: Formal equations, asymptotic bounds, and formulas.
7. Architectural Flowchart: Logic diagram depicting program execution flow.
8. Step-by-Step Algorithm: Language-agnostic pseudocode steps.
9. Input Data Specifications: Domain constraints and variable ranges.
Points 10 to 18: Implementation & Evaluation
10. Complete Source Code: Syntactically verified and fully indented code.
11. Comments & Error Handling: Boundary safety and explanatory annotations.
12. Compilation & Build Commands: Exact terminal CLI invocation.
13. Sample Test Case (Nominal): Standard expected input and output.
14. Boundary Test Case (Edge): Zero, null, negative, or max-scale inputs.
15. Expected Terminal Output: Exact stdout transcript.
16. Result & Conclusion: Verification that the stated aim was fulfilled.
17. Viva Voce Questions & Model Answers: Oral examination preparation.
18. Academic References: Standard textbooks (Cormen, Silberschatz, Tanenbaum).
Data structures establish memory layout models and access patterns for algorithmic processing. Linear data structures (arrays, linked lists, stacks, queues) enforce sequential predecessor-successor relationships, whereas non-linear structures (trees, graphs) represent hierarchical and arbitrary network topologies.
Experiment 1: Implementation of Singly Linked List Operations
Aim: To write a modular C program to implement dynamic singly linked list operations: insertion at beginning/end, deletion by value, reversal of nodes, and display.
Algorithm:
1. Define struct Node containing integer data and pointer struct Node* next.
2. Insert at Beginning: Allocate memory via malloc(sizeof(struct Node)). Set newNode->next = head; update head = newNode.
3. Reverse: Initialize three pointers: prev = NULL, curr = head, next = NULL. In a loop while curr != NULL: save next = curr->next; reverse pointer curr->next = prev; advance prev = curr; advance curr = next. Set head = prev.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* insertBeginning(struct Node* head, int val) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) { printf("Memory allocation failed!\n"); exit(1); }
newNode->data = val;
newNode->next = head;
return newNode;
}
struct Node* reverseList(struct Node* head) {
struct Node *prev = NULL, *curr = head, *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void printList(struct Node* head) {
struct Node* temp = head;
while (temp) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
Viva Voce Questions:
âĸ Q: Why is pointer reversal performed in $O(1)$ auxiliary space?
âĸ Answer: Three temporary pointer variables (prev, curr, next) are reused across all loop iterations without allocating new heap memory, bounding space to $O(1)$.
Object-oriented design organizes code around self-contained entities (objects) encapsulating state (attributes) and behavior (methods). Java implements concurrency using monitors and intrinsic thread locks.
Experiment 2: Inter-Thread Communication (Producer-Consumer Problem)
Aim: To demonstrate thread synchronization and inter-thread signaling in Java using a bounded buffer with synchronized methods, wait(), and notify().
Theory: When multiple concurrent threads access shared mutable state, race conditions emerge. Using intrinsic object monitors, the Producer thread waits when the buffer is full, and the Consumer thread waits when the buffer is empty.
import java.util.LinkedList;
import java.util.Queue;
class BoundedBuffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int CAPACITY = 5;
public synchronized void produce(int item) throws InterruptedException {
while (queue.size() == CAPACITY) {
wait(); // Buffer full: release monitor and sleep
}
queue.add(item);
System.out.println("Produced: " + item + " | Buffer size: " + queue.size());
notifyAll(); // Wake up waiting consumer threads
}
public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
wait(); // Buffer empty: release monitor and sleep
}
int item = queue.poll();
System.out.println("Consumed: " + item + " | Buffer size: " + queue.size());
notifyAll(); // Wake up waiting producer threads
return item;
}
}
Viva Voce Questions:
âĸ Q: Why must wait() always be called inside a while loop instead of an if statement?
âĸ Answer: To guard against spurious wakeups, where a thread resumes execution without an explicit signal. The while loop re-checks the condition predicate before proceeding.
Relational databases store structured schemas governed by foreign keys and integrity constraints. SQL provides declarative data definition (DDL) and manipulation (DML).
Experiment 3: SQL Relational Queries, Grouping & Triggers
Aim: Create a University database schema (Department, Student, Course, Enrollment) and execute nested queries with GROUP BY, HAVING, and an automated audit trigger.
-- Schema Definition
CREATE TABLE Student (
student_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
dept_id INT,
gpa DECIMAL(3,2)
);
CREATE TABLE CourseEnrollment (
enrollment_id INT PRIMARY KEY,
student_id INT,
course_name VARCHAR(50),
grade VARCHAR(2),
FOREIGN KEY (student_id) REFERENCES Student(student_id)
);
-- Advanced Aggregation Query: Students with above-average GPA per Department
SELECT s.student_id, s.name, s.gpa, s.dept_id
FROM Student s
WHERE s.gpa > (
SELECT AVG(s2.gpa)
FROM Student s2
WHERE s2.dept_id = s.dept_id
);
Viva Voce Questions:
âĸ Q: What is the semantic difference between WHERE and HAVING in SQL?
âĸ Answer: The WHERE clause filters individual records before aggregation occurs; the HAVING clause filters aggregated groups produced by GROUP BY.
System programming interfaces directly with the operating system kernel via system calls to manage processes, file descriptors, and virtual memory.
Experiment 4: Round Robin CPU Scheduling Simulation in C
Aim: Implement Round Robin scheduling with a given time quantum $Q$ to compute turnaround times, waiting times, and average response metrics.
#include <stdio.h>
void roundRobin(int n, int burst[], int quantum) {
int rem_burst[n];
for (int i = 0; i < n; i++) rem_burst[i] = burst[i];
int t = 0; // Current time
int wait_time[n];
for (int i = 0; i < n; i++) wait_time[i] = 0;
while (1) {
int done = 1;
for (int i = 0; i < n; i++) {
if (rem_burst[i] > 0) {
done = 0;
if (rem_burst[i] > quantum) {
t += quantum;
rem_burst[i] -= quantum;
} else {
t += rem_burst[i];
wait_time[i] = t - burst[i];
rem_burst[i] = 0;
}
}
}
if (done == 1) break;
}
printf("PID\tBurst\tWaiting\tTurnaround\n");
for (int i = 0; i < n; i++) {
printf("P%d\t%d\t%d\t%d\n", i+1, burst[i], wait_time[i], wait_time[i] + burst[i]);
}
}
Viva Voce Questions:
âĸ Q: How does time quantum size affect Round Robin performance?
âĸ Answer: An excessively large time quantum reduces Round Robin to FCFS; an excessively small quantum causes high context-switching overhead, degrading CPU throughput.
Socket programming enables inter-process network communication across distributed machines using IP addressing and port numbers.
Experiment 5: Client-Server TCP Echo Socket in Python
Aim: Implement an iterative TCP echo server and client using the standard Python socket library.
# Python 3: TCP Echo Server Implementation
import socket
def run_server():
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind(('127.0.0.1', 8080))
server_sock.listen(5)
print("TCP Server listening on 127.0.0.1:8080...")
while True:
client_sock, client_addr = server_sock.accept()
print(f"Connection established from {client_addr}")
data = client_sock.recv(1024)
if data:
print(f"Received payload: {data.decode()}")
client_sock.sendall(data) # Echo data back
client_sock.close()
Viva Voce Questions:
âĸ Q: Why is SO_REUSEADDR recommended for TCP server sockets?
âĸ Answer: It allows the server to immediately re-bind to the port even if previously closed sockets remain in the kernel's TIME_WAIT state.
Machine learning builds predictive data-driven models by discovering functional mappings $f(X) \approx Y$ from empirical training sets.
Experiment 6: Supervised Classification with Decision Trees & Evaluation
Aim: Train a Decision Tree classifier, compute the Confusion Matrix, and calculate Accuracy, Precision, Recall, and F1-Score metrics.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report, confusion_matrix
# Load dataset and partition 80/20
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
# Train Decision Tree with Gini Impurity
clf = DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=42)
clf.fit(X_train, y_train)
# Evaluate model predictions
y_pred = clf.predict(X_test)
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred, target_names=iris.target_names))
Viva Voce Questions:
âĸ Q: Why is Precision preferred over Accuracy in imbalanced datasets?
âĸ Answer: Accuracy is deceptive when the majority class dominates (e.g. 99% negative cases); Precision ($TP / (TP + FP)$) measures exactness among positive predictions regardless of negative class volume.
Aim / Objective: To formulate, implement, and analyze a Consistent Hashing Ring with virtual nodes from scratch for distributed caching and database partitioning.
Prerequisites & Domain Concepts
Cryptographic hash functions, binary search (bisect), modular arithmetic, distributed systems concepts.
Asymptotic Complexity Bounds
âĸ Time Complexity: Lookup: O(log(V * N)) where N is physical nodes and V is virtual node count; Add/Remove: O(V * log(V * N))
âĸ Space Complexity: O(V * N) to store the virtual node list and lookup map
Step-by-Step Algorithm
- Step 1: Define hash_val(key) computing 32-bit integer digest using hashlib.md5.
- Step 2: Construct ConsistentHashRing class with replicas parameter (virtual nodes per server).
- Step 3: Implement add_node(node): for i in range(replicas), hash f"{node}#vnode{i}" and insert into sorted ring list with map to physical node.
- Step 4: Implement get_node(key): hash key, use bisect_right to find first node on ring clockwise. If past end of ring, wrap around to index 0.
- Step 5: Seed ring with servers ["cache-alpha", "cache-beta", "cache-gamma"].
- Step 6: Map a batch of 10 keys and record initial server distribution.
- Step 7: Add new server "cache-delta" and re-evaluate mapping.
- Step 8: Output churn report showing that only a small fraction of keys relocated, preserving cache hit ratios.
Verified Academic Source Code (PYTHON)
import hashlib
import bisect
class ConsistentHashRing:
def __init__(self, replicas=3):
self.replicas = replicas
self.ring = [] # Sorted list of virtual node hash integers
self.vnode_to_node = {} # Map: hash integer -> physical node name
self.physical_nodes = set()
def _hash(self, key):
"""Generates 32-bit integer hash from MD5 digest"""
return int(hashlib.md5(key.encode('utf-8')).hexdigest()[:8], 16)
def add_node(self, node):
self.physical_nodes.add(node)
for i in range(self.replicas):
vnode_name = f"{node}#vnode{i}"
h = self._hash(vnode_name)
bisect.insort(self.ring, h)
self.vnode_to_node[h] = node
def remove_node(self, node):
if node not in self.physical_nodes:
return
self.physical_nodes.remove(node)
for i in range(self.replicas):
vnode_name = f"{node}#vnode{i}"
h = self._hash(vnode_name)
idx = bisect.bisect_left(self.ring, h)
if idx < len(self.ring) and self.ring[idx] == h:
del self.ring[idx]
del self.vnode_to_node[h]
def get_node(self, key):
"""Routes key to first server encountered clockwise on the ring"""
if not self.ring:
return None
h = self._hash(key)
# Find first virtual node with hash >= h
idx = bisect.bisect_right(self.ring, h)
if idx == len(self.ring):
idx = 0 # Wrap around ring boundary
return self.vnode_to_node[self.ring[idx]]
# Initialize Distributed Cache Cluster
ring = ConsistentHashRing(replicas=3)
initial_servers = ["cache-alpha", "cache-beta", "cache-gamma"]
for server in initial_servers:
ring.add_node(server)
print("=== Consistent Hashing Ring Simulation ===")
print(f"Active Cluster Servers: {initial_servers}")
print(f"Total Virtual Nodes on Ring: {len(ring.ring)} (3 replicas per physical node)\n")
# Sample cache request keys
cache_keys = [
"user:profile:1001", "session:tok_9981", "product:sku_452",
"cart:usr_3310", "order:inv_8821", "image:thumb_102",
"video:stream_50", "analytics:ev_12", "auth:jwt_99120",
"comment:post_77"
]
# Initial Key Distribution
initial_mapping = {}
print("--- Initial Key Routing across 3 Cache Servers ---")
for k in cache_keys:
server = ring.get_node(k)
initial_mapping[k] = server
print(f" Key '{k:20}' -> Routed to [{server}]")
# Scale Up: Adding a 4th Server
new_server = "cache-delta"
print(f"\n>>> SCALING EVENT: Adding new server '{new_server}' to cluster...\n")
ring.add_node(new_server)
# Re-evaluating key distribution after scaling
new_mapping = {}
relocated_count = 0
print("--- Post-Scaling Key Routing across 4 Cache Servers ---")
for k in cache_keys:
server = ring.get_node(k)
new_mapping[k] = server
changed = server != initial_mapping[k]
if changed:
relocated_count += 1
status = f"[RELOCATED: {initial_mapping[k]} -> {server}]"
else:
status = f"[PRESERVED on {server}]"
print(f" Key '{k:20}' -> {status}")
print(f"\n--- Scalability Impact Analysis ---")
print(f"Total Cache Keys Evaluated : {len(cache_keys)}")
print(f"Keys Preserved (Cache Hit) : {len(cache_keys) - relocated_count}")
print(f"Keys Relocated (Cache Miss): {relocated_count} ({relocated_count / len(cache_keys) * 100:.1f}%)")
print(f"Under naive modulo hashing (hash % N), scaling 3 -> 4 servers invalidates ~75% of all keys!")
Sample Test Input
3 initial servers, 10 cache keys; scaled up by adding "cache-delta"
Expected Terminal Output
=== Consistent Hashing Ring Simulation ===
Active Cluster Servers: ['cache-alpha', 'cache-beta', 'cache-gamma']
Total Virtual Nodes on Ring: 9 (3 replicas per physical node)
--- Initial Key Routing across 3 Cache Servers ---
Key 'user:profile:1001 ' -> Routed to [cache-gamma]
Key 'session:tok_9981 ' -> Routed to [cache-beta]
Key 'product:sku_452 ' -> Routed to [cache-gamma]
Key 'cart:usr_3310 ' -> Routed to [cache-alpha]
Key 'order:inv_8821 ' -> Routed to [cache-beta]
Key 'image:thumb_102 ' -> Routed to [cache-gamma]
Key 'video:stream_50 ' -> Routed to [cache-alpha]
Key 'analytics:ev_12 ' -> Routed to [cache-alpha]
Key 'auth:jwt_99120 ' -> Routed to [cache-beta]
Key 'comment:post_77 ' -> Routed to [cache-gamma]
>>> SCALING EVENT: Adding new server 'cache-delta' to cluster...
--- Post-Scaling Key Routing across 4 Cache Servers ---
Key 'user:profile:1001 ' -> [PRESERVED on cache-gamma]
Key 'session:tok_9981 ' -> [PRESERVED on cache-beta]
Key 'product:sku_452 ' -> [RELOCATED: cache-gamma -> cache-delta]
Key 'cart:usr_3310 ' -> [PRESERVED on cache-alpha]
Key 'order:inv_8821 ' -> [PRESERVED on cache-beta]
Key 'image:thumb_102 ' -> [PRESERVED on cache-gamma]
Key 'video:stream_50 ' -> [PRESERVED on cache-alpha]
Key 'analytics:ev_12 ' -> [RELOCATED: cache-alpha -> cache-delta]
Key 'auth:jwt_99120 ' -> [PRESERVED on cache-beta]
Key 'comment:post_77 ' -> [PRESERVED on cache-gamma]
--- Scalability Impact Analysis ---
Total Cache Keys Evaluated : 10
Keys Preserved (Cache Hit) : 8
Keys Relocated (Cache Miss): 2 (20.0%)
Under naive modulo hashing (hash % N), scaling 3 -> 4 servers invalidates ~75% of all keys!
University Viva Voce Questions & Model Answers:
âĸ Q: Why does naive modulo hashing (hash(key) % N) fail in elastic cloud environments?
âĸ Answer: When N changes due to scaling up or down, the denominator in the modulo operation changes for almost all keys, resulting in ~N/(N+1) (often 75-90%) of all keys mapping to new servers. This triggers a massive cache miss spike (rehash storm) that can crash backend databases.
âĸ Q: What are Virtual Nodes (vnodes) in consistent hashing and what problem do they solve?
âĸ Answer: With small numbers of physical servers, hash values can cluster randomly, leading to severe load imbalance ("hot spots"). Virtual nodes assign many virtual points (e.g. 150) on the ring to each physical server, ensuring a uniform distribution across the ring.
âĸ Q: How does consistent hashing support heterogeneous servers with different capacities?
âĸ Answer: A more powerful server with twice the RAM or CPU can be assigned twice as many virtual nodes on the ring, naturally receiving double the proportion of keys and traffic.
âĸ Q: How does consistent hashing enable replication in distributed databases (like DynamoDB or Cassandra)?
âĸ Answer: Instead of assigning a key only to the first clockwise node, the system stores replicas on the next N-1 distinct physical servers encountered while traversing clockwise on the ring.
âĸ Q: What is the time complexity of looking up a key on a consistent hash ring?
âĸ Answer: O(log(V * N)), where N is the number of physical nodes and V is the number of virtual nodes, using binary search on the sorted ring array.