Assembly - Recursion

Prahlad Godara ------ From DOOSEEP

Content

Recursion Definition, Syntax and Examples

In assembly language, when any code block or instruction group has to be used repeatedly, then recursion is used. Recursion occurs when a function or instruction group repeatedly calls itself, directly or indirectly.

There are two types of recycling: direct and indirect.

  1. direct recursion - In direct recursion, the process calls itself.
  2. indirect recursion - in indirect recursion, the first process calls the second process, which in turn calls the first process.

Recursion can be seen in many mathematical algorithms. For example, consider the case of computing the factorial of a number. The factorization equation of a number is given by

 Fact (n) = n * fact (n-1) for n > 0

Recursion Exampal

For example: The factorial of 5 is the factorial of 1 x 2 x 3 x 4 x 5 = 5 x 4 and this can be a good example to show a recursive process. Every recursive algorithm must have a termination condition, that is, the recursive calling of the program must stop when a condition is met. In the case of the factorial algorithm, the final condition is reached when n is 0.


Example The following program shows how to implement factorial n in assembly language. To keep the program simple, we'll calculate the factorial of 3.
 section	.text
  global _start         ;must be declared for using gcc
 
_start:                  ;tell linker entry point

  mov bx, 3             ;for calculating factorial 3
  call  proc_fact
  add   ax, 30h
  mov  [fact], ax
   
  mov	  edx,len        ;message length
  mov	  ecx,msg        ;message to write
  mov	  ebx,1          ;file descriptor (stdout)
  mov	  eax,4          ;system call number (sys_write)
  int	  0x80           ;call kernel

  mov   edx,1            ;message length
  mov	  ecx,fact       ;message to write
  mov	  ebx,1          ;file descriptor (stdout)
  mov	  eax,4          ;system call number (sys_write)
  int	  0x80           ;call kernel
   
  mov	  eax,1          ;system call number (sys_exit)
  int	  0x80           ;call kernel
 
proc_fact:
  cmp   bl, 1
  jg    do_calculation
  mov   ax, 1
  ret
 
do_calculation:
  dec   bl
  call  proc_fact
  inc   bl
  mul   bl        ;ax = al * bl
  ret

section	.data
msg db 'Factorial 3 is:',0xa	
len equ $ - msg			

section .bss
fact resb 1

result −

 Factorial 3 is: 6 

Tags- Nasm Assembly language Arrays in hindi. This blogcreates content similar to stackoverflow geeks for geeks tutorialspoint w3schools and dooseep,Recursion in ansm assembly