Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
1.2k views
in Computer by (69.2k points)

How is recursion handled internally. Explain with the help of a suitable example. 

1 Answer

+1 vote
by (69.7k points)
selected by
 
Best answer

Internally, each recursive call to a function needs to store the intermediate values of the parameters and local variables in a run time stack. The general algorithm for any recursive procedure contains the following steps: 

1. Save the parameters, local variables and return address. 

2. If the base criterion has been reached, then perform the final computation and go to step 3, otherwise perform the partial computation and go to step 1 with reduced parameter values (initiate a recursive call).

3. Restore the most recently saved parameters, local variables and return address. Go to this return address.

All parameters is accessed by their positions relative to the top of the stack. Whenever a subroutine is started the variables are pushed onto the stack and whenever it completes execution, the variables are popped off the stack. For ex. consider the factorial function. 

Factorial (int n)

int x;

if n = 0 

return (1);

x = n - 1;

return (n * factorial (x));

}

let the initial call is Y = factorial (4) 

At first time, 4 locations are put in the run time stack

And on each subsequent calls the intermediate values of all these variables are pushed till the condition reaches where n=0. and then the contents are popped one by one and is returned to the place of the precious call. This continues until the control is back to the first call.  

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...