Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Program to calculate Factorial using a subroutine

section .data
prompt db 'Enter a number: ', 0
result_msg db 'The factorial is: ', 0
format db "%d", 0

section .bss
num resd 1
factorial resd 1

section .text
global main
extern printf, scanf

main:
; Prompt for the number
mov eax, 0
lea edi, [prompt]
call printf

; Read the number


lea edi, [format]
lea esi, [num]
call scanf
; Call subroutine to calculate factorial
mov eax, [num]
call calc_factorial

; Print the result


mov eax, 0
lea edi, [result_msg]
call printf
mov eax, [factorial]
lea edi, [format]
call printf

; Exit the program


mov eax, 0
ret

calc_factorial:
; Input: EAX = number
; Output: EAX = factorial
; Modifies: EAX, EBX, ECX

mov ebx, eax ; Copy number to ebx


mov ecx, 1 ; Initialize factorial to 1

.loop:
mul ecx ; Multiply factorial by current number
inc ecx ; Increment current number
cmp ecx, ebx ; Compare current number with input number
jle .loop ; Loop until current number <= input number

mov eax, ecx ; Store factorial in eax


ret

You might also like