CSC231 Fibonacci with Loops

From dftwiki3
Revision as of 09:07, 10 October 2012 by Thiebaut (talk | contribs) (Example 2)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 09:01, 10 October 2012 (EDT)


Example 1


;;; fibWithLoop.asm
;;; D. T.
;;; a simple demo program computing a few Fibonacci terms
;;; using indirect addressing modes and loops.
;;; To compile and run
;;; nasm -f elf fibWithLoop.asm
;;; nasm -f elf asm_io.asm
;;; gcc -m32 -o fibWithLoop driver.c fibWithLoop.o asm_io.o
;;; ./fibWithLoop


             %include "asm_io.inc"

             ;; -------------------------
             ;; data segment
             ;; -------------------------
             section .data
Fib	     db     0,0,0,0,0,0

             ;; -------------------------
             ;; code area
             ;; -------------------------
             section .text
             global  asm_main
asm_main:       
	mov	ebx, Fib	; make ebx point to array
	mov	ecx, 5		; # of terms to compute
	mov	eax, 1		; first term as double word (for printing)
	mov	byte[ebx], al	; set 1st term
	call	print_int	; print it
	call	print_nl
	
	mov	byte[ebx+1], al	; set 2nd term
	call	print_int	; print it
	call	print_nl
	
	sub	ecx,2		; adjust counter 
	add	ebx,2		; and pointer. ebx points to
				; empty Fib
	
for:	add	al, byte[ebx-2]	; al<- fib(n-1)+fib(n-2)
	mov	byte[ebx], al	; store new term
	call	print_int	; print it
	call	print_nl
	
	inc	ebx		; point to new term
        loop	for		; loop back

        ;; return to C program
	
        ret


Example 2


;;; fibWithLoop2.asm
;;; D. T.
;;; a simple demo program computing a few Fibonacci terms
;;; using indirect addressing modes and loops
;;; To compile and run
;;;   nasm -f elf fibWithLoop2.asm
;;;   nasm -f elf asm_io.asm
;;;   gcc -m32 -o fibWithLoop2 driver.c fibWithLoop2.o asm_io.o
;;;   ./fibWithLoop2
	
	     %include "asm_io.inc"

             ;; -------------------------
             ;; data segment
             ;; -------------------------
             section .data
Fib	     db     0,0,0,0,0,0

             ;; -------------------------
             ;; code area
             ;; -------------------------
             section .text
             global  asm_main
asm_main:       
	mov	ebx, 0			; make ebx point to array
	mov	ecx, 5			; # of terms to compute
	mov	eax, 1			; first term as double word (for printing)
	mov	byte [Fib+ebx], al	; set 1st term
	call	print_int		; print it
	call	print_nl
	
	mov	byte [Fib+ebx+1], al	; set 2nd term
	call	print_int		; print it
	call	print_nl
	
	sub	ecx,2			; adjust counter 
	add	ebx,2			; and pointer. ebx points to
					; empty Fib
	
for:	add	al, byte [Fib+ebx-2]	; al<- fib(n-1)+fib(n-2)
	mov	byte [Fib+ebx], al	; store new term
	call	print_int		; print it
	call	print_nl
	
	inc	ebx			; point to new term
        loop	for			; loop back

        ;; return to C program
	
        ret



Output

[231a@grendel ~/handout]$ ./fibWithLoop2
1
1
2
3
5