COA Lab — Computer Organization & Architecture
8086 MASM programs for DOSBox + MASM/LINK/DEBUG. Test-assemble before final submission.
Exp 1 Installation & configuration: DOS, MASM, Debug and x86 mode
.MODEL SMALL
.STACK 100H
.DATA
MSG DB 'Hello, COA lab!$'
.CODE
MAIN PROC
MOV AX,@DATA
MOV DS,AX
LEA DX,MSG
MOV AH,09H
INT 21H
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
Exp 2 ALU operations (ADD, SUB, MUL, DIV, AND, OR, XOR, NOT) in 8086 assembly
.186
.MODEL SMALL
.STACK 100H
.DATA
MSG_ADD DB 0DH,0AH,'ADD (AX+BX) = $'
MSG_SUB DB 0DH,0AH,'SUB (AX-BX) = $'
MSG_MUL DB 0DH,0AH,'MUL (AX*BL) = $'
MSG_DIV DB 0DH,0AH,'DIV (AX/BL) = $'
MSG_AND DB 0DH,0AH,'AND = $'
MSG_OR DB 0DH,0AH,'OR = $'
MSG_XOR DB 0DH,0AH,'XOR = $'
MSG_NOT DB 0DH,0AH,'NOT AX = $'
.CODE
MAIN PROC
MOV AX,@DATA ; initialise data segment
MOV DS,AX
; ADD : 1234H + 00ABH = 12DFH
LEA DX,MSG_ADD
MOV AH,09H
INT 21H
MOV AX,1234H
MOV BX,00ABH
ADD AX,BX ; AX = 12DFH, flags updated
CALL PRINT_HEX
; SUB : 12DFH - 00ABH = 1234H
LEA DX,MSG_SUB
MOV AH,09H
INT 21H
MOV AX,12DFH
MOV BX,00ABH
SUB AX,BX ; AX = 1234H
CALL PRINT_HEX
; MUL : 0012H * 03H = 0036H (result lands in AX)
LEA DX,MSG_MUL
MOV AH,09H
INT 21H
MOV AX,0012H
MOV BL,03H
MUL BL ; AX = 0036H
CALL PRINT_HEX
; DIV : 0096H / 03H -> quotient AL=32H, remainder AH=00H
LEA DX,MSG_DIV
MOV AH,09H
INT 21H
MOV AX,0096H
MOV BL,03H
DIV BL ; AL=32H, AH=00H (AX reads 0032H)
CALL PRINT_HEX
; AND : 12DFH AND 0F0FH = 020FH
LEA DX,MSG_AND
MOV AH,09H
INT 21H
MOV AX,12DFH
MOV BX,0F0FH
AND AX,BX ; AX = 020FH, CF=OF=0
CALL PRINT_HEX
; OR : 12DFH OR 0F0FH = 1FDFH
LEA DX,MSG_OR
MOV AH,09H
INT 21H
MOV AX,12DFH
MOV BX,0F0FH
OR AX,BX ; AX = 1FDFH
CALL PRINT_HEX
; XOR : 12DFH XOR 0F0FH = 1DD0H
LEA DX,MSG_XOR
MOV AH,09H
INT 21H
MOV AX,12DFH
MOV BX,0F0FH
XOR AX,BX ; AX = 1DD0H
CALL PRINT_HEX
; NOT : NOT 12DFH = ED20H (flags unchanged)
LEA DX,MSG_NOT
MOV AH,09H
INT 21H
MOV AX,12DFH
NOT AX ; AX = ED20H
CALL PRINT_HEX
MOV AH,4CH ; clean exit to DOS
INT 21H
MAIN ENDP
; ---- subroutine: print AX as 4 hexadecimal digits ----
PRINT_HEX PROC
PUSH AX
PUSH BX
PUSH CX
PUSH DX
MOV BX,AX
MOV CX,4 ; four nibbles to print
NEXT_DIGIT:
ROL BX,4 ; bring next nibble to low position
MOV AX,BX
AND AL,0FH ; isolate the nibble
CMP AL,0AH
JB IS_DIGIT
ADD AL,07H ; A-F need extra offset past '9'
IS_DIGIT:
ADD AL,30H ; nibble -> ASCII
MOV DL,AL
MOV AH,02H
INT 21H ; print one character
LOOP NEXT_DIGIT
POP DX
POP CX
POP BX
POP AX
RET
PRINT_HEX ENDP
END MAIN
Exp 3 Number conversion: HEX↔BCD, ASCII↔BCD
.186
.MODEL SMALL
.STACK 100H
.DATA
MSG1 DB 0DH,0AH,'Hex 0B (11 decimal) -> unpacked BCD: $'
MSG2 DB 0DH,0AH,'ASCII "27" -> packed BCD: $'
MSG3 DB 0DH,0AH,'BCD 27H -> ASCII: $'
.CODE
MAIN PROC
MOV AX,@DATA ; initialise data segment
MOV DS,AX
; ---- (a) Hex digit 0BH (= 11 decimal) to unpacked BCD ----
LEA DX,MSG1
MOV AH,09H
INT 21H
MOV AL,0BH ; binary value 11
AAM ; 11 / 10 -> AH=01 (tens), AL=01 (ones)
MOV BX,AX ; save both unpacked digits
MOV DL,BH ; tens digit
ADD DL,30H ; unpacked BCD -> ASCII
MOV AH,02H
INT 21H
MOV DL,BL ; ones digit
ADD DL,30H
MOV AH,02H
INT 21H
; ---- (b) ASCII string "27" to packed BCD 27H ----
LEA DX,MSG2
MOV AH,09H
INT 21H
MOV AL,'2'
SUB AL,30H ; ASCII -> digit: AL = 02H
MOV AH,'7'
SUB AH,30H ; AH = 07H
SHL AL,4 ; move tens digit into high nibble
OR AL,AH ; AL = 27H (packed BCD)
MOV CL,AL ; keep a copy
SHR AL,4 ; high nibble down for display
ADD AL,30H
MOV DL,AL
MOV AH,02H
INT 21H
MOV AL,CL
AND AL,0FH ; isolate low nibble
ADD AL,30H
MOV DL,AL
MOV AH,02H
INT 21H
; ---- (c) Packed BCD 27H back to ASCII "27" ----
LEA DX,MSG3
MOV AH,09H
INT 21H
MOV AL,27H ; packed BCD input
MOV BL,AL ; keep a copy
AND AL,0F0H
SHR AL,4 ; high nibble = tens digit
ADD AL,30H ; BCD digit -> ASCII
MOV DL,AL
MOV AH,02H
INT 21H
MOV AL,BL
AND AL,0FH ; low nibble = ones digit
ADD AL,30H
MOV DL,AL
MOV AH,02H
INT 21H
MOV AH,4CH ; return to DOS
INT 21H
MAIN ENDP
END MAIN
Exp 4 8-bit BCD addition with keyboard input (INT 21H)
.186
.MODEL SMALL
.STACK 100H
.DATA
MSG1 DB 'Enter first 2-digit number: $'
MSG2 DB 0DH,0AH,'Enter second 2-digit number: $'
MSG3 DB 0DH,0AH,'Sum = $'
.CODE
MAIN PROC
MOV AX,@DATA ; initialise data segment
MOV DS,AX
; ---- read first number, pack into BH ----
LEA DX,MSG1
MOV AH,09H
INT 21H
MOV AH,01H
INT 21H ; AL = tens digit (ASCII, echoed)
SUB AL,30H ; ASCII -> digit
MOV BH,AL
SHL BH,4 ; tens digit into high nibble
MOV AH,01H
INT 21H ; AL = ones digit (ASCII, echoed)
SUB AL,30H
OR BH,AL ; BH = packed BCD of first number
; ---- read second number, pack into BL ----
LEA DX,MSG2
MOV AH,09H
INT 21H
MOV AH,01H
INT 21H
SUB AL,30H
MOV BL,AL
SHL BL,4
MOV AH,01H
INT 21H
SUB AL,30H
OR BL,AL ; BL = packed BCD of second number
; ---- BCD addition ----
MOV AL,BH
ADD AL,BL ; binary sum of packed bytes
DAA ; adjust to valid packed BCD, CF=hundreds
MOV BH,AL ; BH = packed BCD sum
MOV CH,0 ; CH = hundreds digit (default 0)
JNC NO_CARRY
MOV CH,1 ; DAA set CF -> sum exceeded 99
NO_CARRY:
; ---- display the result ----
LEA DX,MSG3
MOV AH,09H
INT 21H
CMP CH,0
JE SKIP_HUND ; no hundreds digit to print
MOV DL,'1'
MOV AH,02H
INT 21H
SKIP_HUND:
MOV AL,BH
MOV CL,AL ; save packed sum
AND AL,0F0H
SHR AL,4 ; tens digit
ADD AL,30H ; digit -> ASCII
MOV DL,AL
MOV AH,02H
INT 21H
MOV AL,CL
AND AL,0FH ; ones digit
ADD AL,30H
MOV DL,AL
MOV AH,02H
INT 21H
MOV AH,4CH ; exit to DOS
INT 21H
MAIN ENDP
END MAIN
Exp 5 String operations (MOVS, CMPS, SCAS with REP)
; STR_OP.ASM - String copy, compare and scan in 8086 (MASM)
.MODEL SMALL
.STACK 100H
.DATA
SRC DB 'HELLO WORLD$', 0 ; source string
DST DB 12 DUP(?) ; destination buffer
MSG1 DB 0DH,0AH,'Copy (MOVSB) result : $'
MSG2 DB 0DH,0AH,'Compare (CMPSB) result: $'
MSG3 DB 0DH,0AH,'Scan (SCASB) for ''W'' : $'
EQUALM DB 'Equal$'
NEQUALM DB 'Not Equal$'
FOUNDM DB 'Found at offset $'
NFOUNDM DB 'Not Found$'
NEWLINE DB 0DH,0AH,'$'
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX ; DS = data segment
MOV ES, AX ; ES = DS (DI points into data segment too)
; ---------- 1. String COPY using MOVSB + REP ----------
CLD ; forward direction
LEA SI, SRC ; SI -> source
LEA DI, DST ; DI -> destination
MOV CX, 11 ; 11 characters ("HELLO WORLD")
REP MOVSB ; copy byte-by-byte
LEA DX, MSG1
MOV AH, 09H
INT 21H ; print label
LEA DX, DST
MOV AH, 09H
INT 21H ; print copied string
; ---------- 2. String COMPARE using CMPSB + REPE ----------
CLD
LEA SI, SRC ; SI -> first string
LEA DI, DST ; DI -> copied string
MOV CX, 11
REPE CMPSB ; compare while bytes match
JZ STR_EQUAL ; CX hit zero -> all matched
LEA DX, MSG2
MOV AH, 09H
INT 21H
LEA DX, NEQUALM
MOV AH, 09H
INT 21H
JMP SCAN_PART
STR_EQUAL:
LEA DX, MSG2
MOV AH, 09H
INT 21H
LEA DX, EQUALM
MOV AH, 09H
INT 21H
; ---------- 3. String SCAN using SCASB + REPNE ----------
SCAN_PART:
CLD
LEA DI, SRC ; DI -> string to scan
MOV CX, 11
MOV AL, 'W' ; character to find
REPNE SCASB ; scan while not equal
JZ CHAR_FOUND ; ZF set -> match found
LEA DX, MSG3
MOV AH, 09H
INT 21H
LEA DX, NFOUNDM
MOV AH, 09H
INT 21H
JMP DONE
CHAR_FOUND:
LEA DX, MSG3
MOV AH, 09H
INT 21H
LEA DX, FOUNDM
MOV AH, 09H
INT 21H
; DI now points one PAST the match; offset = 11 - CX - 1
MOV AL, 11
SUB AL, CL ; CL = remaining count
DEC AL ; offset = 11 - CX - 1
ADD AL, '0' ; single digit -> ASCII
MOV DL, AL
MOV AH, 02H
INT 21H
DONE:
LEA DX, NEWLINE
MOV AH, 09H
INT 21H
MOV AH, 4CH ; terminate program
INT 21H
MAIN ENDP
END MAIN
Exp 6 Block transfer and block exchange using index registers
.186
; BLOCK.ASM - Block transfer + block exchange (MASM)
.MODEL SMALL
.STACK 100H
.DATA
BLOCK1 DB 10H, 20H, 30H, 40H, 50H, 60H, 70H, 80H, 90H, 0A0H
BLOCK2 DB 01H, 02H, 03H, 04H, 05H, 06H, 07H, 08H, 09H, 0AH
DEST DB 10 DUP(?) ; destination area
MSG_B1 DB 0DH,0AH,'BLOCK1 (src) : $'
MSG_B2 DB 0DH,0AH,'BLOCK2 : $'
MSG_DEST DB 0DH,0AH,'DEST (after transfer): $'
MSG_B1X DB 0DH,0AH,'BLOCK1 (after exchange): $'
MSG_B2X DB 0DH,0AH,'BLOCK2 (after exchange): $'
NEWLINE DB 0DH,0AH,'$'
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
; ----- show BLOCK1 and BLOCK2 before anything -----
LEA DX, MSG_B1
MOV AH, 09H
INT 21H
LEA SI, BLOCK1
MOV CX, 10
CALL PRINT_BLOCK
LEA DX, MSG_B2
MOV AH, 09H
INT 21H
LEA SI, BLOCK2
MOV CX, 10
CALL PRINT_BLOCK
; ----- 1. BLOCK TRANSFER: BLOCK1 -> DEST -----
LEA SI, BLOCK1 ; SI -> source block
LEA DI, DEST ; DI -> destination area
MOV CX, 10 ; 10 bytes to move
NEXT_BYTE:
MOV AL, [SI] ; fetch source byte
MOV [DI], AL ; store into destination
INC SI ; advance both pointers
INC DI
LOOP NEXT_BYTE ; CX = CX-1; repeat if not zero
LEA DX, MSG_DEST
MOV AH, 09H
INT 21H
LEA SI, DEST
MOV CX, 10
CALL PRINT_BLOCK
; ----- 2. BLOCK EXCHANGE: BLOCK1 <-> BLOCK2 -----
LEA SI, BLOCK1
LEA DI, BLOCK2
MOV CX, 10
SWAP_BYTE:
MOV AL, [SI] ; AL = BLOCK1[i]
XCHG AL, [DI] ; AL <-> BLOCK2[i]; AL now holds old BLOCK2[i]
MOV [SI], AL ; BLOCK1[i] = old BLOCK2[i]
INC SI
INC DI
LOOP SWAP_BYTE
LEA DX, MSG_B1X
MOV AH, 09H
INT 21H
LEA SI, BLOCK1
MOV CX, 10
CALL PRINT_BLOCK
LEA DX, MSG_B2X
MOV AH, 09H
INT 21H
LEA SI, BLOCK2
MOV CX, 10
CALL PRINT_BLOCK
LEA DX, NEWLINE
MOV AH, 09H
INT 21H
MOV AH, 4CH ; exit to DOS
INT 21H
MAIN ENDP
; ----- prints CX hex bytes starting at DS:SI -----
PRINT_BLOCK PROC
PUSH AX
PUSH BX
PUSH CX
PUSH DX
PRINT_NEXT:
MOV AL, [SI]
MOV BL, AL
SHR AL, 4 ; high nibble
CALL PRINT_NIBBLE
MOV AL, BL
AND AL, 0FH ; low nibble
CALL PRINT_NIBBLE
MOV DL, ' ' ; space between bytes
MOV AH, 02H
INT 21H
INC SI
LOOP PRINT_NEXT
POP DX
POP CX
POP BX
POP AX
RET
PRINT_BLOCK ENDP
; ----- prints low nibble of AL as hex digit -----
PRINT_NIBBLE PROC
CMP AL, 9
JBE DIGIT
ADD AL, 7 ; A-F need extra offset
DIGIT:
ADD AL, '0'
MOV DL, AL
MOV AH, 02H
INT 21H
RET
PRINT_NIBBLE ENDP
END MAIN
Exp 7 Drawing basic shapes (rectangle, triangle) via BIOS services
; SHAPES.ASM - Rectangle + triangle in mode 13H (MASM)
.MODEL SMALL
.STACK 100H
.DATA
MSG DB 'Press any key to exit...$'
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
; ----- set graphics mode 13H (320x200, 256 colours) -----
MOV AH, 00H
MOV AL, 13H
INT 10H
; ----- set background colour to dark blue (palette 0) -----
MOV AH, 0BH
MOV BH, 00H
MOV BL, 01H ; blue background
INT 10H
; ----- draw RECTANGLE: corners (40,40)-(160,40)-(160,120)-(40,120) -----
MOV AL, 0EH ; yellow
MOV CX, 40 ; x1 = 40
MOV DX, 40 ; y = 40
MOV BX, 160 ; x2 = 160
CALL HLINE ; top edge
MOV CX, 40
MOV DX, 120
MOV BX, 160
CALL HLINE ; bottom edge
MOV AL, 0EH
MOV CX, 40 ; x = 40
MOV DX, 40 ; y1 = 40
MOV BX, 120 ; y2 = 120
CALL VLINE ; left edge
MOV CX, 160 ; x = 160
MOV DX, 40
MOV BX, 120
CALL VLINE ; right edge
; ----- draw TRIANGLE: (200,120) -> (280,120) -> (240,40) -----
MOV AL, 0AH ; light green
MOV CX, 200 ; x1
MOV DX, 120 ; y1
MOV SI, 280 ; x2
MOV DI, 120 ; y2
CALL LINE ; base
MOV CX, 280
MOV DX, 120
MOV SI, 240
MOV DI, 40
CALL LINE ; right side
MOV CX, 240
MOV DX, 40
MOV SI, 200
MOV DI, 120
CALL LINE ; left side
; ----- wait for keypress (BIOS keyboard service) -----
MOV AH, 00H
INT 16H
; ----- restore text mode 03H -----
MOV AH, 00H
MOV AL, 03H
INT 10H
; ----- print exit message in text mode -----
LEA DX, MSG
MOV AH, 09H
INT 21H
MOV AH, 4CH
INT 21H
MAIN ENDP
; ----- horizontal line: AL=colour, CX=x1, DX=y, BX=x2 -----
HLINE PROC
PUSH CX
PUSH DX
HL_LOOP:
PUSH AX
PUSH BX
PUSH CX
PUSH DX
MOV AH, 0CH ; write pixel
MOV BH, 0 ; page 0
INT 10H
POP DX
POP CX
POP BX
POP AX
INC CX ; next x
CMP CX, BX
JLE HL_LOOP
POP DX
POP CX
RET
HLINE ENDP
; ----- vertical line: AL=colour, CX=x, DX=y1, BX=y2 -----
VLINE PROC
PUSH CX
PUSH DX
VL_LOOP:
PUSH AX
PUSH BX
PUSH CX
PUSH DX
MOV AH, 0CH
MOV BH, 0
INT 10H
POP DX
POP CX
POP BX
POP AX
INC DX ; next y
CMP DX, BX
JLE VL_LOOP
POP DX
POP CX
RET
VLINE ENDP
; ----- slanted line: AL=colour, (CX,DX)->(SI,DI), steps in x -----
; (endpoints chosen so the slope is simple)
LINE PROC
PUSH AX
PUSH CX
PUSH DX
PUSH SI
PUSH DI
LN_LOOP:
PUSH AX
PUSH BX
PUSH CX
PUSH DX
PUSH SI
PUSH DI
MOV AH, 0CH
MOV BH, 0
INT 10H ; plot (CX,DX)
POP DI
POP SI
POP DX
POP CX
POP BX
POP AX
CMP CX, SI
JE LN_DONE
; step x toward x2, adjust y by slope sign
CMP CX, SI
JG STEP_LEFT
INC CX
CMP DX, DI
JE LN_NEXT
JL Y_DOWN
DEC DX
JMP LN_NEXT
Y_DOWN:
INC DX
JMP LN_NEXT
STEP_LEFT:
DEC CX
CMP DX, DI
JE LN_NEXT
JL Y_DOWN2
DEC DX
JMP LN_NEXT
Y_DOWN2:
INC DX
LN_NEXT:
JMP LN_LOOP
LN_DONE:
POP DI
POP SI
POP DX
POP CX
POP AX
RET
LINE ENDP
END MAIN
Exp 8 Password detection application with 3-attempt lockout
; PASSWD.ASM - Password detection with 3-attempt lockout (MASM)
.MODEL SMALL
.STACK 100H
.DATA
STORED_PW DB 'secret12' ; the correct password (8 chars)
PW_LEN EQU 8
INPUT_BUF DB 20 DUP(?) ; typed password buffer
PROMPT DB 0DH,0AH,'Enter password: $'
GRANTED DB 0DH,0AH,'Access Granted. Welcome!$'
DENIED DB 0DH,0AH,'Access Denied. Wrong password.$'
LOCKED DB 0DH,0AH,'Too many wrong attempts. Account locked!$'
TRIES_LEFT DB 0DH,0AH,'Attempts remaining: $'
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
MOV ES, AX
MOV BL, 3 ; BL = attempts remaining
TRY_AGAIN:
; ----- prompt -----
LEA DX, PROMPT
MOV AH, 09H
INT 21H
; ----- read password, echo '*' -----
LEA DI, INPUT_BUF ; DI -> input buffer
MOV CX, 0 ; CX = chars typed
READ_CHAR:
MOV AH, 01H ; read keystroke with echo...
INT 21H ; ...but we overwrite the echo below
CMP AL, 0DH ; Enter pressed?
JE INPUT_DONE
CMP AL, 08H ; Backspace?
JE DO_BACKSPACE
CMP CX, 20 ; buffer full?
JAE READ_CHAR ; ignore extra keys
MOV [DI], AL ; store real character
INC DI
INC CX
MOV DL, 08H ; backspace over the echoed char
MOV AH, 02H
INT 21H
MOV DL, '*' ; print mask instead
MOV AH, 02H
INT 21H
JMP READ_CHAR
DO_BACKSPACE:
CMP CX, 0 ; nothing to erase?
JE READ_CHAR
DEC DI
DEC CX
MOV DL, 08H ; erase the '*' visually: BS, space, BS
MOV AH, 02H
INT 21H
MOV DL, ' '
MOV AH, 02H
INT 21H
MOV DL, 08H
MOV AH, 02H
INT 21H
JMP READ_CHAR
INPUT_DONE:
; ----- compare typed input with stored password -----
CMP CX, PW_LEN ; length must match first
JNE WRONG_PW
CLD
LEA SI, STORED_PW
LEA DI, INPUT_BUF
MOV CX, PW_LEN
REPE CMPSB ; compare while equal
JZ ACCESS_OK ; all bytes matched
WRONG_PW:
DEC BL ; one attempt used up
JZ LOCKOUT ; no attempts left -> lock out
LEA DX, DENIED
MOV AH, 09H
INT 21H
LEA DX, TRIES_LEFT ; show remaining attempts
MOV AH, 09H
INT 21H
MOV DL, BL
ADD DL, '0'
MOV AH, 02H
INT 21H
JMP TRY_AGAIN
ACCESS_OK:
LEA DX, GRANTED
MOV AH, 09H
INT 21H
JMP FINISH
LOCKOUT:
LEA DX, LOCKED
MOV AH, 09H
INT 21H
FINISH:
MOV AH, 4CH ; terminate program
INT 21H
MAIN ENDP
END MAIN
Exp 9 File operations using DOS interrupts
; EXP09.ASM - File operations using DOS interrupts
; Creates DATA.TXT, writes a message into it, closes it,
; reopens it, reads the contents back and displays them.
DATA SEGMENT
FILENAME DB 'DATA.TXT', 0 ; ASCIIZ filename
MSG DB 'Hello! This file was written by a DOS program.', 0DH, 0AH
MSGLEN EQU $ - MSG
BUFFER DB 80 DUP('$') ; read buffer
HANDLE DW 0 ; storage for file handle
MSG1 DB 0DH, 0AH, 'Contents of the file:', 0DH, 0AH, '$'
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
START:
MOV AX, DATA
MOV DS, AX
; ---- Create the file ----
MOV AH, 3CH ; create file
MOV CX, 0 ; normal file attribute
LEA DX, FILENAME
INT 21H
JC EXIT_ERR ; CF=1 => error
MOV HANDLE, AX ; save the handle
; ---- Write the message into the file ----
MOV AH, 40H ; write to file
MOV BX, HANDLE
MOV CX, MSGLEN
LEA DX, MSG
INT 21H
JC EXIT_ERR
; ---- Close the file ----
MOV AH, 3EH ; close file
MOV BX, HANDLE
INT 21H
; ---- Reopen the file for reading ----
MOV AH, 3DH ; open file
MOV AL, 0 ; read-only mode
LEA DX, FILENAME
INT 21H
JC EXIT_ERR
MOV HANDLE, AX
; ---- Read the contents back ----
MOV AH, 3FH ; read from file
MOV BX, HANDLE
MOV CX, 80
LEA DX, BUFFER
INT 21H
JC EXIT_ERR
; ---- Close the file again ----
MOV AH, 3EH
MOV BX, HANDLE
INT 21H
; ---- Display what was read ----
MOV AH, 09H
LEA DX, MSG1
INT 21H
MOV AH, 09H
LEA DX, BUFFER
INT 21H
JMP FINISH
EXIT_ERR:
; (carry set here => operation failed)
FINISH:
MOV AH, 4CH ; return to DOS
INT 21H
CODE ENDS
END START
Exp 10 I/O interfacing: PC speaker sound via timer/PPI ports
; EXP10.ASM - Play a beep on the IBM PC speaker.
; Target tone ~880 Hz, duration ~1 second.
; Divisor = 1193180 / 880 = 1355 = 054BH
DATA SEGMENT
DIV_LO DB 4BH ; divisor low byte
DIV_HI DB 05H ; divisor high byte
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
START:
MOV AX, DATA
MOV DS, AX
; ---- Program 8253 channel 2 for square wave ----
MOV AL, 0B6H ; ch2, mode 3, LSB then MSB
OUT 43H, AL ; control register
MOV AL, DIV_LO
OUT 42H, AL ; divisor LSB
MOV AL, DIV_HI
OUT 42H, AL ; divisor MSB
; ---- Turn the speaker ON ----
IN AL, 61H ; read PPI port B
OR AL, 03H ; set bits 0 and 1 (enable speaker)
OUT 61H, AL
; ---- Software delay (~1 second at ~4.77 MHz) ----
MOV CX, 0FFFFH
DELAY1:
PUSH CX
MOV CX, 0FFFH
DELAY2:
LOOP DELAY2
POP CX
LOOP DELAY1
; ---- Turn the speaker OFF ----
IN AL, 61H
AND AL, 0FCH ; clear bits 0 and 1
OUT 61H, AL
MOV AH, 4CH ; return to DOS
INT 21H
CODE ENDS
END START
Exp 11 Cursor control: hide cursor / full-block cursor via INT 10H
; EXP11.ASM - Demonstrate cursor shapes with BIOS INT 10H.
; Three states: normal -> hidden -> full block, keypress pauses between.
DATA SEGMENT
M1 DB 0DH, 0AH, 'NORMAL cursor - press any key to hide it', 0DH, 0AH, '$'
M2 DB 0DH, 0AH, 'Cursor is HIDDEN - press any key for block cursor', 0DH, 0AH, '$'
M3 DB 0DH, 0AH, 'FULL BLOCK cursor - press any key to exit', 0DH, 0AH, '$'
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
START:
MOV AX, DATA
MOV DS, AX
; ---- State 1: normal cursor (CH=06, CL=07) ----
MOV AH, 09H
LEA DX, M1
INT 21H
MOV AH, 01H ; INT 10H set cursor type
MOV CH, 06H ; start scan line
MOV CL, 07H ; end scan line
INT 10H
MOV AH, 01H ; wait for keypress
INT 21H
; ---- State 2: hidden cursor (CH=20H => cursor off) ----
MOV AH, 09H
LEA DX, M2
INT 21H
MOV AH, 01H
MOV CH, 20H ; bit 5 set => hide
MOV CL, 20H
INT 10H
MOV AH, 01H ; wait for keypress
INT 21H
; ---- State 3: full block cursor (CH=00, CL=07) ----
MOV AH, 09H
LEA DX, M3
INT 21H
MOV AH, 01H
MOV CH, 00H ; top of the cell
MOV CL, 07H ; bottom of the cell
INT 10H
MOV AH, 01H ; wait for keypress
INT 21H
; ---- Restore normal cursor before exiting ----
MOV AH, 01H
MOV CH, 06H
MOV CL, 07H
INT 10H
MOV AH, 4CH
INT 21H
CODE ENDS
END START
Exp 12 Booth's multiplication algorithm + worked example
.186
; EXP12.ASM - Booth's multiplication for 8-bit signed numbers.
; Computes X * Y (signed), result shown as 16-bit 2's complement
; and as signed decimal.
DATA SEGMENT
M DB 0FBH ; multiplicand M = -5
Q DB 03H ; multiplier Q = 3
AREG DB 0 ; accumulator A (8 bits)
QREG DB 0
QMINUS1 DB 0
COUNT DB 8
NEG_M DB 0 ; -M (precomputed 2's complement of M)
RESLO DB 0
RESHI DB 0
MSG DB 0DH, 0AH, 'Booth product (hex): $'
MSG2 DB 0DH, 0AH, 'Signed decimal: -$'
DIGS DB '0123456789ABCDEF'
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
START:
MOV AX, DATA
MOV DS, AX
; ---- Initialise: Q=mult, A=0, Q-1=0, count=8 ----
MOV AL, Q
MOV QREG, AL
MOV AREG, 0
MOV QMINUS1, 0
MOV COUNT, 8
; ---- Precompute -M = ~M + 1 ----
MOV AL, M
NOT AL
ADD AL, 1
MOV NEG_M, AL
BOOTH_LOOP:
; Examine bit pair (Q0, Q-1)
MOV AL, QREG
AND AL, 01H ; AL = Q0
MOV BL, QMINUS1 ; BL = Q-1
CMP AL, 0
JNE CHECK_SUB ; Q0 = 1
; Q0 = 0
CMP BL, 0
JE DO_SHIFT ; (0,0) -> no op
; (0,1) -> A = A + M
MOV AL, AREG
ADD AL, M
MOV AREG, AL
JMP DO_SHIFT
CHECK_SUB:
CMP BL, 0
JNE DO_SHIFT ; (1,1) -> no op
; (1,0) -> A = A - M (add -M)
MOV AL, AREG
ADD AL, NEG_M
MOV AREG, AL
DO_SHIFT:
; Arithmetic right shift of (A, Q, Q-1) together
MOV AL, QREG
AND AL, 01H
MOV QMINUS1, AL ; new Q-1 = old Q0
MOV AL, QREG
SHR AL, 1 ; logical shift Q (FIX: SAR kept Q's sign bit, corrupting the result)
; bring A's LSB into Q's MSB
MOV BL, AREG
AND BL, 01H
SHL BL, 7
OR AL, BL
MOV QREG, AL
MOV AL, AREG
SAR AL, 1 ; arithmetic shift A (sign preserved)
MOV AREG, AL
DEC COUNT
JNZ BOOTH_LOOP
; ---- Result: RESHI = A, RESLO = Q ----
MOV AL, QREG
MOV RESLO, AL
MOV AL, AREG
MOV RESHI, AL
; ---- Display hex product ----
MOV AH, 09H
LEA DX, MSG
INT 21H
MOV AL, RESHI
CALL SHOW_HEX_BYTE
MOV AL, RESLO
CALL SHOW_HEX_BYTE
; (decimal display omitted for brevity - product is FFF1H = -15)
MOV AH, 4CH
INT 21H
; Show byte in AL as 2 hex digits
SHOW_HEX_BYTE PROC
PUSH AX
PUSH CX
MOV CL, AL
SHR AL, 4 ; high nibble
MOV BX, OFFSET DIGS
XLAT
MOV DL, AL
MOV AH, 02H
INT 21H
MOV AL, CL
AND AL, 0FH ; low nibble
XLAT
MOV DL, AL
MOV AH, 02H
INT 21H
POP CX
POP AX
RET
SHOW_HEX_BYTE ENDP
CODE ENDS
END START
Exp 13 Restoring & non-restoring division + worked examples
;-------------------------------------------------------
; EXP 13 : 8-bit unsigned RESTORING DIVISION on 8086
; Dividend in DIVIDEND, divisor in DIVISOR
; Result -> AL = quotient, DX = remainder
;-------------------------------------------------------
.MODEL SMALL
.STACK 100H
.DATA
DIVIDEND DB 23
DIVISOR DB 5
MSG1 DB 0DH,0AH,'Dividend = 23, Divisor = 5',0DH,0AH,'$'
MSGQ DB 'Quotient = $'
MSGR DB 0DH,0AH,'Remainder = $'
.CODE
MAIN PROC
MOV AX,@DATA
MOV DS,AX
LEA DX,MSG1
MOV AH,09H
INT 21H
MOV AL,DIVIDEND ; Q = dividend
MOV BL,DIVISOR
XOR BH,BH ; BX = divisor as a word
XOR DX,DX ; A = 0
MOV CX,8 ; 8 cycles for 8-bit numbers
DIV_LOOP:
SHL AL,1 ; shift Q left, old Q7 goes to Carry (FIX: AL not AX)
RCL DX,1 ; shift A left, Carry (old Q7) enters A0
SUB DX,BX ; A = A - M
JNC NO_RESTORE ; CF=0 means no borrow, so A >= 0
ADD DX,BX ; A was negative: restore A = A + M
JMP NEXT
NO_RESTORE:
OR AL,1 ; A >= 0 : set Q0 = 1
NEXT:
LOOP DIV_LOOP
; now AL = quotient, DX = remainder
PUSH DX ; save remainder
LEA DX,MSGQ
MOV AH,09H
INT 21H
CALL PRINT_DEC ; print quotient (in AL)
LEA DX,MSGR
MOV AH,09H
INT 21H
POP DX
MOV AL,DL
CALL PRINT_DEC ; print remainder
MOV AH,4CH
INT 21H
MAIN ENDP
; Prints unsigned byte in AL as decimal (uses INT 21H/02H)
PRINT_DEC PROC
PUSH AX
PUSH BX
PUSH CX
PUSH DX
XOR AH,AH
MOV CX,0
MOV BX,10
PD1:
XOR DX,DX
DIV BX ; AX/10 -> quotient AX, remainder DX
PUSH DX
INC CX
CMP AX,0
JNE PD1
PD2:
POP DX
ADD DL,'0'
MOV AH,02H
INT 21H
LOOP PD2
POP DX
POP CX
POP BX
POP AX
RET
PRINT_DEC ENDP
END MAIN
Exp 14 Cache memory mapping simulation (direct / associative / set-associative)
/* EXP 14 : cache mapping simulation
16-bit address, 64 lines, 4 words/line, 4-way set associative */
#include <stdio.h>
#define LINES 64
#define SETS 16
#define WAYS 4
int d_valid[LINES], d_tag[LINES]; /* direct */
int a_valid[LINES], a_tag[LINES]; /* assoc */
int s_valid[SETS][WAYS], s_tag[SETS][WAYS];/* set-assoc */
void init_all(void) {
int i, s, w;
for (i = 0; i < LINES; i++)
d_valid[i] = a_valid[i] = 0, d_tag[i] = a_tag[i] = -1;
for (s = 0; s < SETS; s++)
for (w = 0; w < WAYS; w++)
s_valid[s][w] = 0, s_tag[s][w] = -1;
}
/* DIRECT: index = bits[7:2], tag = bits[15:8], offset = bits[1:0] */
int direct_access(unsigned a) {
int idx = (a >> 2) & 0x3F; /* 6-bit index */
int tag = a >> 8; /* 8-bit tag */
printf(" direct : addr %04X -> tag %02X index %2d : ", a, tag, idx);
if (d_valid[idx] && d_tag[idx] == tag) { printf("HIT\n"); return 1; }
d_valid[idx] = 1; d_tag[idx] = tag;
printf("MISS (line %d now holds tag %02X)\n", idx, tag);
return 0;
}
/* FULLY ASSOCIATIVE: tag = bits[15:2] compared with every line */
int assoc_access(unsigned a) {
int tag = a >> 2, i; /* 14-bit tag */
printf(" assoc : addr %04X -> tag %03X : ", a, tag);
for (i = 0; i < LINES; i++)
if (a_valid[i] && a_tag[i] == tag) { printf("HIT\n"); return 1; }
for (i = 0; i < LINES; i++) /* first empty line */
if (!a_valid[i]) { a_valid[i] = 1; a_tag[i] = tag;
printf("MISS (stored in line %d)\n", i); return 0; }
a_valid[0] = 1; a_tag[0] = tag; /* simple replacement */
printf("MISS (replaced line 0)\n");
return 0;
}
/* 4-WAY SET ASSOCIATIVE: set = bits[5:2], tag = bits[15:6] */
int setassoc_access(unsigned a) {
int set = (a >> 2) & 0x0F; /* 4-bit set index (16 sets) */
int tag = a >> 6, w; /* 10-bit tag */
printf(" setasc : addr %04X -> tag %03X set %2d : ", a, tag, set);
for (w = 0; w < WAYS; w++)
if (s_valid[set][w] && s_tag[set][w] == tag) { printf("HIT\n"); return 1; }
for (w = 0; w < WAYS; w++)
if (!s_valid[set][w]) { s_valid[set][w] = 1; s_tag[set][w] = tag;
printf("MISS (stored in set %d way %d)\n", set, w); return 0; }
s_valid[set][0] = 1; s_tag[set][0] = tag;
printf("MISS (replaced way 0 of set %d)\n", set);
return 0;
}
int main(void) {
/* 0x0104 and 0x4104 map to the SAME direct-mapped line but
different tags -> they thrash each other in direct mapping */
unsigned trace[] = {0x0104, 0x0105, 0x4104, 0x0104};
int i;
printf("--- DIRECT MAPPING ---\n");
init_all();
for (i = 0; i < 4; i++) direct_access(trace[i]);
printf("--- FULLY ASSOCIATIVE ---\n");
init_all();
for (i = 0; i < 4; i++) assoc_access(trace[i]);
printf("--- 4-WAY SET ASSOCIATIVE ---\n");
init_all();
for (i = 0; i < 4; i++) setassoc_access(trace[i]);
return 0;
}
Exp 15 Displaying 8086 flag register contents
;-------------------------------------------------------
; EXP 15 : display 8086 flag register contents
; Does ADD AL,BL, then PUSHF / POP BX and prints each flag
;-------------------------------------------------------
.MODEL SMALL
.STACK 100H
.DATA
HEAD DB 0DH,0AH,'FLAG REGISTER AFTER ADD AL,BL (25H+1BH=40H)',0DH,0AH,'$'
N_CF DB 'CF = $'
N_PF DB 0DH,0AH,'PF = $'
N_AF DB 0DH,0AH,'AF = $'
N_ZF DB 0DH,0AH,'ZF = $'
N_SF DB 0DH,0AH,'SF = $'
N_TF DB 0DH,0AH,'TF = $'
N_IF DB 0DH,0AH,'IF = $'
N_DF DB 0DH,0AH,'DF = $'
N_OF DB 0DH,0AH,'OF = $'
.CODE
MAIN PROC
MOV AX,@DATA
MOV DS,AX
MOV AL,25H
MOV BL,1BH
ADD AL,BL ; the operation whose flags we inspect
PUSHF
POP BX ; BX = flag register image
LEA DX,HEAD
MOV AH,09H
INT 21H
; macro-like sequence: print name, TEST the bit, print '1'/'0'
LEA DX,N_CF
MOV AH,09H
INT 21H
TEST BX,0001H ; CF = bit 0
JZ B0_CF
MOV DL,'1'
JMP P_CF
B0_CF:
MOV DL,'0'
P_CF:
MOV AH,02H
INT 21H
LEA DX,N_PF
MOV AH,09H
INT 21H
TEST BX,0004H ; PF = bit 2
JZ B0_PF
MOV DL,'1'
JMP P_PF
B0_PF:
MOV DL,'0'
P_PF:
MOV AH,02H
INT 21H
LEA DX,N_AF
MOV AH,09H
INT 21H
TEST BX,0010H ; AF = bit 4
JZ B0_AF
MOV DL,'1'
JMP P_AF
B0_AF:
MOV DL,'0'
P_AF:
MOV AH,02H
INT 21H
LEA DX,N_ZF
MOV AH,09H
INT 21H
TEST BX,0040H ; ZF = bit 6
JZ B0_ZF
MOV DL,'1'
JMP P_ZF
B0_ZF:
MOV DL,'0'
P_ZF:
MOV AH,02H
INT 21H
LEA DX,N_SF
MOV AH,09H
INT 21H
TEST BX,0080H ; SF = bit 7
JZ B0_SF
MOV DL,'1'
JMP P_SF
B0_SF:
MOV DL,'0'
P_SF:
MOV AH,02H
INT 21H
LEA DX,N_TF
MOV AH,09H
INT 21H
TEST BX,0100H ; TF = bit 8
JZ B0_TF
MOV DL,'1'
JMP P_TF
B0_TF:
MOV DL,'0'
P_TF:
MOV AH,02H
INT 21H
LEA DX,N_IF
MOV AH,09H
INT 21H
TEST BX,0200H ; IF = bit 9
JZ B0_IF
MOV DL,'1'
JMP P_IF
B0_IF:
MOV DL,'0'
P_IF:
MOV AH,02H
INT 21H
LEA DX,N_DF
MOV AH,09H
INT 21H
TEST BX,0400H ; DF = bit 10
JZ B0_DF
MOV DL,'1'
JMP P_DF
B0_DF:
MOV DL,'0'
P_DF:
MOV AH,02H
INT 21H
LEA DX,N_OF
MOV AH,09H
INT 21H
TEST BX,0800H ; OF = bit 11
JZ B0_OF
MOV DL,'1'
JMP P_OF
B0_OF:
MOV DL,'0'
P_OF:
MOV AH,02H
INT 21H
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
Exp 16 Designing 4×4 memory using 1×1 chips
A1 A0
\ /
+---------------+
| 2-to-4 |
| DECODER |
+--+---+---+-- -+
| | | |
Y0 ---------+ | | |
Y1 -------------+ | |
Y2 -----------------+ |
Y3 ---------------------+
row 0 (addr 00) <--- Y0 ----+------+------+------+------+
| | | | |
[1x1] [1x1] [1x1] [1x1] <- word 0
| | | | |
row 1 (addr 01) <--- Y1 ----+------+------+------+------+
| | | | |
[1x1] [1x1] [1x1] [1x1] <- word 1
| | | | |
row 2 (addr 10) <--- Y2 ----+------+------+------+------+
| | | | |
[1x1] [1x1] [1x1] [1x1] <- word 2
| | | | |
row 3 (addr 11) <--- Y3 ----+------+------+------+------+
| | | | |
[1x1] [1x1] [1x1] [1x1] <- word 3
| | | | |
D3 D2 D1 D0
\ \ \ \
v v v v
4-bit data bus
Exp 17 Greatest number in series (teacher's important list — not in journal)
; GREATEST.ASM - Greatest number in a series (MASM, 8086)
; Method: take the first number as MAX, compare every next number,
; replace MAX whenever a bigger number comes, loop till the series ends.
.186
.MODEL SMALL
.STACK 100H
.DATA
ARR DB 12, 45, 7, 89, 33, 67, 90, 21
LEN EQU 8
MSG DB 0DH,0AH,'Greatest number = $'
.CODE
MAIN PROC
MOV AX,@DATA
MOV DS,AX
LEA SI,ARR ; SI points to the series
MOV AL,[SI] ; MAX = first number
MOV CX,LEN-1 ; numbers still to check
INC SI ; move to the second number
CHK:
CMP AL,[SI] ; compare MAX with next number
JAE SKIP ; MAX already bigger or equal: keep it
MOV AL,[SI] ; else this number becomes the new MAX
SKIP:
INC SI
LOOP CHK
; print the result (MAX is in AL, 0-99, as two digits)
LEA DX,MSG
MOV AH,09H
INT 21H
XOR AH,AH
MOV BL,10
DIV BL ; AL = tens, AH = ones
MOV CL,AH ; save ones
CMP AL,0
JE ONES_ONLY
ADD AL,30H
MOV DL,AL
MOV AH,02H
INT 21H
ONES_ONLY:
MOV DL,CL
ADD DL,30H
MOV AH,02H
INT 21H
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
AOA Lab — Analysis of Algorithms
C programs from the verified journal set — each was compiled with gcc and run.
Exp 1 Selection Sort and Insertion Sort (with comparison)
#include <stdio.h>
int main() {
int n, i, j;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[50], b[50];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
b[i] = a[i]; /* keep a fresh copy for insertion sort */
}
/* ---------- Selection Sort ---------- */
int compSel = 0, swapSel = 0;
for (i = 0; i < n - 1; i++) {
int minIdx = i;
for (j = i + 1; j < n; j++) {
compSel++;
if (a[j] < a[minIdx])
minIdx = j;
}
if (minIdx != i) {
int t = a[i]; a[i] = a[minIdx]; a[minIdx] = t;
swapSel++;
}
}
printf("\nSelection Sort result: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
printf("\nComparisons = %d, Swaps = %d\n", compSel, swapSel);
/* ---------- Insertion Sort ---------- */
int compIns = 0, swapIns = 0;
for (i = 1; i < n; i++) {
int key = b[i];
j = i - 1;
while (j >= 0) {
compIns++;
if (b[j] > key) {
b[j + 1] = b[j]; /* shift right */
swapIns++;
j--;
} else break;
}
b[j + 1] = key;
}
printf("\nInsertion Sort result: ");
for (i = 0; i < n; i++) printf("%d ", b[i]);
printf("\nComparisons = %d, Shifts = %d\n", compIns, swapIns);
return 0;
}
Exp 2 Divide & Conquer — Merge Sort, Quick Sort, Binary Search
#include <stdio.h>
void merge(int a[], int l, int m, int r) {
int n1 = m - l + 1, n2 = r - m, i, j, k;
int L[50], R[50];
for (i = 0; i < n1; i++) L[i] = a[l + i];
for (j = 0; j < n2; j++) R[j] = a[m + 1 + j];
i = 0; j = 0; k = l;
while (i < n1 && j < n2) { /* combine step */
if (L[i] <= R[j]) a[k++] = L[i++];
else a[k++] = R[j++];
}
while (i < n1) a[k++] = L[i++];
while (j < n2) a[k++] = R[j++];
}
void mergeSort(int a[], int l, int r) {
if (l < r) {
int m = (l + r) / 2;
mergeSort(a, l, m); /* conquer left */
mergeSort(a, m + 1, r); /* conquer right */
merge(a, l, m, r); /* combine */
}
}
int partition(int a[], int l, int r) {
int pivot = a[r], i = l - 1, j, t;
for (j = l; j < r; j++) {
if (a[j] < pivot) {
i++;
t = a[i]; a[i] = a[j]; a[j] = t;
}
}
t = a[i + 1]; a[i + 1] = a[r]; a[r] = t;
return i + 1;
}
void quickSort(int a[], int l, int r) {
if (l < r) {
int p = partition(a, l, r);
quickSort(a, l, p - 1);
quickSort(a, p + 1, r);
}
}
int binarySearch(int a[], int n, int key) {
int low = 0, high = n - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) return mid;
else if (a[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
int main() {
int n, i, key;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[50], b[50];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
b[i] = a[i];
}
mergeSort(a, 0, n - 1);
printf("\nAfter Merge Sort: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
quickSort(b, 0, n - 1);
printf("\nAfter Quick Sort: ");
for (i = 0; i < n; i++) printf("%d ", b[i]);
printf("\n\nEnter key to search: ");
scanf("%d", &key);
int pos = binarySearch(a, n, key); /* search the merge-sorted array */
if (pos != -1) printf("Key %d found at index %d (0-based)\n", key, pos);
else printf("Key %d not found\n", key);
return 0;
}
Exp 3 Greedy — Dijkstra's Single-Source Shortest Path
#include <stdio.h>
#define V 5
#define INF 9999
/* greedy choice: unvisited vertex with the smallest distance */
int minDist(int dist[], int vis[]) {
int min = INF, idx = -1, v;
for (v = 0; v < V; v++)
if (!vis[v] && dist[v] < min) { min = dist[v]; idx = v; }
return idx;
}
void dijkstra(int g[V][V], int src) {
int dist[V], vis[V], v, u;
for (v = 0; v < V; v++) { dist[v] = INF; vis[v] = 0; }
dist[src] = 0;
printf("\n%-6s | %-6s | %-18s | %-22s\n",
"Step", "Pick", "Relaxed from picked", "dist[] after step");
printf("------------------------------------------------------------\n");
for (int step = 1; step <= V; step++) {
u = minDist(dist, vis);
if (u == -1) break;
vis[u] = 1;
printf("%-6d | %-6d | ", step, u);
int first = 1;
for (v = 0; v < V; v++) {
if (!vis[v] && g[u][v] != 0 && dist[u] != INF
&& dist[u] + g[u][v] < dist[v]) {
if (!first) printf(", ");
printf("%d->%d (d%d=%d)", u, v, v, dist[u] + g[u][v]);
first = 0;
dist[v] = dist[u] + g[u][v]; /* relaxation */
}
}
if (first) printf("none");
printf(" | [");
for (v = 0; v < V; v++) {
if (dist[v] == INF) printf("inf");
else printf("%d", dist[v]);
if (v < V - 1) printf(", ");
}
printf("]\n");
}
printf("\nShortest distances from source %d:\n", src);
for (v = 0; v < V; v++)
printf(" 0 -> %d : %d\n", v, dist[v]);
}
int main() {
/* undirected edges: 0-1:10, 0-3:30, 0-4:100, 1-2:50, 2-3:20, 2-4:10, 3-4:60 */
int g[V][V] = {
{0, 10, 0, 30, 100},
{10, 0, 50, 0, 0},
{0, 50, 0, 20, 10},
{30, 0, 20, 0, 60},
{100, 0, 10, 60, 0}
};
int src;
printf("Enter source vertex (0-4): ");
scanf("%d", &src);
dijkstra(g, src);
return 0;
}
Exp 4 Greedy — Fractional Knapsack
#include <stdio.h>
int main() {
int n, i, j;
printf("Enter number of items: ");
scanf("%d", &n);
float value[20], weight[20], ratio[20];
for (i = 0; i < n; i++) {
printf("Enter value and weight of item %d: ", i + 1);
scanf("%f %f", &value[i], &weight[i]);
ratio[i] = value[i] / weight[i]; /* profit per kg */
}
float W;
printf("Enter knapsack capacity: ");
scanf("%f", &W);
/* greedy order: sort by ratio, descending */
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (ratio[j] < ratio[j + 1]) {
float t = ratio[j]; ratio[j] = ratio[j + 1]; ratio[j + 1] = t;
t = value[j]; value[j] = value[j + 1]; value[j + 1] = t;
t = weight[j]; weight[j] = weight[j + 1]; weight[j + 1] = t;
}
printf("\nItem Value Weight v/w ratio\n");
for (i = 0; i < n; i++)
printf("%-5d %-7.0f %-7.0f %.2f\n", i + 1, value[i], weight[i], ratio[i]);
float total = 0, remaining = W;
printf("\nItem Taken(kg) Fraction Contribution\n");
for (i = 0; i < n && remaining > 0; i++) {
float take = (weight[i] <= remaining) ? weight[i] : remaining;
float frac = take / weight[i];
float gain = frac * value[i];
total += gain;
remaining -= take;
printf("%-5d %-10.0f %-9.2f %.2f\n", i + 1, take, frac, gain);
}
printf("\nTotal value in knapsack = %.2f\n", total);
return 0;
}
Exp 5 Minimum Spanning Tree — Kruskal's and Prim's (with comparison)
#include <stdio.h>
#define V 4
#define E 5
/* Union-Find helpers for Kruskal */
int findSet(int parent[], int x) {
if (parent[x] == x) return x;
return parent[x] = findSet(parent, parent[x]);
}
void unionSet(int parent[], int a, int b) {
parent[findSet(parent, a)] = findSet(parent, b);
}
int main(void) {
/* Fixed demo graph, echoed below */
int u[E] = {0, 0, 0, 1, 2};
int v[E] = {1, 2, 3, 3, 3};
int w[E] = {10, 6, 5, 15, 4};
int i, j, count, total;
printf("Edges of the graph (u - v : weight):\n");
for (i = 0; i < E; i++)
printf("%d - %d : %d\n", u[i], v[i], w[i]);
/* ---------- Kruskal ---------- */
/* sort edges by weight (simple bubble sort on index order) */
int order[E] = {0, 1, 2, 3, 4};
for (i = 0; i < E - 1; i++)
for (j = 0; j < E - 1 - i; j++)
if (w[order[j]] > w[order[j + 1]]) {
int t = order[j]; order[j] = order[j + 1]; order[j + 1] = t;
}
printf("\n--- KRUSKAL'S ALGORITHM ---\nEdges sorted by weight:\n");
for (i = 0; i < E; i++)
printf("%d - %d : %d\n", u[order[i]], v[order[i]], w[order[i]]);
int parent[V];
for (i = 0; i < V; i++) parent[i] = i;
printf("MST edges: ");
total = 0; count = 0;
for (i = 0; i < E && count < V - 1; i++) {
int a = u[order[i]], b = v[order[i]];
if (findSet(parent, a) != findSet(parent, b)) {
unionSet(parent, a, b);
printf("(%d,%d) ", a, b);
total += w[order[i]];
count++;
}
}
printf("\nTotal weight (Kruskal) = %d\n", total);
/* ---------- Prim ---------- */
printf("\n--- PRIM'S ALGORITHM (start vertex 0) ---\n");
int inTree[V] = {0}, key[V], edgeU[V];
for (i = 0; i < V; i++) { key[i] = 9999; edgeU[i] = -1; }
key[0] = 0;
total = 0;
for (count = 0; count < V; count++) {
/* pick cheapest vertex outside the tree */
int best = -1;
for (i = 0; i < V; i++)
if (!inTree[i] && (best == -1 || key[i] < key[best])) best = i;
inTree[best] = 1;
if (edgeU[best] != -1) {
printf("Add edge (%d,%d) weight %d\n", edgeU[best], best, key[best]);
total += key[best];
}
/* relax: update cheapest connection through 'best' */
for (i = 0; i < E; i++) {
int x = u[i], y = v[i];
if (x == best && !inTree[y] && w[i] < key[y]) { key[y] = w[i]; edgeU[y] = x; }
if (y == best && !inTree[x] && w[i] < key[x]) { key[x] = w[i]; edgeU[x] = y; }
}
}
printf("Total weight (Prim) = %d\n", total);
return 0;
}
Exp 6 Dynamic Programming — Floyd-Warshall + 0/1 Knapsack
#include <stdio.h>
#define N 4
#define INF 999
int max2(int a, int b) { return a > b ? a : b; }
int main(void) {
/* ---------- Floyd-Warshall (fixed demo input) ---------- */
int d[N][N] = {
{0, 3, INF, 7},
{8, 0, 2, INF},
{5, INF, 0, 1},
{2, INF, INF, 0}
};
int i, j, k;
printf("Initial cost matrix:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) printf("%4d", d[i][j]);
printf("\n");
}
for (k = 0; k < N; k++)
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
if (d[i][k] + d[k][j] < d[i][j])
d[i][j] = d[i][k] + d[k][j];
printf("\nAll-pairs shortest path matrix:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) printf("%4d", d[i][j]);
printf("\n");
}
/* ---------- 0/1 Knapsack (fixed demo input) ---------- */
int val[4] = {0, 60, 100, 120}; /* 1-indexed: 3 items */
int wt[4] = {0, 10, 20, 30};
int n = 3; /* capacity W = 50, in steps of 10 */
int dp[4][6]; /* columns = capacity 0..50 */
int c;
for (c = 0; c <= 5; c++) dp[0][c] = 0;
for (i = 1; i <= n; i++)
for (c = 0; c <= 5; c++) {
int cap = c * 10;
if (wt[i] > cap) dp[i][c] = dp[i - 1][c];
else dp[i][c] = max2(dp[i - 1][c], val[i] + dp[i - 1][c - wt[i] / 10]);
}
printf("\nKnapsack DP table (columns = capacity 0,10,...,50):\n");
printf(" 0 10 20 30 40 50\n");
for (i = 1; i <= n; i++) {
printf("item%d: ", i);
for (c = 0; c <= 5; c++) printf("%3d ", dp[i][c]);
printf("\n");
}
printf("Optimal value = %d (items 2 and 3: 100+120, weight 20+30=50)\n", dp[n][5]);
return 0;
}
Exp 7 Travelling Salesperson Problem + Longest Common Subsequence
#include <stdio.h>
#include <string.h>
#define N 4
int dist[N][N] = {
{ 0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
int bestCost = 1000000;
int bestTour[N + 1];
/* try every permutation of cities[1..N-1]; city 0 is the fixed start */
void permute(int a[], int l, int r) {
int i, cost, k;
if (l == r) {
cost = dist[0][a[0]];
for (i = 0; i < r; i++) cost += dist[a[i]][a[i + 1]];
cost += dist[a[r]][0];
printf("Tour 0");
for (i = 0; i <= r; i++) printf("-%d", a[i]);
printf("-0 : cost = %d\n", cost);
if (cost < bestCost) {
bestCost = cost;
bestTour[0] = 0;
for (k = 0; k <= r; k++) bestTour[k + 1] = a[k];
bestTour[N] = 0;
}
return;
}
for (i = l; i <= r; i++) {
int t = a[l]; a[l] = a[i]; a[i] = t;
permute(a, l + 1, r);
t = a[l]; a[l] = a[i]; a[i] = t;
}
}
int max2(int a, int b) { return a > b ? a : b; }
int main(void) {
int order[N - 1] = {1, 2, 3}, i, j;
printf("--- TSP (start city 0) ---\n");
permute(order, 0, N - 2);
printf("Minimum tour cost = %d (route 0", bestCost);
for (i = 1; i <= N; i++) printf("-%d", bestTour[i]);
printf(")\n");
/* ---------- LCS ---------- */
char X[] = "AGGTAB", Y[] = "GXTXAYB";
int m = strlen(X), n = strlen(Y);
int dp[7][8];
for (i = 0; i <= m; i++)
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0) dp[i][j] = 0;
else if (X[i - 1] == Y[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = max2(dp[i - 1][j], dp[i][j - 1]);
}
printf("\n--- LCS of \"%s\" and \"%s\" ---\n ", X, Y);
for (j = 0; j < n; j++) printf(" %c", Y[j]);
printf("\n");
for (i = 0; i <= m; i++) {
printf("%c ", i == 0 ? ' ' : X[i - 1]);
for (j = 0; j <= n; j++) printf("%2d", dp[i][j]);
printf("\n");
}
/* backtrack */
char lcs[8]; int len = 0;
i = m; j = n;
while (i > 0 && j > 0) {
if (X[i - 1] == Y[j - 1]) { lcs[len++] = X[i - 1]; i--; j--; }
else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
else j--;
}
printf("LCS length = %d, LCS = \"", dp[m][n]);
for (i = len - 1; i >= 0; i--) printf("%c", lcs[i]);
printf("\"\n");
return 0;
}
Exp 8 Graph Traversals — BFS and DFS
#include <stdio.h>
#define V 6
/* adjacency lists in increasing order (undirected graph) */
int adj[V][V] = {
{1, 2, -1, -1}, /* 0: 1, 2 */
{0, 3, 4, -1}, /* 1: 0, 3, 4 */
{0, 4, -1, -1}, /* 2: 0, 4 */
{1, 5, -1, -1}, /* 3: 1, 5 */
{1, 2, 5, -1}, /* 4: 1, 2, 5 */
{3, 4, -1, -1} /* 5: 3, 4 */
};
int deg[V] = {2, 3, 2, 2, 3, 2};
int visited[V];
void bfs(int s) {
int q[V], front = 0, rear = 0, i, u, v;
for (i = 0; i < V; i++) visited[i] = 0;
visited[s] = 1;
q[rear++] = s;
printf("BFS order: ");
while (front < rear) {
u = q[front++];
printf("%d ", u);
for (i = 0; i < deg[u]; i++) {
v = adj[u][i];
if (!visited[v]) { visited[v] = 1; q[rear++] = v; }
}
}
printf("\n");
}
void dfs(int s) {
int i, v;
visited[s] = 1;
printf("%d ", s);
for (i = 0; i < deg[s]; i++) {
v = adj[s][i];
if (!visited[v]) dfs(v);
}
}
int main(void) {
int i;
printf("Edges: 0-1 0-2 1-3 1-4 2-4 3-5 4-5\n\n");
bfs(0);
for (i = 0; i < V; i++) visited[i] = 0;
printf("DFS order: ");
dfs(0);
printf("\n");
return 0;
}
Exp 9 Backtracking — N-Queens, Sum of Subsets, Graph Coloring
/* Experiment 9: Backtracking - N-Queens, Sum of Subsets, Graph Coloring */
#include <stdio.h>
/* ---------- Part 1: N-Queens (n = 4) ---------- */
#define NQ 4
int qcol[NQ + 1]; /* qcol[r] = column of queen in row r (1-indexed) */
int qcount = 0;
int qsafe(int row, int c) {
for (int i = 1; i < row; i++) {
int dcol = c > qcol[i] ? c - qcol[i] : qcol[i] - c;
if (qcol[i] == c || (row - i) == dcol)
return 0; /* same column or same diagonal */
}
return 1;
}
void qsolve(int row) {
if (row > NQ) {
qcount++;
printf(" Solution %d: (%d, %d, %d, %d)\n",
qcount, qcol[1], qcol[2], qcol[3], qcol[4]);
return;
}
for (int c = 1; c <= NQ; c++)
if (qsafe(row, c)) { qcol[row] = c; qsolve(row + 1); }
}
/* ---------- Part 2: Sum of Subsets ---------- */
int sw[] = {2, 3, 4, 5, 12, 34}; /* sorted form of {3, 34, 4, 12, 5, 2} */
int sn = 6, starget = 9, sx[6] = {0}, scount = 0;
void sos(int k, int csum) {
if (csum == starget) {
scount++;
printf(" Subset %d: { ", scount);
for (int i = 0; i < sn; i++)
if (sx[i]) printf("%d ", sw[i]);
printf("}\n");
return;
}
if (k == sn) return;
if (csum + sw[k] <= starget) { sx[k] = 1; sos(k + 1, csum + sw[k]); sx[k] = 0; }
sos(k + 1, csum); /* exclude sw[k] */
}
/* ---------- Part 3: Graph Coloring ---------- */
#define GV 4
int gadj[GV][GV] = {
{0, 1, 1, 0},
{1, 0, 1, 1},
{1, 1, 0, 1},
{0, 1, 1, 0}
};
int gcolor[GV] = {0}, gmax = 3;
int gok(int v, int c) {
for (int i = 0; i < GV; i++)
if (gadj[v][i] && gcolor[i] == c) return 0;
return 1;
}
int gbacktrack(int v) {
if (v == GV) return 1;
for (int c = 1; c <= gmax; c++)
if (gok(v, c)) { gcolor[v] = c; if (gbacktrack(v + 1)) return 1; gcolor[v] = 0; }
return 0;
}
int main(void) {
printf("PART 1: N-Queens (n = 4)\n");
qsolve(1);
printf(" Total solutions for 4-queens: %d\n\n", qcount);
printf("PART 2: Sum of Subsets\n");
printf(" Set = {3, 34, 4, 12, 5, 2}, target sum = 9\n");
sos(0, 0);
printf(" Total subsets found: %d\n\n", scount);
printf("PART 3: Graph Coloring (m = 3)\n");
printf(" Edges: 0-1, 0-2, 1-2, 1-3, 2-3\n");
if (gbacktrack(0)) {
for (int v = 0; v < GV; v++)
printf(" Vertex %d -> Color %d\n", v, gcolor[v]);
printf(" Chromatic number = 3 (vertices 0, 1, 2 form a triangle)\n");
} else {
printf(" No 3-coloring exists.\n");
}
return 0;
}
Exp 10 Branch and Bound — 0/1 Knapsack
/* Experiment 10: 0/1 Knapsack via Branch and Bound (best-first, fractional bounds) */
#include <stdio.h>
#define N 3
#define MAXQ 64
typedef struct { int value, weight; } Item;
/* items sorted by value/weight ratio in descending order: 6, 5, 4 */
Item items[N] = { {60, 10}, {100, 20}, {120, 30} };
int W = 50;
typedef struct {
int level; /* next item index to decide (0..N) */
int profit, weight;
double bound; /* fractional-knapsack upper bound */
int taken[N]; /* include/exclude decisions made so far */
} Node;
Node queue[MAXQ];
int qsize = 0;
void push(Node nd) { queue[qsize++] = nd; }
Node popmax(void) { /* simple priority queue: pop node with largest bound */
int bi = 0;
for (int i = 1; i < qsize; i++)
if (queue[i].bound > queue[bi].bound) bi = i;
Node nd = queue[bi];
queue[bi] = queue[--qsize];
return nd;
}
/* upper bound: current profit + greedy fractional fill of remaining capacity */
double bound(Node *nd) {
if (nd->weight > W) return 0.0;
double b = nd->profit;
int w = nd->weight, i = nd->level;
while (i < N && w + items[i].weight <= W) {
w += items[i].weight;
b += items[i].value;
i++;
}
if (i < N) b += (W - w) * ((double)items[i].value / items[i].weight);
return b;
}
void printvec(Node *u) {
printf("[");
for (int i = 0; i < u->level; i++) printf("x%d=%d ", i + 1, u->taken[i]);
printf("]");
}
int main(void) {
int best = 0, bestTaken[N] = {0, 0, 0};
printf("0/1 Knapsack - Branch and Bound (best-first search)\n");
printf("Capacity W = %d\n", W);
printf("Items (value, weight): ");
for (int i = 0; i < N; i++) printf("%d:(%d,%d) ", i + 1, items[i].value, items[i].weight);
printf("\n\n");
Node root = {0, 0, 0, 0.0, {0, 0, 0}};
root.bound = bound(&root);
push(root);
while (qsize > 0) {
Node u = popmax();
printf("Expand level=%d profit=%d weight=%d bound=%.2f ",
u.level, u.profit, u.weight, u.bound);
printvec(&u);
printf("\n");
if (u.level == N) { /* leaf: all items decided */
if (u.profit > best) {
best = u.profit;
for (int i = 0; i < N; i++) bestTaken[i] = u.taken[i];
printf(" Leaf: profit %d -> new best = %d\n", u.profit, best);
} else {
printf(" Leaf: profit %d <= best %d, ignored\n", u.profit, best);
}
continue;
}
if (u.bound <= best) { /* bounding: cannot beat best */
printf(" Pruned: bound %.2f <= best %d\n", u.bound, best);
continue;
}
/* branch 1: include items[u.level] */
Node v = u;
v.level++;
v.taken[u.level] = 1;
v.profit += items[u.level].value;
v.weight += items[u.level].weight;
if (v.weight > W) {
printf(" Include item %d: weight %d > %d, infeasible, discarded\n",
u.level + 1, v.weight, W);
} else {
v.bound = bound(&v);
printf(" Include item %d: profit=%d weight=%d bound=%.2f -> queued\n",
u.level + 1, v.profit, v.weight, v.bound);
push(v);
}
/* branch 2: exclude items[u.level] */
Node wnd = u;
wnd.level++;
wnd.taken[u.level] = 0;
wnd.bound = bound(&wnd);
printf(" Exclude item %d: profit=%d weight=%d bound=%.2f -> queued\n",
u.level + 1, wnd.profit, wnd.weight, wnd.bound);
push(wnd);
}
printf("\nOptimal profit = %d\nItems selected:", best);
for (int i = 0; i < N; i++) if (bestTaken[i]) printf(" %d", i + 1);
printf("\n");
return 0;
}
Exp 11 String Matching — Naïve, Rabin-Karp, Knuth-Morris-Pratt
/* Experiment 11: String Matching - Naive, Rabin-Karp, KMP */
#include <stdio.h>
#include <string.h>
char T[] = "AABAACAADAABAABA"; /* text, n = 16 */
char P[] = "AABA"; /* pattern, m = 4 */
/* ---------- Naive ---------- */
void naive(void) {
int n = strlen(T), m = strlen(P), cmp = 0, found = 0;
printf("--- Naive ---\n");
for (int s = 0; s <= n - m; s++) {
int j = 0;
while (j < m) {
cmp++;
if (T[s + j] != P[j]) break;
j++;
}
if (j == m) { printf(" Pattern found at shift %d\n", s); found++; }
}
printf(" Matches: %d, character comparisons: %d\n", found, cmp);
}
/* ---------- Rabin-Karp ---------- */
void rabinKarp(void) {
int n = strlen(T), m = strlen(P), d = 256, q = 101;
int h = 1, p = 0, t = 0;
for (int i = 0; i < m - 1; i++) h = (h * d) % q; /* h = d^(m-1) mod q */
for (int i = 0; i < m; i++) { /* initial hashes */
p = (d * p + P[i]) % q;
t = (d * t + T[i]) % q;
}
printf("--- Rabin-Karp (d = %d, q = %d) ---\n", d, q);
printf(" Pattern hash = %d, h = d^(m-1) mod q = %d\n", p, h);
for (int s = 0; s <= n - m; s++) {
if (p == t) {
int j = 0;
while (j < m && T[s + j] == P[j]) j++;
if (j == m)
printf(" shift %2d: window hash = %d -> MATCH\n", s, t);
else
printf(" shift %2d: window hash = %d -> hash equal but chars differ (spurious hit)\n", s, t);
} else {
printf(" shift %2d: window hash = %d\n", s, t);
}
if (s < n - m) { /* rolling hash */
t = (d * (t - T[s] * h) + T[s + m]) % q;
if (t < 0) t += q;
}
}
}
/* ---------- KMP ---------- */
void kmp(void) {
int n = strlen(T), m = strlen(P), lps[16];
/* build prefix (lps) table */
lps[0] = 0;
for (int i = 1, len = 0; i < m; ) {
if (P[i] == P[len]) lps[i++] = ++len;
else if (len) len = lps[len - 1];
else lps[i++] = 0;
}
printf("--- KMP ---\n lps array: [ ");
for (int i = 0; i < m; i++) printf("%d ", lps[i]);
printf("]\n");
int i = 0, j = 0; /* i over text, j over pattern */
while (i < n) {
if (P[j] == T[i]) { j++; i++; }
if (j == m) {
printf(" Pattern found at shift %d\n", i - j);
j = lps[j - 1];
} else if (i < n && P[j] != T[i]) {
if (j) j = lps[j - 1]; /* slide pattern using lps, no re-scan */
else i++;
}
}
}
int main(void) {
printf("Text T = \"%s\" (n = %lu)\n", T, strlen(T));
printf("Pattern P = \"%s\" (m = %lu)\n\n", P, strlen(P));
naive();
printf("\n");
rabinKarp();
printf("\n");
kmp();
return 0;
}
Exp 12 Min-Max Algorithm + Job Sequencing with Deadlines + Bellman-Ford
/* Experiment 12, Part A: Min-Max by divide and conquer (pairwise method) */
#include <stdio.h>
int main(void) {
int a[] = {100, 11, 445, 1, 330, 3000};
int n = 6, cmp = 0, mn, mx;
printf("Array = {100, 11, 445, 1, 330, 3000}, n = 6\n\n");
/* first pair seeds mn and mx */
cmp++;
if (a[0] < a[1]) { mn = a[0]; mx = a[1]; }
else { mn = a[1]; mx = a[0]; }
printf("Pair (%d, %d): local min = %d, local max = %d\n", a[0], a[1], mn, mx);
/* remaining pairs: 1 comparison inside pair, 2 against running mn/mx */
for (int i = 2; i < n; i += 2) {
int lmn, lmx;
cmp++;
if (a[i] < a[i + 1]) { lmn = a[i]; lmx = a[i + 1]; }
else { lmn = a[i + 1]; lmx = a[i]; }
printf("Pair (%d, %d): local min = %d, local max = %d\n", a[i], a[i + 1], lmn, lmx);
cmp++; if (lmn < mn) mn = lmn;
cmp++; if (lmx > mx) mx = lmx;
}
printf("\nMinimum = %d\nMaximum = %d\n", mn, mx);
printf("Comparisons used = %d (3n/2 - 2 = %d)\n", cmp, 3 * n / 2 - 2);
return 0;
}
/* Experiment 12, Part B: Job Sequencing with Deadlines (greedy) */
#include <stdio.h>
typedef struct { char id; int deadline, profit; } Job;
int main(void) {
Job jobs[] = {
{'a', 2, 100},
{'b', 1, 19},
{'c', 2, 27},
{'d', 1, 25},
{'e', 3, 15}
};
int n = 5, maxd = 3;
/* sort jobs by profit, descending */
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (jobs[j].profit < jobs[j + 1].profit) {
Job t = jobs[j]; jobs[j] = jobs[j + 1]; jobs[j + 1] = t;
}
printf("Jobs sorted by profit (id, deadline, profit):\n ");
for (int i = 0; i < n; i++)
printf("%c(%d,%d) ", jobs[i].id, jobs[i].deadline, jobs[i].profit);
printf("\n\n");
char slot[4] = {0, 0, 0, 0}; /* slots 1..3, 0 = free */
int total = 0;
for (int i = 0; i < n; i++) {
int s, limit = jobs[i].deadline < maxd ? jobs[i].deadline : maxd;
for (s = limit; s >= 1 && slot[s] != 0; s--)
; /* latest free slot before the deadline */
if (s >= 1) {
slot[s] = jobs[i].id;
total += jobs[i].profit;
printf(" Job %c: profit %d, deadline %d -> placed in slot %d\n",
jobs[i].id, jobs[i].profit, jobs[i].deadline, s);
} else {
printf(" Job %c: profit %d, deadline %d -> no free slot, skipped\n",
jobs[i].id, jobs[i].profit, jobs[i].deadline);
}
}
printf("\nFinal schedule: ");
for (int s = 1; s <= maxd; s++)
printf("[slot %d: job %c] ", s, slot[s] ? slot[s] : '-');
printf("\nTotal profit = %d\n", total);
return 0;
}
/* Experiment 12, Part C: Bellman-Ford shortest paths (handles negative weights) */
#include <stdio.h>
#define V 5
#define E 8
#define INF 1000000
int main(void) {
/* directed edges (CLRS classic example): 0->1:-1, 0->2:4, 1->2:3,
1->3:2, 1->4:2, 3->2:5, 3->1:1, 4->3:-3 */
int U[E] = {0, 0, 1, 1, 1, 3, 3, 4};
int Vc[E] = {1, 2, 2, 3, 4, 2, 1, 3};
int Wt[E] = {-1, 4, 3, 2, 2, 5, 1, -3};
int dist[V];
for (int i = 0; i < V; i++) dist[i] = INF;
dist[0] = 0; /* source */
printf("Source vertex = 0\n");
for (int pass = 1; pass <= V - 1; pass++) {
for (int e = 0; e < E; e++) {
int u = U[e], v = Vc[e], w = Wt[e];
if (dist[u] != INF && dist[u] + w < dist[v])
dist[v] = dist[u] + w; /* relax */
}
printf("After pass %d: [ ", pass);
for (int i = 0; i < V; i++) printf("%d ", dist[i]);
printf("]\n");
}
/* one more sweep: any relaxation now means a negative cycle */
int negcycle = 0;
for (int e = 0; e < E; e++)
if (dist[U[e]] != INF && dist[U[e]] + Wt[e] < dist[Vc[e]])
negcycle = 1;
printf(negcycle ? "Negative-weight cycle detected!\n"
: "No negative-weight cycle reachable from source.\n");
printf("Shortest distances from 0: ");
for (int i = 0; i < V; i++) printf("d[%d]=%d ", i, dist[i]);
printf("\n");
return 0;
}
AOA Practical Exam — Analysis of Algorithms — Practical Examination (teacher's list)
Turbo C versions — one standalone program per experiment, exactly the 10 on the teacher's practical list. Each includes <conio.h> and ends with getch(). No combined programs: each card is one experiment, ready for its own statement.
Exp 1 Selection Sort
/* Selection Sort (Turbo C) */
#include <stdio.h>
#include <conio.h>
int main(void) {
int n, i, j, min, temp;
int a[100];
printf("Enter number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid size.\n");
return 1;
}
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min]) min = j;
temp = a[i]; a[i] = a[min]; a[min] = temp;
}
printf("Sorted array: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
getch();
return 0;
}
Exp 2 Insertion Sort
/* Insertion Sort (Turbo C) */
#include <stdio.h>
#include <conio.h>
int main(void) {
int n, i, j, key;
int a[100];
printf("Enter number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid size.\n");
return 1;
}
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
for (i = 1; i < n; i++) {
key = a[i];
j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
printf("Sorted array: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
getch();
return 0;
}
Exp 3 Quick Sort
/* Quick Sort (Turbo C, Lomuto partition) */
#include <stdio.h>
#include <conio.h>
void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }
int partition(int a[], int low, int high) {
int pivot = a[high], i = low - 1, j;
for (j = low; j < high; j++) {
if (a[j] <= pivot) {
i++;
swap(&a[i], &a[j]);
}
}
swap(&a[i + 1], &a[high]);
return i + 1;
}
void quickSort(int a[], int low, int high) {
int p;
if (low < high) {
p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
int main(void) {
int n, i;
int a[100];
printf("Enter number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid size.\n");
return 1;
}
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
quickSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
getch();
return 0;
}
Exp 4 Binary Search
/* Binary Search (Turbo C, array must be sorted in ascending order) */
#include <stdio.h>
#include <conio.h>
int main(void) {
int n, i, key, low, high, mid, found = -1;
int a[100];
printf("Enter number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid size.\n");
return 1;
}
printf("Enter %d elements in sorted order: ", n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
printf("Enter element to search: ");
scanf("%d", &key);
low = 0; high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) { found = mid; break; }
else if (a[mid] < key) low = mid + 1;
else high = mid - 1;
}
if (found == -1) printf("Element %d not found.\n", key);
else printf("Element %d found at index %d.\n", key, found);
getch();
return 0;
}
Exp 5 Fractional Knapsack Problem
/* Fractional Knapsack Problem, Greedy (Turbo C) */
#include <stdio.h>
#include <conio.h>
typedef struct {
float profit, weight, ratio;
} Item;
int main(void) {
int n, i, j;
float capacity, total = 0.0f;
Item a[100], t;
printf("Enter number of items: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid count.\n");
return 1;
}
for (i = 0; i < n; i++) {
printf("Enter profit and weight of item %d: ", i + 1);
scanf("%f %f", &a[i].profit, &a[i].weight);
a[i].ratio = a[i].profit / a[i].weight;
}
printf("Enter knapsack capacity: ");
scanf("%f", &capacity);
/* sort by profit/weight ratio, descending */
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (a[j].ratio < a[j + 1].ratio) {
t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
for (i = 0; i < n && capacity > 0; i++) {
if (a[i].weight <= capacity) {
total += a[i].profit;
capacity -= a[i].weight;
printf("Taken fully: profit %.2f\n", a[i].profit);
} else {
total += a[i].ratio * capacity;
printf("Taken fraction %.2f of item (profit %.2f, weight %.2f)\n",
capacity / a[i].weight, a[i].profit, a[i].weight);
capacity = 0;
}
}
printf("Maximum profit: %.2f\n", total);
getch();
return 0;
}
Exp 6 Kruskal's Algorithm
/* Kruskal's Algorithm, Minimum Spanning Tree (Turbo C) */
#include <stdio.h>
#include <conio.h>
typedef struct {
int u, v, w;
} Edge;
int parent[100];
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
void unite(int x, int y) { parent[find(x)] = find(y); }
int main(void) {
int n, e, i, j, count = 0, cost = 0;
Edge a[500], t;
printf("Enter number of vertices and edges: ");
if (scanf("%d %d", &n, &e) != 2 || n <= 0 || n > 100 || e <= 0 || e > 500) {
printf("Invalid input.\n");
return 1;
}
printf("Enter edges as u v weight (vertices 0 to %d):\n", n - 1);
for (i = 0; i < e; i++) scanf("%d %d %d", &a[i].u, &a[i].v, &a[i].w);
for (i = 0; i < n; i++) parent[i] = i;
/* sort edges by weight, ascending */
for (i = 0; i < e - 1; i++)
for (j = 0; j < e - i - 1; j++)
if (a[j].w > a[j + 1].w) {
t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
printf("Edges in MST:\n");
for (i = 0; i < e && count < n - 1; i++) {
if (find(a[i].u) != find(a[i].v)) {
unite(a[i].u, a[i].v);
printf("%d - %d : %d\n", a[i].u, a[i].v, a[i].w);
cost += a[i].w;
count++;
}
}
printf("Total cost of MST: %d\n", cost);
getch();
return 0;
}
Exp 7 Prim's Algorithm
/* Prim's Algorithm, Minimum Spanning Tree, adjacency matrix (Turbo C) */
#include <stdio.h>
#include <conio.h>
#define INF 9999
int main(void) {
int n, i, j, count = 0, cost = 0;
int g[100][100], key[100], inMST[100], par[100];
printf("Enter number of vertices: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid input.\n");
return 1;
}
printf("Enter adjacency matrix (%d x %d, 0 = no edge, except diagonal):\n", n, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
scanf("%d", &g[i][j]);
if (i != j && g[i][j] == 0) g[i][j] = INF;
}
for (i = 0; i < n; i++) {
key[i] = INF; inMST[i] = 0; par[i] = -1;
}
key[0] = 0;
printf("Edges in MST:\n");
for (count = 0; count < n; count++) {
int u = -1, min = INF;
for (i = 0; i < n; i++)
if (!inMST[i] && key[i] < min) { min = key[i]; u = i; }
if (u == -1) break;
inMST[u] = 1;
if (par[u] != -1) {
printf("%d - %d : %d\n", par[u], u, g[par[u]][u]);
cost += g[par[u]][u];
}
for (i = 0; i < n; i++)
if (!inMST[i] && g[u][i] < key[i]) {
key[i] = g[u][i];
par[i] = u;
}
}
printf("Total cost of MST: %d\n", cost);
getch();
return 0;
}
Exp 8 0/1 Knapsack Problem
/* 0/1 Knapsack Problem, Dynamic Programming (Turbo C) */
/* Limits kept small on purpose: Turbo C has a 64KB data segment, */
/* so the DP table is 21 x 201 instead of 101 x 1001. */
#include <stdio.h>
#include <conio.h>
int max(int x, int y) { return x > y ? x : y; }
int main(void) {
int n, W, i, w;
int profit[100], weight[100];
static int dp[21][201];
printf("Enter number of items and knapsack capacity: ");
if (scanf("%d %d", &n, &W) != 2 || n <= 0 || n > 20 || W < 0 || W > 200) {
printf("Invalid input (max 20 items, capacity 200).\n");
return 1;
}
for (i = 0; i < n; i++) {
printf("Enter profit and weight of item %d: ", i + 1);
scanf("%d %d", &profit[i], &weight[i]);
}
for (i = 0; i <= n; i++)
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0) dp[i][w] = 0;
else if (weight[i - 1] <= w)
dp[i][w] = max(profit[i - 1] + dp[i - 1][w - weight[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
printf("Maximum profit: %d\n", dp[n][W]);
printf("Items selected: ");
w = W;
for (i = n; i > 0; i--) {
if (dp[i][w] != dp[i - 1][w]) {
printf("%d ", i);
w -= weight[i - 1];
}
}
printf("\n");
getch();
return 0;
}
Exp 9 Breadth-First Search (BFS)
/* Breadth-First Search, BFS, adjacency matrix (Turbo C) */
#include <stdio.h>
#include <conio.h>
int main(void) {
int n, i, j, src, front = 0, rear = 0;
int g[100][100], visited[100] = {0}, q[100];
printf("Enter number of vertices: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid input.\n");
return 1;
}
printf("Enter adjacency matrix (%d x %d):\n", n, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) scanf("%d", &g[i][j]);
printf("Enter source vertex (0 to %d): ", n - 1);
scanf("%d", &src);
visited[src] = 1;
q[rear++] = src;
printf("BFS order: ");
while (front < rear) {
int u = q[front++];
printf("%d ", u);
for (j = 0; j < n; j++)
if (g[u][j] && !visited[j]) {
visited[j] = 1;
q[rear++] = j;
}
}
printf("\n");
getch();
return 0;
}
Exp 10 Depth-First Search (DFS)
/* Depth-First Search, DFS, adjacency matrix, recursive (Turbo C) */
#include <stdio.h>
#include <conio.h>
int n, g[100][100], visited[100];
void dfs(int u) {
int j;
visited[u] = 1;
printf("%d ", u);
for (j = 0; j < n; j++)
if (g[u][j] && !visited[j]) dfs(j);
}
int main(void) {
int i, j, src;
printf("Enter number of vertices: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Invalid input.\n");
return 1;
}
printf("Enter adjacency matrix (%d x %d):\n", n, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
scanf("%d", &g[i][j]);
visited[i] = 0;
}
printf("Enter source vertex (0 to %d): ", n - 1);
scanf("%d", &src);
printf("DFS order: ");
dfs(src);
printf("\n");
getch();
return 0;
}
FSJP Lab — Full Stack Java Programming
Written from the syllabus list. Servlet/JSP code uses javax.servlet (Tomcat 9 style); on Tomcat 10 change javax to jakarta.
Exp 1 Programs on classes and objects
class Student {
int rollNo;
String name;
double marks;
Student(int r, String n, double m) {
rollNo = r;
name = n;
marks = m;
}
void display() {
System.out.println("Roll No : " + rollNo);
System.out.println("Name : " + name);
System.out.println("Marks : " + marks);
}
}
public class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student(14, "Kalpesh Patil", 88.5);
Student s2 = new Student(13, "Mukta Patange", 91.0);
s1.display();
System.out.println();
s2.display();
}
}
Exp 2 Programs on method and constructor overloading
class Calculator {
// Constructor overloading
Calculator() {
System.out.println("Default constructor called");
}
Calculator(int a) {
System.out.println("One-arg constructor, a = " + a);
}
Calculator(int a, int b) {
System.out.println("Two-arg constructor, sum = " + (a + b));
}
// Method overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class OverloadingDemo {
public static void main(String[] args) {
Calculator c1 = new Calculator();
Calculator c2 = new Calculator(10);
Calculator c3 = new Calculator(10, 20);
System.out.println("add(5, 7) = " + c1.add(5, 7));
System.out.println("add(5.5, 2.5) = " + c1.add(5.5, 2.5));
System.out.println("add(1, 2, 3) = " + c1.add(1, 2, 3));
}
}
Exp 3 Programs on various types of inheritance and Exception handling
// Single inheritance
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
// Multilevel inheritance
class Puppy extends Dog {
void weep() {
System.out.println("Puppy weeps");
}
}
// Hierarchical inheritance
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
// Multiple inheritance through interface
interface Flyable {
void fly();
}
class Bird extends Animal implements Flyable {
public void fly() {
System.out.println("Bird flies");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // from Animal
p.bark(); // from Dog
p.weep(); // own method
Cat c = new Cat();
c.eat();
c.meow();
Bird b = new Bird();
b.eat();
b.fly();
}
}
// User-defined exception
class AgeException extends Exception {
AgeException(String msg) {
super(msg);
}
}
public class ExceptionDemo {
static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or above");
}
System.out.println("Age valid: " + age);
}
public static void main(String[] args) {
// Multiple catch blocks + finally
try {
int a = 10 / 0;
System.out.println(a);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Finally block always executes");
}
// throw + throws + custom exception
try {
checkAge(16);
} catch (AgeException e) {
System.out.println("Caught AgeException: " + e.getMessage());
}
try {
checkAge(21);
} catch (AgeException e) {
System.out.println("Caught AgeException: " + e.getMessage());
}
}
}
Exp 4 Program on Implementing Generic and HTTP servlet
import javax.servlet.*;
import java.io.*;
public class GenericServletDemo extends GenericServlet {
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><body>");
out.println("<h2>Hello from GenericServlet!</h2>");
out.println("<p>This servlet handles any protocol request.</p>");
out.println("</body></html>");
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HttpServletDemo extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><body>");
out.println("<h2>Hello from HttpServlet (GET)!</h2>");
out.println("<form method='post'>");
out.println("Name: <input type='text' name='username'>");
out.println("<input type='submit' value='Submit'>");
out.println("</form>");
out.println("</body></html>");
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("username");
out.println("<html><body>");
out.println("<h2>Welcome, " + name + " (POST handled)</h2>");
out.println("</body></html>");
}
}
<web-app>
<servlet>
<servlet-name>generic</servlet-name>
<servlet-class>GenericServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>generic</servlet-name>
<url-pattern>/generic</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>http</servlet-name>
<servlet-class>HttpServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>http</servlet-name>
<url-pattern>/http</url-pattern>
</servlet-mapping>
</web-app>
Exp 5 Design a login webpage in JSP that makes validation through Database using JDBC and call the servlet for various operations
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head><title>Login</title></head>
<body>
<h2>Login</h2>
<% String err = (String) request.getAttribute("error");
if (err != null) { %>
<p style="color:red;"><%= err %></p>
<% } %>
<form action="login" method="post">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String user = req.getParameter("username");
String pass = req.getParameter("password");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM users WHERE username = ? AND password = ?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// Valid user: create session and go to welcome page
HttpSession session = req.getSession();
session.setAttribute("user", user);
res.sendRedirect("welcome.jsp");
} else {
req.setAttribute("error", "Invalid username or password");
req.getRequestDispatcher("login.jsp").forward(req, res);
}
con.close();
} catch (Exception e) {
throw new ServletException(e);
}
}
}
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Exp 6 Program on Implicit and Explicit objects in JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%! int visitCount = 0; %> <%-- declaration: explicit member --%>
<html>
<head><title>JSP Implicit Objects</title></head>
<body>
<h2>JSP Implicit Objects</h2>
<%
// request (implicit): data sent by the client
String name = request.getParameter("name");
if (name == null) name = "Guest";
// session (implicit): stored across requests
Integer count = (Integer) session.getAttribute("count");
if (count == null) count = 0;
session.setAttribute("count", count + 1);
// application (implicit): shared by all users
application.setAttribute("siteName", "FSJP Lab");
visitCount++; // explicit declaration variable
%>
<p>Hello, <%= name %>! (expression: explicit output)</p>
<p>Your session visits: <%= session.getAttribute("count") %></p>
<p>Application name: <%= application.getAttribute("siteName") %></p>
<p>Server info (config implicit object): <%= config.getServletName() %></p>
<p>Total page visits (declaration variable): <%= visitCount %></p>
<% out.println("<p>Printed with the implicit out object.</p>"); %>
</body>
</html>
Exp 7 Program to create a website using HTML CSS and JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Website</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
<nav>
<a href="#" onclick="showSection('home')">Home</a>
<a href="#" onclick="showSection('about')">About</a>
<a href="#" onclick="showSection('contact')">Contact</a>
</nav>
</header>
<section id="home">
<h2>Home</h2>
<p>This is a simple website built with HTML, CSS and JavaScript.</p>
<button onclick="changeMessage()">Click Me</button>
<p id="message"></p>
</section>
<section id="about" style="display:none;">
<h2>About</h2>
<p>This page demonstrates DOM manipulation with JavaScript.</p>
</section>
<section id="contact" style="display:none;">
<h2>Contact</h2>
<form onsubmit="return validateForm()">
<input type="text" id="cname" placeholder="Your name">
<input type="submit" value="Send">
</form>
</section>
<script src="script.js"></script>
</body>
</html>
body {
font-family: Arial, sans-serif;
margin: 0;
background: #f4f4f4;
color: #222;
}
header {
background: #1f3a5f;
color: #fff;
padding: 20px;
text-align: center;
}
nav a {
color: #fff;
margin: 0 12px;
text-decoration: none;
font-weight: bold;
}
section {
background: #fff;
max-width: 700px;
margin: 24px auto;
padding: 24px;
border-radius: 8px;
}
button, input[type="submit"] {
background: #1f3a5f;
color: #fff;
border: none;
padding: 10px 18px;
border-radius: 4px;
cursor: pointer;
}
function showSection(id) {
var sections = ["home", "about", "contact"];
for (var i = 0; i < sections.length; i++) {
document.getElementById(sections[i]).style.display =
(sections[i] === id) ? "block" : "none";
}
}
function changeMessage() {
document.getElementById("message").innerHTML =
"Button clicked! JavaScript updated this text.";
}
function validateForm() {
var name = document.getElementById("cname").value;
if (name === "") {
alert("Please enter your name");
return false;
}
alert("Thank you, " + name + "!");
return true;
}
Exp 8 Program using JavaScript to validate the email address entered by the user
<!DOCTYPE html>
<html>
<head><title>Email Validation</title>
<script>
function validateEmail() {
var email = document.getElementById("email").value;
var atPos = email.indexOf("@");
var dotPos = email.lastIndexOf(".");
if (atPos < 1 || dotPos < atPos + 2 || dotPos + 2 >= email.length) {
alert("Invalid email! It must contain '@' and '.' in valid positions.\nPlease re-enter your email.");
document.getElementById("email").focus();
document.getElementById("email").select();
return false;
}
alert("Valid email: " + email);
return true;
}
</script>
</head>
<body>
<h2>Email Validation</h2>
<form onsubmit="return validateEmail()">
Email: <input type="text" id="email" placeholder="example@domain.com">
<input type="submit" value="Validate">
</form>
</body>
</html>
Exp 9 Program based on Document Object Model to change the background color of the web page automatically after every 5 seconds
<!DOCTYPE html>
<html>
<head><title>DOM Background Color Changer</title>
<script>
var colors = ["#ffcccc", "#ccffcc", "#ccccff", "#ffffcc", "#ffccff"];
var index = 0;
function changeBackground() {
document.body.style.backgroundColor = colors[index];
document.getElementById("colorName").innerHTML =
"Current background: " + colors[index];
index = (index + 1) % colors.length;
}
// Change the background automatically every 5 seconds
window.onload = function () {
changeBackground();
setInterval(changeBackground, 5000);
};
</script>
</head>
<body>
<h2>DOM Background Color Changer</h2>
<p>The background color of this page changes automatically every 5 seconds.</p>
<p id="colorName"></p>
</body>
</html>
Exp 10 Program for making use of React Hooks that displays four buttons namely, "Red", "Blue", "Green", "Yellow"
import React, { useState } from "react";
function App() {
const [selectedColor, setSelectedColor] = useState("");
const colors = ["Red", "Blue", "Green", "Yellow"];
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h2>Select a Color</h2>
{colors.map((color) => (
<button
key={color}
onClick={() => setSelectedColor(color)}
style={{ margin: "8px", padding: "10px 20px" }}
>
{color}
</button>
))}
{selectedColor && (
<h3>You have selected {selectedColor} color.</h3>
)}
</div>
);
}
export default App;
Exp 11 Creating a Single Page website using the concepts in React like Hooks, Router, Props and States
import React from "react";
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import { Home, About } from "./Pages";
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> |{" "}
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home title="Welcome Home" />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
export default App;
import React, { useState, useEffect } from "react";
// Props: title is received from App.js
export function Home({ title }) {
const [count, setCount] = useState(0); // State + Hook
useEffect(() => {
document.title = "Count: " + count; // Effect Hook
}, [count]);
return (
<div>
<h2>{title}</h2>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
export function About() {
const [message] = useState("This is a Single Page Application.");
return (
<div>
<h2>About</h2>
<p>{message}</p>
</div>
);
}
Exp 12 Program to create a Monolithic Application using SpringBoot
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/")
public String home() {
return "Welcome to the Spring Boot Monolithic Application!";
}
@GetMapping("/hello")
public String hello() {
return "Hello from Spring Boot!";
}
}
server.port=8080
spring.application.name=demo
Exp 13 Program for Building RESTful APIs with spring boot
package com.example.demo;
public class Student {
private int id;
private String name;
public Student() {}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/api/students")
public class StudentRestController {
private List<Student> students = new ArrayList<>(Arrays.asList(
new Student(1, "Kalpesh"),
new Student(2, "Mukta")
));
// GET all students
@GetMapping
public List<Student> getAll() {
return students;
}
// GET one student by id
@GetMapping("/{id}")
public Student getById(@PathVariable int id) {
for (Student s : students) {
if (s.getId() == id) return s;
}
return null;
}
// POST: add a new student
@PostMapping
public Student add(@RequestBody Student s) {
students.add(s);
return s;
}
// PUT: update a student
@PutMapping("/{id}")
public Student update(@PathVariable int id, @RequestBody Student updated) {
for (Student s : students) {
if (s.getId() == id) {
s.setName(updated.getName());
return s;
}
}
return null;
}
// DELETE a student
@DeleteMapping("/{id}")
public String delete(@PathVariable int id) {
students.removeIf(s -> s.getId() == id);
return "Deleted student with id " + id;
}
}