Semester 4 Labs | BTech CSE Practical Guide

Semester 4 - Page 6: Labs. 25 numbered practical topics, worked examples, answered viva questions, record/test templates, diagrams and one complete route-reconstruction program. General common-core practice guide, not an official experiment list or assessment format. Follow your assigned tools,department format and instructor safety rules.

Evidence rule: keep actual observations separate from expected results. All data below is synthetic. Linked subject guides supply additional complete checked programs; this page supplies a Python 3 route demo with no external packages. Neither ideal logic simulation nor CLI validation is a tested physical circuit or production web endpoint.

Topic map

  1. Experiment contract and evidence
  2. Reproducible setup and privacy
  3. Java objects and library state
  4. Java exception and boundary tests
  5. Collections, equality and files
  6. Algorithm test graphs and representation
  7. BFS for fewest edges
  8. Dijkstra for minimum nonnegative cost
  9. Sort,search and complexity evidence
  10. Greedy versus DP experiment
  11. DP states and reconstruction
  12. DFA transition table
  13. DFA simulation and oracle comparison
  14. NFA and regular-expression comparison
  15. Stack and grammar exercise
  16. PHP CLI validation exercise
  17. PHP escaping and security separation
  18. PDO persistence and duplicate constraints
  19. HTTP/session/CSRF integration plan
  20. Combinational logic truth-table lab
  21. K-map and equivalent expression test
  22. Two-bit counter simulation
  23. Hardware timing and safe observations
  24. Integrated project boundaries
  25. Submission and viva readiness

1. Experiment contract and evidence

Write aim,inputs,outputs,assumptions,versions and success criteria before the exercise. Expected and observed results are different records; never invent measurements or screenshots.

Worked example: For a counter, expected states are00,01,10,11; record what the actual simulator or bench produced separately.
Viva question: Can a failed experiment be a valid submission record?
Answer: Yes, if it is reported honestly with the failure analysis and the required format is followed.
Aim + contract
  -> prediction + procedure
  -> actual evidence
  -> comparison + limitation
Record sequence. Never replace actual measurements with theoretical predictions.

2. Reproducible setup and privacy

Keep source,run commands,software versions and synthetic input together. Never include passwords,session IDs or private student records in public examples or repositories.

Worked example: Java examples can use Java11; PHP CLI examples use PHP8.1-compatible syntax. A README says which file to compile/run.
Viva question: Why not submit only a screenshot?
Answer: It does not reproduce code,input,environment or the route to the result.

3. Java objects and library state

Model one physical book copy with a distinct inventory ID, and keep checkout/return rules in methods. Identity and availability are not inferred from a title string.

Worked example: Two copies of one title can have two IDs; checkout of one copy should not mark the other unavailable.
Viva question: Why use encapsulation here?
Answer: It keeps invalid transitions from being scattered across caller code.

4. Java exception and boundary tests

Test successful issue,duplicate issue,unknown ID and return-before-issue. Explain the error contract and leave state unchanged when an operation fails.

Worked example: The Java Lab File supplies complete programs; rerun them in your assigned environment rather than claiming a copied output is your observation.
Viva question: Is every exception an application failure?
Answer: Expected invalid-input exceptions can be part of the contract; unexpected failures need separate investigation.

5. Collections, equality and files

Choose collection keys deliberately,define equality/hash consistently and close resources. Immutable inventory IDs are safer keys than mutable titles. File exercises need controlled paths and cleanup.

Worked example: A map keyed by inventory ID makes lookup direct; a copied reference still points to the same mutable object unless an independent copy is made.
Viva question: Why can a mutable hash key break lookup?
Answer: Changing equality/hash fields can move its logical bucket while stored placement remains unchanged.

6. Algorithm test graphs and representation

State directedness,weights,vertex labels and unreachable policy. Adjacency lists support efficient traversal; a disconnected vertex must remain visible in the input.

Worked example: Use H,A,B,L,X with X isolated. Give H->A2,H->B5,A->B1,A->L7,B->L2.
Viva question: Why include an isolated vertex?
Answer: It tests unreachable output and prevents assuming every vertex has a path.

7. BFS for fewest edges

BFS uses a FIFO queue and marks vertices on discovery. On unweighted graphs it finds minimum edge counts; it does not minimize arbitrary weighted cost.

Worked example: In the campus graph, H->B->L uses two edges while H->A->B->L uses three, even though the latter has smaller weight.
Viva question: What happens if a vertex is marked only when popped?
Answer: It can be queued repeatedly by different predecessors, increasing work and complicating parent tracking.

8. Dijkstra for minimum nonnegative cost

Dijkstra needs nonnegative weights and minimum-distance extraction. Track predecessors for a route and skip stale queue entries in lazy-heap implementations.

Worked example: The complete Python demo returns cost5 and route H,A,B,L; X yields no route. A negative edge is rejected before search.
Viva question: Is a shortest path tree necessarily an MST?
Answer: No. Shortest paths minimize source-to-vertex distances; an MST minimizes total connecting edge weight.

Shortest route with predecessor reconstruction

from heapq import heappush, heappop
from math import inf

def route(graph, source, target):
    if source not in graph or target not in graph:
        raise ValueError("unknown endpoint")
    if any(v not in graph or type(w) is not int or w < 0
           for edges in graph.values() for v, w in edges):
        raise ValueError("nonnegative integer edges required")
    distance, parent = dict.fromkeys(graph, inf), {}
    distance[source] = 0
    heap = [(0, source)]
    while heap:
        d, u = heappop(heap)
        if d != distance[u]:
            continue
        for v, w in graph[u]:
            if d + w < distance[v]:
                distance[v] = d + w
                parent[v] = u
                heappush(heap, (d + w, v))
    if distance[target] == inf:
        return None
    path = [target]
    while path[-1] != source:
        path.append(parent[path[-1]])
    return distance[target], path[::-1]

graph = {"H": [("A", 2), ("B", 5)], "A": [("B", 1), ("L", 7)],
         "B": [("L", 2)], "L": [], "X": []}
print(route(graph, "H", "L"))
print(route(graph, "H", "X"))
print(route(graph, "H", "H"))
try:
    route({"H": [("L", -1)], "L": []}, "H", "L")
except ValueError:
    print("negative edge rejected")

Checked output:

(5, ['H', 'A', 'B', 'L'])
None
(0, ['H'])
negative edge rejected

9. Sort,search and complexity evidence

Separate algorithm complexity from benchmark observations. Test empty,duplicate,sorted and reversed input. Binary search assumes sorted random-access data; include preparation cost.

Worked example: Run the DAA guide's merge-sort and first-index demo,then compare its results with a trusted oracle on synthetic lists.
Viva question: Does one fast runtime prove a better asymptotic class?
Answer: No. Inputs,machine effects and constants can dominate a small benchmark.

10. Greedy versus DP experiment

Compare a greedy candidate with a brute-force oracle on small inputs before trusting it. A passing experiment is not a proof; write the exchange proof or recurrence.

Worked example: 0/1 knapsack capacity50 with items10/60,20/100,30/120 defeats ratio-first whole-item selection; optimum220.
Viva question: Why do fractional and 0/1 knapsack differ?
Answer: Fractional items can be split; whole-item choices cannot.

11. DP states and reconstruction

Define each state precisely and fill dependencies in a valid order. A value-only table does not necessarily store the choices needed to reconstruct the solution.

Worked example: Use the DAA guide's knapsack and LCS programs; verify zero capacity,empty strings and the stated positive-weight contract.
Viva question: Why does downward capacity scanning matter?
Answer: It prevents using one0/1 item repeatedly in the same iteration.

12. DFA transition table

Submit alphabet,states,start,final set and every transition. Trace the whole input before accepting; a valid prefix is not the final decision.

Worked example: For ends-in-AB, q0A->qA,q0B->q0,qAA->qA,qAB->qAB,qABA->qA,qABB->q0.
Viva question: What does the state remember?
Answer: Only the suffix information needed to decide whether the final string ends in AB.
Input BAB
q0 --B--> q0 --A--> qA --B--> qAB
Accept: final state qAB
One complete transition trace, with all input consumed.

13. DFA simulation and oracle comparison

Implement the theoretical transition table faithfully and compare bounded inputs with an independent language predicate. Reject symbols outside the alphabet deliberately.

Worked example: The Python DFA demo on the TOC page is checked against endswith('AB') for all A/B strings up to length10.
Viva question: Does this finite test prove equivalence for every length?
Answer: No. The state invariant supplies the proof; tests find implementation errors.

14. NFA and regular-expression comparison

An NFA tracks possible states; acceptance needs one successful complete branch. Theoretical regex and NFA can describe the same regular language, but programming regex extensions may differ.

Worked example: The TOC suffix01 NFA demo tracks sets and is compared with a simple suffix predicate.
Viva question: Should every NFA branch accept?
Answer: No. Acceptance is existential over complete runs.

15. Stack and grammar exercise

Use a stack to recognize a^n b^n with all a symbols before b symbols. Compare with the grammar S->aSb or epsilon, and explain push/pop invariants.

Worked example: aabb accepts,abab and aab reject; epsilon accepts for n>=0. The TOC guide provides a complete simulator.
Viva question: Why does order matter in addition to counts?
Answer: Equal totals alone would incorrectly accept interleaved strings such as abab.

16. PHP CLI validation exercise

Validate scalar shape,format and bounds before conversion. A lab form can send arrays where strings are expected, so server-side checks must reject them.

Worked example: The PHP guide's simulated form demo accepts event12 and a syntactically valid email; missing fields,array ID and invalid email fail.
Viva question: Does CLI simulation test an HTTP endpoint?
Answer: No. It tests the chosen validation function,not headers,session cookies or web deployment.

17. PHP escaping and security separation

Escape display text for HTML context,bind SQL values separately and authorize identities independently. CSRF adds another check for browser state changes.

Worked example: The PHP guide escapes an HTML-like name; that output does not prove SQL injection or authorization handling is safe.
Viva question: Why list separate defenses?
Answer: Each prevents a different kind of mistake; no single sanitizer supplies them all.

18. PDO persistence and duplicate constraints

For a database exercise,declare schema,driver,connection policy and uniqueness rules. Capacity check and insert need a transaction with a concurrency strategy.

Worked example: UNIQUE(event_id,student_id) rejects duplicate registration even when two requests race. Keep credentials outside submitted/public source.
Viva question: Is this page's PHP CLI code a complete PDO implementation?
Answer: No. Database work is an extension requiring its own driver and integration tests.

19. HTTP/session/CSRF integration plan

A real form test checks authentication,permission,token,validation,transaction and response. Use synthetic accounts and do not publish live credentials or session identifiers.

Worked example: Test unauthenticated POST,wrong token,wrong event,duplicate and two requests for the last seat; record expected status and actual response.
Viva question: Does post-redirect-get prevent all duplicate registrations?
Answer: No. It reduces refresh repeats; a database rule still enforces uniqueness.

20. Combinational logic truth-table lab

Derive every output row,then simulate the Boolean circuit. A full-adder has eight input rows and must satisfy A+B+Cin=Sum+2Carry.

Worked example: The Digital Electronics page's full-adder block checks all eight combinations with an arithmetic assertion.
Viva question: Can checking only00 and11 validate XOR?
Answer: No. Its mismatch cases01 and10 are essential.

21. K-map and equivalent expression test

Lay out Gray-code rows/columns and verify the simplified function exhaustively. Include don't-cares only under a valid input assumption.

Worked example: Minterms1,3,5,7 simplify to C in a three-variable map; the electronics guide checks every row.
Viva question: Are diagonal K-map cells adjacent?
Answer: No. Adjacent cells differ in exactly one variable under the Gray-code layout.

22. Two-bit counter simulation

Compute next state from the old state,then update both flip-flops together. Reset is a defined operation; document whether it is synchronous or asynchronous.

Worked example: D0=NOT Q0,D1=Q1 XOR Q0 cycles00,01,10,11. AlarmQ1 AND Q0 is one only at11.
Viva question: Why not update Q0 before calculating D1?
Answer: D1 would use a new rather than current Q0,changing the intended state machine.
Old state -> next-state logic -> D inputs
                  clock edge
                -> new state
Compute from the same old state and update registers together.

23. Hardware timing and safe observations

An ideal simulation does not establish setup/hold,pin compatibility or metastability behavior. Verify exact part datasheets and lab safety rules; power off before rewiring.

Worked example: Step clock and record stable states,but use a scope/logic analyzer to observe glitches an LED may miss.
Viva question: Can two same-named simulator parts justify a real IC pinout?
Answer: No. The physical part number and package determine the datasheet.

24. Integrated project boundaries

A campus-event demo can combine PHP registration,Java domain modeling,route algorithms and a logic-counter exercise without pretending they are one deployed secure system..

Worked example: Keep each module's inputs,outputs and tests separate; connect only interfaces that you actually implement and test.
Viva question: Why state limitations in the report?
Answer: It prevents classroom assumptions from being mistaken for production guarantees.

25. Submission and viva readiness

Submit readable source,diagrams,test matrix,versions,run steps,actual results and limitations in the required department format. Be ready to explain one failed test and its fix.

Worked example: Explain why Dijkstra rejects negatives,why the DFA needs qAB,and why a duplicate database constraint matters.
Viva question: What should a viva answer include beyond the output?
Answer: The invariant or rule,an edge case and the reason the method satisfies its contract.

Practical test matrix

ExerciseSuccessBoundary / failure
Java book checkoutAvailable known copy issuedDuplicate,unknown ID,invalid return
BFS / DijkstraCorrect route and objectiveIsolated,tie,negative edge rejection
DFA / NFAWhole input ends in required suffixEmpty,wrong suffix,invalid symbol
PHP validationAllowed scalar ID and emailMissing,array input,bad format
Database extensionUnique committed registrationDuplicate,last-seat race,rollback
CounterFour-state cycle and alarm11Reset,timing,invalid wiring conditions

Lab record template

FieldWhat to record
Aim / contractQuestion,inputs,outputs,assumptions
EnvironmentVersion,driver/device,run command
MethodAlgorithm,circuit,procedure
ExpectedCalculated result before execution
ActualObserved result and raw evidence
TestsSuccessful,boundary and failure cases
ConclusionAgreement,limitations,next test

Linked practicals and references

The subject guides provide complete examples with their own run instructions. Java Lab File programs use Main.java; Java theory demos use Demo.java. Run one whole block at a time. Check your assigned version. New HTTP,database or hardware exercises need independent tests.

Comments

Popular posts from this blog

Big Data Analytics Exam Prep

Process States in OS: Diagram, PCB and Context Switching

Python Mutable Default Arguments and Shallow Copies: Why Lists Keep Changing