đ 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 the Inter-Integrated Circuit (I2C) synchronous serial bus protocol: Open-Drain pull-up bus lines, 7-bit slave addressing, ACK/NACK handshaking, and register read/write cycles.
Prerequisites & Domain Concepts
Synchronous serial communication, open-drain logic, pull-up resistors, 7-bit addressing.
Asymptotic Complexity Bounds
âĸ Time Complexity: O(B) clock cycles where B is number of bytes transmitted (9 clock cycles per byte)
âĸ Space Complexity: O(1) memory overhead
Step-by-Step Algorithm
- Step 1: Define I2CSlaveDevice with 7-bit address and internal register dictionary.
- Step 2: Construct I2CBusMaster managing communication states across SDA and SCL.
- Step 3: Implement start_condition(): SDA transitions from HIGH to LOW while SCL is HIGH.
- Step 4: Implement stop_condition(): SDA transitions from LOW to HIGH while SCL is HIGH.
- Step 5: Implement write_byte(byte): transmit 8 bits on clock pulses; sample 9th clock pulse for ACK (0 = ACK, 1 = NACK).
- Step 6: Address device: send (address << 1) | (0 for Write / 1 for Read). Check for ACK.
- Step 7: Perform Master Write to Temperature Sensor (0x48) setting configuration register 0x01 to 0x60.
- Step 8: Perform Master Read from Temperature Sensor reading raw temperature bytes.
- Step 9: Test addressing a non-existent slave (0x7F) and verify that NACK is received.
Verified Academic Source Code (PYTHON)
class I2CSlaveDevice:
def __init__(self, address_7bit, name):
self.address = address_7bit
self.name = name
self.registers = {
0x00: 0x19, # Temp Register: 25 degrees Celsius (0x19)
0x01: 0x00 # Config Register
}
def handle_address_match(self, addr, rw_bit):
return addr == self.address
def write_register(self, reg_addr, value):
self.registers[reg_addr] = value
return True # ACK
def read_register(self, reg_addr):
return self.registers.get(reg_addr, 0x00)
class I2CMaster:
def __init__(self):
self.slaves = {}
self.bus_log = []
def attach_slave(self, slave):
self.slaves[slave.address] = slave
def _log(self, event):
self.bus_log.append(event)
print(f" [I2C BUS] {event}")
def write_device_register(self, slave_addr, reg_addr, data_val):
print(f"\n--- Master Write Transaction -> Slave 0x{slave_addr:02X} ---")
self._log("START Condition (SDA HIGH->LOW while SCL=HIGH)")
# Byte 1: 7-bit Address + Write Bit (0)
addr_byte = (slave_addr << 1) | 0
if slave_addr not in self.slaves:
self._log(f"Send Address 0x{slave_addr:02X} + WRITE -> NACK (Device Not Found)")
self._log("STOP Condition")
return False
slave = self.slaves[slave_addr]
self._log(f"Send Address 0x{slave_addr:02X} + WRITE (0x{addr_byte:02X}) -> ACK from {slave.name}")
# Byte 2: Target Register Pointer
self._log(f"Send Register Pointer (0x{reg_addr:02X}) -> ACK")
# Byte 3: Data to Write
slave.write_register(reg_addr, data_val)
self._log(f"Send Data Byte (0x{data_val:02X}) -> ACK (Stored into register 0x{reg_addr:02X})")
self._log("STOP Condition (SDA LOW->HIGH while SCL=HIGH)")
return True
def read_device_register(self, slave_addr, reg_addr):
print(f"\n--- Master Read Transaction -> Slave 0x{slave_addr:02X} ---")
self._log("START Condition")
if slave_addr not in self.slaves:
self._log(f"Send Address 0x{slave_addr:02X} -> NACK")
self._log("STOP Condition")
return None
slave = self.slaves[slave_addr]
# Step A: Write register pointer
self._log(f"Send Address 0x{slave_addr:02X} + WRITE -> ACK")
self._log(f"Send Register Pointer (0x{reg_addr:02X}) -> ACK")
# Step B: Repeated START to change direction to READ
self._log("REPEATED-START Condition (Changing bus direction to READ)")
read_addr_byte = (slave_addr << 1) | 1
self._log(f"Send Address 0x{slave_addr:02X} + READ (0x{read_addr_byte:02X}) -> ACK from {slave.name}")
# Step C: Slave sends data; Master replies with NACK to end read
val = slave.read_register(reg_addr)
self._log(f"Receive Data (0x{val:02X}) from Slave -> Master sends NACK (Signaling end of read)")
self._log("STOP Condition")
return val
# Execution Simulation
master = I2CMaster()
temp_sensor = I2CSlaveDevice(0x48, "TMP102 Temperature Sensor")
eeprom = I2CSlaveDevice(0x50, "AT24C32 EEPROM")
master.attach_slave(temp_sensor)
master.attach_slave(eeprom)
print("=== I2C Two-Wire Bus Protocol Simulation ===")
print("Bus Configuration : 2 Bidirectional Open-Drain lines (SDA, SCL) with Pull-up Resistors")
print(f"Attached Slaves : {temp_sensor.name} (0x48), {eeprom.name} (0x50)")
# 1. Master Writes to Sensor Configuration Register
master.write_device_register(slave_addr=0x48, reg_addr=0x01, data_val=0x60)
# 2. Master Reads Temperature from Sensor
temp_val = master.read_device_register(slave_addr=0x48, reg_addr=0x00)
print(f"\n>>> Temperature Value Retrieved: 0x{temp_val:02X} = {temp_val}°C")
# 3. Master Probes a Non-Existent Device Address (0x7A)
master.write_device_register(slave_addr=0x7A, reg_addr=0x00, data_val=0xFF)
Sample Test Input
I2C Master write and read cycles with 7-bit slaves 0x48 and 0x50; NACK probe on 0x7A
Expected Terminal Output
=== I2C Two-Wire Bus Protocol Simulation ===
Bus Configuration : 2 Bidirectional Open-Drain lines (SDA, SCL) with Pull-up Resistors
Attached Slaves : TMP102 Temperature Sensor (0x48), AT24C32 EEPROM (0x50)
--- Master Write Transaction -> Slave 0x48 ---
[I2C BUS] START Condition (SDA HIGH->LOW while SCL=HIGH)
[I2C BUS] Send Address 0x48 + WRITE (0x90) -> ACK from TMP102 Temperature Sensor
[I2C BUS] Send Register Pointer (0x01) -> ACK
[I2C BUS] Send Data Byte (0x60) -> ACK (Stored into register 0x01)
[I2C BUS] STOP Condition (SDA LOW->HIGH while SCL=HIGH)
--- Master Read Transaction -> Slave 0x48 ---
[I2C BUS] START Condition
[I2C BUS] Send Address 0x48 + WRITE -> ACK
[I2C BUS] Send Register Pointer (0x00) -> ACK
[I2C BUS] REPEATED-START Condition (Changing bus direction to READ)
[I2C BUS] Send Address 0x48 + READ (0x91) -> ACK from TMP102 Temperature Sensor
[I2C BUS] Receive Data (0x19) from Slave -> Master sends NACK (Signaling end of read)
[I2C BUS] STOP Condition
>>> Temperature Value Retrieved: 0x19 = 25°C
--- Master Write Transaction -> Slave 0x7A ---
[I2C BUS] START Condition (SDA HIGH->LOW while SCL=HIGH)
[I2C BUS] Send Address 0x7A + WRITE -> NACK (Device Not Found)
[I2C BUS] STOP Condition
University Viva Voce Questions & Model Answers:
âĸ Q: Why are I2C bus lines (SDA and SCL) designed as Open-Drain with pull-up resistors?
âĸ Answer: Open-drain logic allows multiple devices to be connected in parallel on the same wire without danger of electrical short circuits. If two devices transmit at once, the line behaves as a "Wired-AND" gate, enabling clock synchronization (Clock Stretching) and multi-master collision arbitration.
âĸ Q: How are I2C START and STOP conditions defined?
âĸ Answer: A START condition is defined as a HIGH-to-LOW transition on SDA while SCL is held HIGH. A STOP condition is defined as a LOW-to-HIGH transition on SDA while SCL is held HIGH. During normal data bit transmission, SDA must remain stable while SCL is HIGH.
âĸ Q: What is the function of the ACK and NACK bit on the 9th clock pulse?
âĸ Answer: After every 8-bit byte transfer, the transmitter releases SDA. During the 9th clock pulse, the receiver pulls SDA LOW to signal Acknowledge (ACK=0). If SDA remains floating HIGH, it indicates a Not-Acknowledge (NACK=1), signaling an error or end of read.
âĸ Q: What is Clock Stretching in I2C?
âĸ Answer: If a slow slave device needs more time to process data or analog conversions, it can hold the SCL clock line LOW after receiving a byte. The master senses this and pauses its clock until the slave releases SCL back HIGH.
âĸ Q: How does I2C multi-master arbitration work?
âĸ Answer: When two masters start transmitting simultaneously, each monitors the SDA line. If a master sends a 1 (floats high) but reads back a 0 (because the other master pulled SDA low), it realizes it lost arbitration and immediately releases the bus without data corruption.