đ 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 Universal Asynchronous Receiver-Transmitter (UART) serial framing protocol (8-N-1 / 8-E-1) and Longitudinal Redundancy Check (LRC) checksum from scratch.
Prerequisites & Domain Concepts
Serial communications, bit shifting, parity generation, XOR bitwise operations.
Asymptotic Complexity Bounds
âĸ Time Complexity: O(1) encode/decode per byte
âĸ Space Complexity: O(1) storage for 11-bit list frame
Step-by-Step Algorithm
- Step 1: Define encode_uart_byte(byte_val, parity_type="EVEN"): start_bit = 0, data_bits = 8 bits LSB first.
- Step 2: Compute Parity: for EVEN parity, count 1s in byte_val; parity = 1 if count is odd else 0 (making total 1s even).
- Step 3: Append stop_bit = 1. Output 11-bit serial frame: [Start(0), D0, D1, D2, D3, D4, D5, D6, D7, Parity, Stop(1)].
- Step 4: Implement decode_uart_frame(bit_list): verify bit_list[0] == 0 (valid Start bit) and bit_list[10] == 1 (valid Stop bit).
- Step 5: Reconstruct data byte from bits 1..8 (sum(bit[i] << (i-1))).
- Step 6: Recompute parity and check for Parity Error.
- Step 7: Encode a packet message with an XOR Checksum trailer; inject a simulated single-bit wire error and verify detection.
- Step 8: Output UART bit timing diagrams and protocol audit.
Verified Academic Source Code (PYTHON)
class UARTSimulator:
def __init__(self, baud_rate=9600, parity="EVEN"):
self.baud_rate = baud_rate
self.bit_duration_us = (1.0 / baud_rate) * 1e6 # microseconds per bit
self.parity = parity.upper()
def _compute_parity_bit(self, byte_val):
count_ones = bin(byte_val).count('1')
if self.parity == "EVEN":
return 1 if (count_ones % 2 != 0) else 0
elif self.parity == "ODD":
return 1 if (count_ones % 2 == 0) else 0
return None # None for 'NONE' parity
def encode_byte_to_frame(self, byte_val):
"""Builds standard 8-E-1 / 8-O-1 UART frame (LSB first)"""
frame = [0] # 1. Start Bit (Always 0)
# 2. 8 Data Bits (LSB first)
for i in range(8):
bit = (byte_val >> i) & 1
frame.append(bit)
# 3. Optional Parity Bit
if self.parity in ("EVEN", "ODD"):
frame.append(self._compute_parity_bit(byte_val))
# 4. Stop Bit (Always 1)
frame.append(1)
return frame
def decode_frame_to_byte(self, frame_bits):
"""Decodes frame, checks Start/Stop framing and Parity integrity"""
# Framing check: Start must be 0, Stop must be 1
if frame_bits[0] != 0:
return None, "FRAMING_ERROR: Invalid Start bit (Expected 0)"
if frame_bits[-1] != 1:
return None, "FRAMING_ERROR: Invalid Stop bit (Expected 1)"
# Reconstruct byte (Bits 1 to 8, LSB first)
data_byte = 0
for i in range(8):
data_byte |= (frame_bits[1 + i] << i)
# Parity check
if self.parity in ("EVEN", "ODD"):
received_parity = frame_bits[9]
expected_parity = self._compute_parity_bit(data_byte)
if received_parity != expected_parity:
return data_byte, f"PARITY_ERROR: Expected {expected_parity}, got {received_parity}"
return data_byte, "OK"
# Execution Simulation: Transmitting "IOT" over 9600-Baud UART (8-E-1)
uart = UARTSimulator(baud_rate=9600, parity="EVEN")
message = "IOT"
print("=== UART Asynchronous Serial Protocol (8-E-1) ===")
print(f"Baud Rate : {uart.baud_rate} bps | Bit Duration: {uart.bit_duration_us:.2f} us")
print(f"Frame Format: 1 Start Bit + 8 Data Bits (LSB First) + 1 Even Parity Bit + 1 Stop Bit (11 bits total)\n")
# Transmit each character
transmitted_frames = []
for char in message:
byte_val = ord(char)
frame = uart.encode_byte_to_frame(byte_val)
transmitted_frames.append((char, byte_val, frame))
print("--- Transmitter Encoding ---")
for char, val, frame in transmitted_frames:
bit_str = "".join(str(b) for b in frame)
# Highlight frame components: [Start | D0-D7 | Parity | Stop]
annotated = f"Start({frame[0]}) Data({''.join(str(b) for b in frame[1:9])}) Parity({frame[9]}) Stop({frame[10]})"
print(f"Char '{char}' (0x{val:02X}) -> Wire Bits: {bit_str} | {annotated}")
# Receiver Decoding with Integrity Check
print("\n--- Receiver Decoding (Noise-Free Channel) ---")
for char, val, frame in transmitted_frames:
decoded_byte, status = uart.decode_frame_to_byte(frame)
print(f"Received Bits: {''.join(str(b) for b in frame)} -> Decoded: '{chr(decoded_byte)}' (Status: {status})")
# Simulated Noise Corruption (Flipping Bit 3 during transmission)
print("\n--- Noise Simulation: Corrupting 1 Data Bit in Transit ---")
corrupted_frame = list(transmitted_frames[0][2])
corrupted_frame[3] ^= 1 # Flip bit!
decoded_byte, status = uart.decode_frame_to_byte(corrupted_frame)
print(f"Corrupted Frame : {''.join(str(b) for b in corrupted_frame)}")
print(f"Receiver Action : {status} (Data Rejected due to Parity Mismatch!)")
Sample Test Input
Transmission of ASCII string "IOT" over 9600-baud 8-E-1 UART with 1-bit injected error
Expected Terminal Output
=== UART Asynchronous Serial Protocol (8-E-1) ===
Baud Rate : 9600 bps | Bit Duration: 104.17 us
Frame Format: 1 Start Bit + 8 Data Bits (LSB First) + 1 Even Parity Bit + 1 Stop Bit (11 bits total)
--- Transmitter Encoding ---
Char 'I' (0x49) -> Wire Bits: 01001001011 | Start(0) Data(10010010) Parity(1) Stop(1)
Char 'O' (0x4F) -> Wire Bits: 01111001011 | Start(0) Data(11110010) Parity(1) Stop(1)
Char 'T' (0x54) -> Wire Bits: 00010101011 | Start(0) Data(00101010) Parity(1) Stop(1)
--- Receiver Decoding (Noise-Free Channel) ---
Received Bits: 01001001011 -> Decoded: 'I' (Status: OK)
Received Bits: 01111001011 -> Decoded: 'O' (Status: OK)
Received Bits: 00010101011 -> Decoded: 'T' (Status: OK)
--- Noise Simulation: Corrupting 1 Data Bit in Transit ---
Corrupted Frame : 01011001011
Receiver Action : PARITY_ERROR: Expected 0, got 1 (Data Rejected due to Parity Mismatch!)
University Viva Voce Questions & Model Answers:
âĸ Q: Why does UART not require a separate shared clock wire like SPI or I2C?
âĸ Answer: UART is asynchronous: timing is agreed upon beforehand via the configured Baud Rate. The receiver synchronizes its internal clock on the falling edge of the Start bit (HIGH to LOW transition) and samples incoming bits at the exact midpoint (T/2) of each bit period.
âĸ Q: What is a UART Framing Error and what causes it?
âĸ Answer: A Framing Error occurs when the receiver samples where the Stop Bit should be (expecting a HIGH logic level) but detects a LOW level instead. This is commonly caused by mismatched baud rates, clock drift, or electrical line noise.
âĸ Q: What is the meaning of the notation "9600 8-N-1"?
âĸ Answer: 9600 Baud rate (9600 bits per second), 8 Data bits per frame, No parity bit (N), and 1 Stop bit. It is the most common default serial configuration in computer science.
âĸ Q: Why is RS-232 voltage signaling different from TTL UART?
âĸ Answer: Microcontroller TTL UART uses 0V for logic 0 and 3.3V/5V for logic 1. RS-232 uses inverted bipolar voltages (+3V to +15V for logic 0, -3V to -15V for logic 1) to resist noise over long industrial cables. A level shifter (like MAX232) is required between them.
âĸ Q: What is the role of RTS/CTS hardware flow control in UART?
âĸ Answer: Request to Send (RTS) and Clear to Send (CTS) are two dedicated control lines that allow a receiver to signal to the transmitter when its internal FIFO buffer is full, pausing transmission to prevent buffer overflow.