Darshan P. answered 11/13/24
A highly motivated and computer science engineer with a strong fo
; Fibonacci Program in PEP/9 Assembly
.ORIG 0x1000 ; Program starting address
; Global message "Which fibonacci number? "
PROMPT .STRING "Which fibonacci number? "
NEWLINE .STRING "\n"
; Equates for stack access and function call
.EQU SPREG, 0xFFFC ; Stack pointer register
.EQU RETADDR, 0xFFFA ; Return address register
.EQU FIB_PARAM, 0xFFFE ; Parameter for fib function
; Main program
MAIN:
; Print "Which fibonacci number? "
LDX #PROMPT
JSR PRINT_STRING
; Read user input (integer)
JSR READ_INT
; Store user input (Fibonacci number) in memory
STX FIB_PARAM
; Call fib function
LDX FIB_PARAM
JSR FIB
; Print result (Fibonacci number)
JSR PRINT_INT
; Print newline
LDX #NEWLINE
JSR PRINT_STRING
; Exit program
JSR HALT
; Function to print a string
PRINT_STRING:
LDA ,X ; Load the byte at address X
BEQ DONE_PRINT ; If it's zero (end of string), exit
OUT ; Output the character
INX ; Move to next character
BRA PRINT_STRING
DONE_PRINT:
RTS ; Return from subroutine
; Function to read an integer
READ_INT:
IN ; Read an integer from input (PEP/9 I/O)
STX FIB_PARAM ; Store the integer in FIB_PARAM
RTS
; Function to print an integer
PRINT_INT:
LDA FIB_PARAM ; Load the number to be printed
OUT ; Output the integer
RTS
; Fibonacci function (recursive)
FIB:
LDX FIB_PARAM ; Load the input parameter (n)
CPX #0 ; Compare n with 0
BEQ FIB_ZERO ; If n == 0, return 0
CPX #2 ; Compare n with 2
BLS FIB_TWO ; If n <= 2, return 1
; n > 2: Recursive case
TSX ; Push return address onto stack
STX RETADDR ; Store the return address
; fib(n-1)
LDX FIB_PARAM ; Load n
SUB #1 ; n-1
STX FIB_PARAM ; Update parameter to n-1
JSR FIB ; Recursive call fib(n-1)
LDX RETADDR ; Get return address
TSX ; Push return address onto stack
STX RETADDR ; Store the return address
; fib(n-2)
LDX FIB_PARAM ; Load n
SUB #2 ; n-2
STX FIB_PARAM ; Update parameter to n-2
JSR FIB ; Recursive call fib(n-2)
LDX RETADDR ; Get return address
ADD RETADDR ; Add fib(n-1) + fib(n-2)
RTS
FIB_ZERO:
LDA #0 ; Return 0 for fib(0)
RTS
FIB_TWO:
LDA #1 ; Return 1 for fib(1) or fib(2)
RTS
; End of program
HALT:
.END