๐ 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 Pulse Width Modulation (PWM) signal generation, duty cycle modulation, average voltage calculation, and DC motor velocity simulation.
Prerequisites & Domain Concepts
DC circuits, electrical power, timers/counters, motor electromechanical properties.
Asymptotic Complexity Bounds
โข Time Complexity: O(1) calculation per control cycle
โข Space Complexity: O(1) memory overhead
Step-by-Step Algorithm
- Step 1: Set PWM carrier frequency f = 1000 Hz (period T = 1.0 ms), supply V_cc = 12.0V.
- Step 2: Define motor constants: motor constant K_v = 150 RPM/Volt, internal resistance R = 2.0 ohms, no-load friction.
- Step 3: Define simulate_pwm_cycle(duty_cycle_pct, steps=20): generate 20 discrete time samples over 1 period. If step/steps < duty_cycle, output V_cc; else 0V.
- Step 4: Compute effective average voltage V_avg = (duty_cycle_pct / 100) * V_cc.
- Step 5: Compute motor terminal current and rotational speed: RPM = V_avg * K_v.
- Step 6: Sweep duty cycles: 0%, 25%, 50%, 75%, 100%.
- Step 7: Output waveform visualization and performance telemetry table.
Verified Academic Source Code (PYTHON)
class PWMMotorSimulator:
def __init__(self, v_supply=12.0, pwm_freq_hz=1000, motor_kv=150):
self.v_supply = v_supply
self.pwm_freq_hz = pwm_freq_hz
self.period_ms = (1.0 / pwm_freq_hz) * 1000.0
self.motor_kv = motor_kv # RPM per volt
def generate_pwm_waveform(self, duty_cycle_pct, samples=20):
"""Generates one period of discrete PWM signal samples"""
cutoff_sample = int(round((duty_cycle_pct / 100.0) * samples))
waveform = []
for i in range(samples):
volts = self.v_supply if i < cutoff_sample else 0.0
waveform.append(volts)
return waveform
def calculate_motor_response(self, duty_cycle_pct):
duty_fraction = max(0.0, min(100.0, duty_cycle_pct)) / 100.0
# Average delivered voltage: V_avg = D * V_supply
v_avg = duty_fraction * self.v_supply
# Steady-state rotational velocity: RPM = V_avg * K_v
rpm = v_avg * self.motor_kv
# Power dissipation approximation: P = (V_avg^2) / R (assuming 4 ohm coil)
power_watts = (v_avg ** 2) / 4.0 if v_avg > 0 else 0.0
return v_avg, rpm, power_watts
# Execution Simulation
motor_sim = PWMMotorSimulator(v_supply=12.0, pwm_freq_hz=1000, motor_kv=150)
print("=== Pulse Width Modulation (PWM) & Motor Speed Control ===")
print(f"Power Supply Rail : V_supply = {motor_sim.v_supply}V")
print(f"Carrier Frequency : {motor_sim.pwm_freq_hz} Hz (Period = {motor_sim.period_ms:.2f} ms)")
print(f"Motor Velocity Spec : K_v = {motor_sim.motor_kv} RPM/Volt\n")
test_duties = [0, 25, 50, 75, 100]
print(f"{'Duty Cycle':>11} | {'V_avg (V)':>10} | {'Motor RPM':>10} | {'Power (W)':>10} | {'PWM Waveform Shape':>22}")
print("-" * 75)
for duty in test_duties:
v_avg, rpm, power = motor_sim.calculate_motor_response(duty)
wave = motor_sim.generate_pwm_waveform(duty, samples=16)
# ASCII wave representation: '#' = HIGH (12V), '_' = LOW (0V)
wave_str = "".join("#" if v > 0 else "_" for v in wave)
print(f"{duty:>10}% | {v_avg:>9.2f}V | {rpm:>9.0f} | {power:>9.2f}W | [{wave_str:16}]")
print("\n--- Analysis & Observations ---")
print("1. Linearity: Motor speed (RPM) scales strictly linearly with Duty Cycle percentage.")
print("2. Energy Efficiency: Unlike linear resistive potentiometers that waste unused voltage as heat,")
print(" PWM switches power transistors (MOSFETs) fully ON or fully OFF, achieving >90% electrical efficiency.")
Sample Test Input
Duty cycles: 0%, 25%, 50%, 75%, 100% on 12V motor with Kv=150 RPM/V
Expected Terminal Output
=== Pulse Width Modulation (PWM) & Motor Speed Control ===
Power Supply Rail : V_supply = 12.0V
Carrier Frequency : 1000 Hz (Period = 1.00 ms)
Motor Velocity Spec : K_v = 150 RPM/Volt
Duty Cycle | V_avg (V) | Motor RPM | Power (W) | PWM Waveform Shape
---------------------------------------------------------------------------
0% | 0.00V | 0 | 0.00W | [________________]
25% | 3.00V | 450 | 2.25W | [####____________]
50% | 6.00V | 900 | 9.00W | [########________]
75% | 9.00V | 1350 | 20.25W | [############____]
100% | 12.00V | 1800 | 36.00W | [################]
--- Analysis & Observations ---
1. Linearity: Motor speed (RPM) scales strictly linearly with Duty Cycle percentage.
2. Energy Efficiency: Unlike linear resistive potentiometers that waste unused voltage as heat,
PWM switches power transistors (MOSFETs) fully ON or fully OFF, achieving >90% electrical efficiency.
University Viva Voce Questions & Model Answers:
โข Q: What is Pulse Width Modulation (PWM) and why is it used for motor speed control?
โข Answer: PWM is a technique for delivering variable average voltage to a load by pulsing a digital DC signal at high frequency. Varying the duty cycle (T_on / T) controls the average voltage (and motor speed) with very high electrical efficiency (>90%).
โข Q: Why is PWM more energy efficient than using a variable resistor (rheostat)?
โข Answer: A variable resistor drops excess voltage by dissipating it as waste heat (P = I^2 * R). A switching MOSFET in a PWM circuit is either fully ON (near zero resistance, so low power loss) or fully OFF (zero current, zero power loss), wasting negligible energy.
โข Q: What is an H-Bridge circuit and why is it essential in motor control?
โข Answer: An H-Bridge uses 4 switching transistors arranged in an "H" topology. Closing diagonal pairs of switches reverses the direction of current flow through the motor coil, allowing the motor to spin both forward and backward.
โข Q: What is Back-EMF (Electromotive Force) and why are flyback diodes necessary?
โข Answer: When voltage to an spinning inductive motor coil is abruptly switched off, the collapsing magnetic field induces a massive reverse voltage spike (V = -L * di/dt) that can destroy the switching transistors. A flyback diode provides a safe return path to dissipate this energy.
โข Q: What is PWM resolution in timer hardware?
โข Answer: PWM resolution is determined by the timer counter bit width. An 8-bit timer provides 2^8 = 256 duty cycle steps (0.39% precision); a 16-bit timer provides 65,536 steps, enabling micro-fine speed and servo position control.