Download presentation
Presentation is loading. Please wait.
1
Microprocessor and Assembly Language
Lecture-15-Recursion Muhammad Hafeez Department of Computer Science GC University Lahore
2
Today’s Agenda Recursion Theory in Assembly
Implementation in 8086 Environment
3
Recursion A process is recursive if its defined in terms of itself
Main Characteristics of a recursive process The Main Problem is break down to simpler problem, each of these simpler problem are solved exactly the way, main problem is solved There must be an escape case One sub problem is solved, proceed to next step of solving main problem
4
Example: Factorial Non-recursive way
Factorial (N) = N x (N-1) x (N-2)x…x3x2x1 Recursive Way: Factorial (N) = N x Factorial (N-1)
5
Algorithm for Factorial:
PROCEDURE FACTORIAL (INPUT:N, OUTPUT: RESULT) IF N =1 THEN RESULT=1 ELSE CALL FACTORIAL(INPUT:N-1, OUTPUT:RESULT) RESULT = N X RESULT END_IF RETURN
6
Algorithm for Find Max in An Array:
If N = 1 then largest entry is A[1], else largest entry is either A[N] or largest of A[1] …A [N-1] PROCEDURE FIND_MAX(INPUT:N, OUPUT:MAX) IF N = 1 THEN MAX = A[1] ELSE CALL FIND_MAX(N-1,MAX) IF A[N] > MAX THEN MAX = A[N] MAX = MAX END_IF RETURN
7
Revision-Passing Parameters to Procedure on the Stack
Write a procedure that adds two words and return the result in AX Pass words to procedure using Stack
8
The Activation Record Each new call to a recursive procedure require the parameters and local variables to be reinitialized for that particular call When the call is completed the procedure resumes the previous call, on the point it left off. Hence, the procedure needs to ‘remember’ the point, the parameters and local values of the previous call, this is called ‘the activation record’
9
Example: Activation Record First Call Activation Record 2nd Call
10
Example: Activation Record First Call
Suppose, 3rd call is the escape case, result of this call is computed and stored in a register or memory location to be available to 2nd call and so on..
11
Implementation of Factorial using Recursion:
MODEL SMALL .STACK 100H .CODE MAIN PROC MOV AX,3 ;N = 3 PUSH AX ;N on stack CALL FACTORIAL ;AX has 3 factorial MOV AH,4CH INT 21H ;dos return MAIN ENDP
12
Implementation of Factorial using Recursion:
FACTORIAL PROC NEAR ; computes N factorial ; input: stack on entry - ret. addr.(top), N ; output: AX PUSH BP ;save BP MOV BP,SP ;BP pts to stacktop ;if CMP WORD PTR[BP+4],1 ;N = 1? JG END_IF ;no , N>1 ;then MOV AX,1 ;result = 1 JMP RETURN ;to to return END_IF: MOV CX,[BP+4] ;get N DEC CX ;N-1 PUSH CX ;save on stack CALL FACTORIAL ;recursive call MUL WORD PTR[BP+4] ;RESULT = N*RESULT RETURN: POP BP ;restore BP RET 2 ;return and discard N FACTORIAL ENDP END MAIN
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.