Question

Unrolling Recursion
The objective of this problem is to simulate recursion using stacks and loops. A synthetic linear recursive procedure for this problem is provided in Code Fragment 1. A recursive function such as the one described is intuitive and easily understandable. On calling myRecursion(input), the execution first checks for the stopping condition. If the stopping condition is not met, then operations inside the recursive call are performed. This can include operations on local variables. The operations inside the function can result in changes to the input. The recursive function is again called using the modified input.

public static int myRecursion(input)
{
   if (recursion stopping condition)
       return value;
   //perform some operations
   ...
   //modified input = make changes to input
   ...
   return myRecursion(modified input)
}
Programming languages internally execute recursion using stacks: To understand the call stack operations performed during execution, let us consider a call to myRecursion(input). Assuming that the recursion stopping criteria is satisfied at a recursive depth of 2, the recursion trace during execution is illustrated in Figure 1.
Figure 1
valuel myRecursion(input0) value mvRecursion( inpu myRecursion(input2) Figure 1

Before calling the first level recursion using input1, the current state of level 0 recursion is pushed onto a stack for future processing. Similarly, before calling the second level recursion using input2, the current state of level 1 recursion is pushed onto the stack for future processing. After execution of second level of recursion, when the stopping condition is satisfied, value is returned. Following which recursion at level 1 continues to execute using the returned value.
The depth of the recursion can sometimes exceed the allowed capacity resulting in "Stack Overflow Error". You can verify this by executing a recursive procedure to compute the sum of first n integers with n = 10000. Our goal in this problem to re-write recursive functions using stacks and while loops. The idea is to simulate the stacked recursive function call. In order to create the user defined stack, we need to first define a class whose object stores the current values of local variables used inside the recursion function (lines 5 through 8 in Code Fragment 1. We also need to store the stage of the current recursion if a recursive call can start more than one recursions (multiple recursions). Thus, we would need only one stack to perform even multiple recursions. A sample snapshot class for the myRecursion function is illustrated in Code Fragment 2.
You should create an object containing the current status values of local variables and push it to the stack before executing the deeper recursive function as discussed in the class. Implement the following problem first in the recursive fashion and then simulate the recursion using stacks and loops:

public class myRecursionSnapShot {
/**
define all local variables as private members
*/
private int stage;

public myRecursionSnapShot() {
}

public myRecursionSnapShot (local variables, int stage) {
//local variable assignments
this.stage = stage;
}
/**
public get functions to obtain the variable of variables
*/

/**
public get functions to obtain the variable of stage
*/

public int getStage() {
return stage;
}
/**
public get functions to assign the variable of variables
*/

/**
public get functions to assign the variable of stage
*/
public void setStage(int stage) {
this.stage = stage;
}
}

1. Sum of first n positive integers.
2. nth number in the Fibonacci series.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1.

public class MyClass {
  
public static int Sum_recursion(int n)
{   
//here is the stopping condition
if(n==0)
{
return n;
}
return n+ Sum_recursion(n-1); //performing changes adding every n and number less than n
  
}
public static void main(String args[]) {
// intializing n
int n=5;
System.out.println(Sum_recursion(n));// calling Function and printing the answer
  
}
}

Ml Result... CPU Time: 0.12 sec(s), Memory: 29728 ki lobyte 15

2.

public class Fibonacci {
  
public static int fib(int n)
{   
//here is the stopping condition
if(n==1 || n==0 )
{
return n;
}
return fib(n-1)+ fib(n-2); //performing changes
  
}
public static void main(String args[]) {
// intializing n
int n=10;
System.out.println(fib(n));// calling function and printing the answer
  
}
}

O Execute Save My Pr Result... CPU Time: 0.12 sec(s), Memory: 30092 kilobyte(s


Add a comment
Know the answer?
Add Answer to:
Unrolling Recursion The objective of this problem is to simulate recursion using stacks and loops...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • LANGUAGE IS C++ Lab Ch14 Recursion In this lab, you are provided with startup code which...

    LANGUAGE IS C++ Lab Ch14 Recursion In this lab, you are provided with startup code which has six working functions that use looping (for, while, or do loops) to repeat the same set of statements multiple times. You will create six equivalent functions that use recursion instead of looping. Although looping and recursion can be interchanged, for many problems, recursion is easier and more elegant. Like loops, recursion must ALWAYS contain a condition; otherwise, you have an infinite recursion (or...

  • C++ Using Recursion We are going to create a (looping) menu that accesses functions that use...

    C++ Using Recursion We are going to create a (looping) menu that accesses functions that use recursion. The function headers and a description will be provided. You are responsible for defining the functions. Ensure that they each contain a base case they reach that doesn’t have a recursive function call, otherwise it’s an infinite loop! Functions must be implemented with recursion. int Factorial(int arg) Returns arg! (4! Is 4 * 3 * 2 = 24) Base case is Factorial(1) returning...

  • Given an array-based stack of integers, sort it largest to smallest using recursion. Do NOT use...

    Given an array-based stack of integers, sort it largest to smallest using recursion. Do NOT use any loop constructs such as while, for and so on. Only use the following stack ADT functions in the recursion: IsEmpty Push Pop Top (note: doesn’t remove anything from the stack). Your program should read 10 integers into a stack from a file named input.txt (outputting them to the screen first) then implement the recursions. Use stacks only, no queues. The program should then...

  • This a lab for C++ using visual studio 2017 Lab 10 Total 50 points Stacks and...

    This a lab for C++ using visual studio 2017 Lab 10 Total 50 points Stacks and Queues - Part A (40 points) Finish the code for Lab10aStacksAndQueues.cpp . You will write code for the same function which will return true if the values of the elements of the vector that is passed to it are the same read both forwards and backwards. If they are not the same in both directions, it will return false. Don’t change anything in the...

  • help me answer the following questions please 1. Stack (LIFO) & its application 1. Stack overflow...

    help me answer the following questions please 1. Stack (LIFO) & its application 1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking Exercises: 1) Which of the following applications may use a stack? A. parentheses balancing program. B. Keeping track of local variables at run time. C. Syntax analyzer for a compiler. D. All of the above. 2) Consider the usual algorithm for determining whether a sequence of parentheses is balanced....

  • JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using...

    JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using recursion. The method signatures are included in the starter code below, with a more detailed explanation of what function the method should perform. You will be writing the following methods: stringClean() palindromeChecker() reverseString() totalWord() permutation() You will be using tools in the String class like .substring(), .charAt(), and .length() in all of these methods, so be careful with indices. If you get stuck, think...

  • Trying to solve the following problem based on the below program. It's from Chapter 2 in...

    Trying to solve the following problem based on the below program. It's from Chapter 2 in Computer Systems (Fourth Edition) by J. Stanley Warford Section 2.4 . The function sum in Figure 2.25 is called for the first time by the main program. From the second time on it is called by itself. "(a) How many times is it called altogether? (b) Draw a picture of the main program variables and the run-time stack just after the function is called...

  • Backtracking is a computing algorithm using stack to “remember” user-generated events when using a program. A...

    Backtracking is a computing algorithm using stack to “remember” user-generated events when using a program. A user event may be “pressing the Enter key on keyboard” or “clicking a mouse button”. Stack is a data structure with the Last-In-First-Out property (LIFO). If we push the aforesaid user events into a stack, a computer program using that data structure can “rewind” user events by popping them out of stack one at a time. This backtracking feature is available as Edit ->...

  • C++ PROGRAM ONLY! For this lab you need to write a program that will read in...

    C++ PROGRAM ONLY! For this lab you need to write a program that will read in two values from a user and output the greatest common divisor (using a recursive implementation of the Euclidean algorithm) to a file. In Lab #3, you implemented this program using an iterative method. Greatest Common Divisor In mathematics, the greatest common divisor (GCD) of two or more integers (when at least one of of them is zero then the larger value is the GCD....

  • Maze Solving with Stacks Problem Statement Consider a maze made up of rectangular array of squares,...

    Maze Solving with Stacks Problem Statement Consider a maze made up of rectangular array of squares, such as the following one: X X X X X X X X X X X X X           X            X X X X    X X X           X               X     X X X     X X    X    X     X     X X X         X          X             X X X     X X X X X                X X X X X X X X X X X X X Figure...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT