ITFN 2313
Recursion Lab – September 10, 2009
1. On the back of this page, explain in detail what happens when the following code executes. I’m not looking for output here. Also, identify the base case and the recursive call.
public static int myRecursiveFunction(int x)
{
if (x <= 0) return x;
return myRecursiveFunction(x - 1);
}
static void Main(string[] args)
{
int x = myRecursiveFunction(7);
Console.WriteLine(x);
}
· myRecursiveFunction is called from Main, and 7 is passed into x
· Base Case if (x <= 0) evaluates to false, so recursive call is made, passing 6 (x-1)
· This cycle continues until the base case evaluates to true (0 is passed with the recursive call)
· 0 is returned to main and the next line prints 0 to the screen
2. In the space below, write a recursive function that displays the numbers counting up by 2 (0, 2, 4, 6, …) to 100. Be sure you indicate how it would be invoked to get the desired results.
static void RecursiveFunction(int x)
{
if (x > 100) //Condition to stop recursion or base case
return; //Exit out of function
else
{
Console.WriteLine(x);
RecursiveFunction(x + 2); //Recursive Call
}
}
static void Main(string[] args)
{
RecursiveFunction(0);
}
3. In the space below, rewrite the function for question #2 so that the numbers are printed in reverse (100, 99, 98, …)
NOTE: This is the same function, it is just a matter of the output taking place after the recursive calls.
static void RecursiveFunction(int x)
{
if (x > 100) //Condition to stop recursion or base case
return; //Exit out of function
else
{
RecursiveFunction(x + 2); //Recursive Call
Console.WriteLine(x);
}
}
static void Main(string[] args)
{
RecursiveFunction(0);
}