Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. What is direct recursion? 2. Consider the following recursive function: void

ID: 3853532 • Letter: 1

Question

1. What is direct recursion?

2. Consider the following recursive function:

void funcRec(int u, char v)                       //Line 1
{  
if (u == 0)                                              //Line 2
cout << v;                                            //Line 3
else                                                      //Line 4
{                                                       //Line 5
char w;                                                //Line 6
w = static_cast <char>                        //Line 7
(static_cast<int>(v) + 1);
funcRec(u - 1, w);                               //Line 8
                                    }                 //Line 9
                        }                              //Line 10

Now answer the following questions:

a. Identify the base case.

b. Identify the general case.

c. What is the output of the following statement? funcRec(5, 'A');

3. Consider the following recursive function:

void recFun(int u)
{

if (u == 0)
cout << "Zero! ";
else
{
cout << "Negative ";
recFun(u + 1);
}

}

What is the output, if any, of the following statements?

a. recFun(8);

b. recFun(0);

c. recFun(-2);

4. Consider the following function:

int test(int x, int y)
{

if (x <= y)
return y - x;
else
return test(x - 1, y + 1);

}

What is the output of the following statements?

a. cout << test(3, 100) << endl;

b. cout << test(15, 7) << endl;

5. Suppose that intArray is an array of integers, and length specifies the number of elements in intArray. Also, suppose that low and high are two integers such that 0 <= low < length, 0 <= high < length, and low < high. That is, low and high are two indices in intArray.

a. Write a recursive definition that reverses the elements in intArray between low and high.

Explanation / Answer

1. Direct recursion is the concept of calling a function to itself from the same function. For example consider:

void test(int value)

{

...

test(otherValue);

...

}

Here test is a function which calls to itself, and therefore is called direct recursion.

2. a. The base case of a recursive function is the case which doesn't lead to recursion, or the case which will pull you out of recursively calling a function.

Here, in the example,

line 2, i.e., u == 0 is the base case which will not call the function recFun() recursively, and for all other values, the else block will be executed, and therefore, will be recursively called.

b. The general case is the different possibilities of a recursive function, and the general case is:

F(u, v) = 0, if u == 0

= F(u-1, v+1) otherwise.

c. Output of funcRec(5, 'A')

= funcRec(4, 'B')

= funcRec(3, 'C')

= funcRec(2, 'D')

= funcRec(1, 'E')

= funcRec(0, 'F')

= 'F'

Therefore, the output to be printed to the screen is: F