Exercises
Recursion #2

Evaluate each Java recursive function f for the given parameter values.

int f(int x) //x is nonnegative
	
	{
		if (x == 0)
			return (x + 1);
		return 1 + f(x-1);
	}
System.out.print(f(3));
int f(int x, int y)
	{
		if (x <= 0)
			return (0);
		if (y >= x)
			return 1 + f(y,x);
		return 2 + f(x-3,y-1);
	}
System.out.print(f(6,5));
int f(int x)
	{
		if (x < 5)
			return x*x + 1;
		if (x == 5)
			return x*x - 3;
		return f(x-2);
	}
System.out.print(f(f(f(f(f(f(3)))))));

Show the output of each recursive module.

void print(int n)
	{
		print (n - 1);
		System.out.print(n);
		print (n - 1);
	}
	:
print(3);
System.out.println();

ArrayList list(10);
// list contains	{ 4, -1, 5, 1, 8, 3, -2, 1, 6, 7 }
	:
int calculate(ArrayList list, int first, int last)
	{
		if (first < last )
			return 0;
		return list.get(first) + calculate(list,first+1,last);
	}
	:
System.out.print("The result is "  + calculate (list, 2, 7));  


Continue to:  Unit 3 / Prev / Next