Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

Computer Organization &

Assembly Language
Recursion
Recursion
 A process is said to be recursive if it is defined in terms of
itself.
 A recursive procedure is a procedure that calls itself.
• Functions can be written in two ways:
• Iterative
• keep repeating until a task is done
• e.g., loop counter reaches limit
• Recursive
• Solve a large problem by breaking it up into
smaller and smaller pieces until you can solve it;
combine the results.

2
Recursive Function Properties
• A recursive function must have two properties:
• There must be a certain (base) criteria for which function
doesn’t call itself.
• Each time function does call itself (directly or indirectly),
it must closer to the base criteria.

3
Example (Factorial)

  Non recursive definition of factorial:

• Recursive definition of factorial:

4
Passing Parameters on the stack
org 100h ADD_WORDS PROC
.DATA PUSH BP
WORD1 DW 2 MOV BP,SP
WORD2 DW 5 MOV AX,[BP+6] ;AX GETS
.CODE WORD1
MAIN PROC ADD AX,[BP+4] ;AX HAS SUM
PUSH WORD1 POP BP
PUSH WORD2 RET 4
CALL ADD_WORDS ADD_WORDS ENDP
RET
MAIN ENDP ret

5
Example (Factorial)
PROCEDURE FACTORIAL
IF N = 1
THEN
RESULT=1
ELSE
CALL FACTORIAL
RESULT = N * RESULT
END_IF
RETURN

6
Factorial Code
org 100h MOV AX, 1
.CODE JMP RETURN
MAIN PROC END_IF:
MOV AX,3 MOV BX, [BP+4]
PUSH AX DEC BX
CALL FACTORIAL PUSH BX
RET CALL FACTORIAL
MAIN ENDP MUL [BP+4]
FACTORIAL PROC RETURN:
PUSH BP POP BP
MOV BP, SP RET 2
CMP [BP+4], 1 FACTORIAL ENDP
JG END_IF
7
Fibonacci Sequence
• Following is the Fibonacci Series
• 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89………………..
• Fibonacci series start with 1 and 1 as first two
numbers and any subsequent number is
sum of previous two numbers
• 2 = 1+1
• 3 = 2+1
• 5 = 3+2
• 8 = 5+3
• 21 = 13+8

8
Nth Fibonacci Number
• Base Case : if n = 1 or n=0 then Fn = 1
• Recursive Call: if n > 1 then Fn = Fn-2 + Fn-1

int fib(int n)
{
if ( n == 0 )
return 1;
else if ( n == 1 )
return 1;
else
return (fib(n-1) + fib (n-2) );
}

9
Fibonacci Sequence Code
org 100h CALL FIB
.CODE PUSH CX
MAIN PROC MOV CX, DX
MOV AX, 3 DEC AX
MOV DX, 0 CALL FIB
MOV CX, 0 ADD DX, CX
CALL FIB POP CX
RET POP AX
MAIN ENDP RET
FIB PROC RET1:
PUSH AX MOV DX, 1
CMP AX,1 POP AX
JLE RET1 RET
DEC AX FIB ENDP

10
Chapter Reading
• Chapter # 17

11

You might also like