Factorial of a number
A program that finds the factorial of a number. The factorial of a number n (written n!) is the product of all natural numbers from 1 to n inclusive.
Program source code
title .model small .stack 100h data segment public askUser db "Enter a number to find its factorial: \0" fmtoutput db "\nThe factorial of this number is: %d\0" fmtinput db "%d" number dw ? factorial dw 1 data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure lea ax, ds:[askUser] ; Load the address of the askUser variable into ax call WriteString ; Call the WriteString procedure lea ax, ds:[number] ; Load the address of the number variable into the ax register push ax ; 2nd: save the ax register value on the stack lea ax, ds:[fmtinput] ; 1st: load the address of the fmtinput format string into ax call ScanFormatString ; Call the ScanFormatString procedure add sp, 2 ; Align the stack mov cx, 1 ; Set the counter to 1 MainLoop: mov ax, factorial ; Copy the value of the factorial variable into the ax register mul cx ; Multiply the value in the ax register by the value in cx mov factorial, ax ; Save the result in the factorial variable inc cx ; Increment the counter register value by 1 cmp cx, number ; Compare the value of cx with the value in the number variable jbe MainLoop ; If the value is below or equal to userInput, then jump to MainLoop push factorial ; 2nd: Save the factorial variable value on the stack lea ax, ds:[fmtoutput] ; 1st: Load the address of the fmtoutput format string into the ax register call PrintFormatString ; Call the PrintFormatString procedure add sp, 2 ; Align the stack xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
Enter a number to find its factorial: 5
The factorial of this number is: 120
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".