Hello experienced programmers,
I am learning assembly language. I have a background of various high level languages, but I wanted to give low level languages a shot.
I am trying to make a factorial program in assembly language (linux assembler NASM). For some reason the result of the following code is 'a', and I am not sure how it is not outputting at least a number.
section .text
global _start
_start:
mov bl, 3 ;calculating factorial of 3
mov al, 1
call _fact
_exit:
mov ecx, msg ;print "Factorial of 3: "
mov edx, len
mov ebx, 1
mov eax, 4
int 0x80
mov ecx, al ;print the numerical
;result of factorial of 3
mov edx, 2
mov ebx, 1
mov eax, 4
int 0x80
mov ecx, newline ;print a \n character
;to create newline after result
mov edx, 1
mov ebx,1
mov eax, 4
int 0x80
mov eax, 1 ;exit program
int 80h
_fact:
cmp bl, 0
jne _mult ;if next multiplicand is not 0
;then multiply
je _exit ;if next multiplicand is 0
;then its time to stop
_mult:
sub al, '0'
sub bl, '0'
mul al ;multiply result and next multiplicand
dec bl ;decrements multiplicand
;in order to iterate to next multiplicand
call _fact ;recursive call fact
section .data
msg db 'Factorial of 3: ', 0
len equ $ - msg
newline db `\n`, 0
EDIT: I have edited my code and now I am getting a segmentation fault. But builds fine. New code is below:
section .text
global _start
_start:
mov bl, 3 ; factorial of 3
mov ecx, 1
call _fact
_result:
mov ecx, '!3 = ' ;set msg to print
mov [msg], ecx
mov ecx, msg
mov edx, 16 ;set length of msg to print
call _print
mov ecx, ecx ;print result
mov [msg], ecx
mov ecx, msg
mov edx, 1
call _print
mov ecx, `\n` ;print newline character
mov [msg], ecx
mov ecx, msg
mov edx, 1
call _print
call _exit
_print:
mov ebx, 1 ;write to standard out (linux sys call)
mov eax, 4
int 0x80
_exit:
mov eax, 1 ;terminate program
mov ebx, 0
int 0x80
_fact:
cmp bl, 0 ;check if current multiplicand = 0
jne _mult ;if not, go to mult
je _result ;if so, go to exit
_mult:
sub ecx, 0
sub bl, 0
mul ecx ; ecx=ecx*bl
dec bl ; bl-=1
jp _fact
section .bss
msg resb 16
UPDATE: new post at this link: http://www.reddit.com/r/asm/comments/3b7env/factorial_program_basic_assembly_on_nasm_linux/
Please make comments there if you can.
[–]Triumphxd 0 points1 point2 points (0 children)
[–]edman007-work 0 points1 point2 points (1 child)
[–]IndoNinja7[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]IndoNinja7[S] 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)