CS111 Lab 5 Recursion Part I

Part I: Answer the following questions given the function below.

		static void func (int num) {
			if ( 1 <= num && num <= 8) {
				func(num - 1);
				System.out.print(num);
			}
			else {
				System.out.println();
			}
		}
	
  1. What is the base case for the recrusive function func?
  2. What output is produced for func(5)?
  3. What output is produced for func(10)?
  4. If num - 1 is replaced by num + 1, what output is produced for func(5)?
  5. If num - 1 is replaced by num + 1, what output is produced for func(10)?
  6. If the statement System.out.print(num); is interchanged with func(num - 1);, what output is produced for func(5)?
  7. If the statement System.out.print(num); is interchanged with func(num - 1);, what output is produced for func(10)?
  8. If the statement System.out.print(num); occurs both before and after the function call func(num - 1);, what output is produced for func(5)?
  9. If the statement System.out.print(num); occurs both before and after the function call func(num - 1);, what output is produced for func(10)?



Part II: Answer the following questions given the function below.

		static int funcA (int x, int y) {
			if (x > y)
			return 0;
			else if (y == x + 1)
			return 1;
			else
			return funcA(x+1, y-1) + 2;
		}
	
  1. What is the primitive state for the function funcA()?
  2. What value is returned from the function call funcA(1,5)?
  3. What value is returned from the function call funcA(8,3)?



Part III: Determine what is calculated by the recursive functions below.

Exercise 1
		static int f(int n) {
			if (n == 0)
	  		return 0;
			else
		  	return n * f(n - 1);
		}
	
Exercise 2
		static double f( double x, int n) {
			if (n == 1)
		  	return 1;
			else
		  	return x * f(x, n - 1);
		}
	
Exercise 3
		static int f( int n) {
			if (n < 2)
		  	return 0;
			else
		  	return 1 + f(n / 2);
		}
	
Exercise 4
		static void asciiArt(int rowNumber, int rows){
			int i;

			if (rowNumber <= rows){
				for (i = 1; i <= rowNumber; i++){
					System.out.print("*");
				}
				System.out.println();

				asciiArt(rowNumber + 1, rows);

				for (i = 1; i <= rowNumber; i++){
					System.out.print("*");
				}
				System.out.println("*");
			}
		}