Recursive calls

Hello I am very confused on this homework I am doing. I know you make think i am lazy for doing this but I am desperate and really need the help. I've done most of the work but can figure out these last 2 questions. The questions for both are "What is the output of the following code fragment? Please trace the recursive calls" any help you could give would be great.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int f1(int n, int m)
{
	if(n < m)
		return 0;
	else if(n == m)
		return m + f1(n - 1,m);
	else
		return n+ f1(n - 2,m - 1);
}

int main( )
{
	cout << f1(5,4);
	return 0;
} 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int f1(int base, int limit)
{
	if(base > limit)
		return -1;
	else
		if(base == limit)
				return 1;	
	else
		return base * f1(base + 1, limit);
}

int main( )
{
	cout << f1(2,4) << endl;
	return 0;

} 

Have you though about e.g. instrumenting the code and running it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>

int f1(int n, int m, int indent)
{
   std::cout << std::string(indent, ' ') << "f1(" << n << ',' << m << ")\n";

   if(n < m)
      return 0;
   else if(n == m)
      return m + f1(n - 1, m, indent + 1);
   else
      return n + f1(n - 2, m - 1, indent + 1);
}

int main()
{
   std::cout << f1(5,4,0) << '\n';
   return 0;
}

f1(5,4)
 f1(3,3)
  f1(2,3)
8
Topic archived. No new replies allowed.