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

The following program defines and calls a recursive function that should display

ID: 3915976 • Letter: T

Question

The following program defines and calls a recursive function that should display the sum of integers from one to the value of x. However, the program is not producing the desired result:

Your task is to analyze the program and function definitions. Identify the logic error(s) and fix the program.

In your post, share with us the following information about the program:

1. What is the recursive function's base case?

2.   What happens if the recursive function does not handle base cases correctly? How do we know if a base case is not written correctly?

3. Provide us the source code of your solution as text file.

Explanation / Answer

The error in your code is where you call the function again. It is very important that when you are defining recursive functions, two things must be taken care of. One is to manage the base case, which is done correctly in this program, and the other one is how you call the method recursively. In this program you are calling the function again and again with the same argument that is num with no change. That infinite loop is causing the program to exhaust memory and crash. So the fix is to change the below line

return function(num) - 1 + num;

to

return function(num-1)+ num;

at the end of the method. This will add all numbers between 1 and num and return it.

Now I’ll answer other questions you asked.

1. What is the recursive function's base case?

The base case is the condition where the recursion should stop. If you define a recursive function and if there is no stopping case, it will cause an infinite loop and the program crashes. In this program, if(num<=0) is the base case. The function will return 0 to the one that called it, no further recursive executions.

2.   What happens if the recursive function does not handle base cases correctly? How do we know if a base case is not written correctly?

As we said earlier, if the base cases are not implemented correctly, the program will run into an infinite loop, which will eventually crash it. Also depends on the cases, it can even throw some type of exceptions.

3. Provide us the source code of your solution as text file.

Here is the fixed code, along with the output. Thanks

#include <iostream>

using namespace std;

   

int function(int);

int main () {

    int x = 10;

    cout << function(x) << endl;

    return 0;

}

int function(int num){

    if (num <= 0)

        return 0;

    else

        return function(num-1)+ num; //function argument should be (num-1)

}

/*OUTPUT*/

55