I need help with recursive.

Hi. I am taking a course on C++ but now i regret. professor taught some basic knowledge but the homework seems complicated.
please help me.

1
2
3
4
5
6
7
8
9
10
11
12
13
  int sum_down(int x)
{
	if (x >= 0)
	{
		x = x - 1;
		int y = x + sum_down(x);
		return y + sum_down(x-1);
	}
	else
	{
		return 1;
	}
}


a) What is this smallest integer value of the parameter x, so that the returned value is greater than 1.000.000 ?

b) Rewrite the function, so that it is free of recursion. I.e. give an iterative definition on the foundation of a loop-construct.
TIP: First transform the recursive definition, so that you have just a single recursive call.

c) Assume that we change the parameter x to a reference parameter. So we get:
int sum_down(int &x)

Adapt your solution for b), so that it shows once again the same behaviour like the recursive definition.

d) Is it ok to switch the type of the parameter x to unsigned int?
Discuss your decision / give an argumentation.

e) Is it ok to switch the type of the parameter x to double?
Discuss your decision / give an argumentation.

f) Is it ok to switch the function head to int sum_down(const int x)?
Discuss your decision / give an argumentation.
The "base case" of the recursion is when x<0. Figure out what sum_down() returns when x= -1, when x=0, when x=1..... Look for the pattern. Once you have that the rest should fall into place.
lets explain for x=0 from main,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int sum_down(int x) // x=0(from main), x= -1 (from line 9) , x= -2 (from line 10)
{
	if (x >= 0) // yes , no, no
	{
		x = x - 1; // x = -1
		int y = x + sum_down(x); // y = -1 + sum_down (-1)  = -1 + 1 = 0
		return y + sum_down(x-1); // 0 + sum_down (-1-1) = 0 + sum_down(-2) = 0+ 1 = 1 
	}
	else 
	{
		return 1; // 1 for x = -1 (line 9), 1 for x= -2 (line 10)
	}
}

int main ()
{
    cout << sum_down(0); // output 1
    return 0;	
}
Topic archived. No new replies allowed.