Create a gist now

Instantly share code, notes, and snippets.

Embed
Trial at learning Assembly with NASM + GCC on Windows
global _main ; Define the global. _main on windows and _start on UNIX
extern _printf ; Import printf and scanf functions from C. Remove _ on UNIX
extern _scanf
section .data
; Messages in printf and scanf
pm db "Enter a number: ", 0
sf db "%ld", 0
em db "Error: factorial of negative number is not possible.", 0
rm db "The factorial of %ld is %ld", 0
section .bss
; long i, f
i resb 4
f resb 4
section .text
; The equivalent C code is as follows:
; ~~~
; long fact(long n)
; {
; return (n == 0) ? 1 : n * fact(n - 1);
; }
; ~~~
fact:
cmp dword ebx, 0 ; n == 0
je .yes
.no:
push ebx ; save ebx in stack
sub ebx, dword 1 ; sub 1 from ebx. (n - 1)
call fact ; call fact recursively
pop ebx ; get back the ebx from stack
imul eax, ebx ; eax *= ebx; eax == fact(n - 1)
ret
.yes:
mov eax, dword 1 ; store 1 in eax to return it
ret
; The main function, also known as the entry point.
_main:
push pm ; prompt the user
call _printf
add esp, 4
push i ; read the value into i
push sf
call _scanf
add esp, 8
; check for validity of the factorial value
cmp dword ebx, 0
jnl .no
.yes:
push em ; print error message and exit
call _printf
add esp, 4
ret
.no:
mov ebx, dword [i] ; call the fact function
call fact
mov dword [f], eax
push dword [f] ; print the result and exit
push dword [i]
push rm
call _printf
add esp, 12
ret
#include <stdio.h>
long fact(long n);
int main()
{
long i, f;
printf("Enter a number: ");
scanf("%ld", &i);
if (i < 0)
{
printf("Error: factorial of negative number is not possible.");
return 1;
}
f = fact(i);
printf("The factorial of %ld is %ld", i, f);
return 0;
}
long fact(long n)
{
return (n == 0) ? 1 : n * fact(n - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment