Computer Science Concepts - Test 13 (Recursion)


  1. The following four statements describe the term recursion. Three of them are correct. Which one is incorrect?

    1. Recursion is induction applied to programming

    2. When a program calls itself, we say it is a recursive program

    3. Recursion in programming does involve a stack but one hidden from us by the compiler

    4. Recursion means iteration

    check/hide answer

  2. The following is a recursive program. Let's assume that it only takes the positive integers as the input:
    int do_something(int n) {
        if(n==1) return 1;
        else if(n>1) return n * do_something(n-1);
    }
    
    Can you tell what the above program really does?

    1. It always returns 1

    2. It returns the value n

    3. It returns the value n*(n-1)

    4. It returns the value n*(n-1)*(n-2)*...*(3)*(2)*(1)

  3. In the above program, assume that the recursion part is written differently as below, i.e. (n-1) is replaced by (n):
    int do_something(int n) {
        if(n==1) return 1;
        else if(n>1) return n * do_something(n);
    }
    
    

    what will happen?

    1. The program will just work fine

    2. The compiler will not compile the program, and you will get a syntax error message

    3. The program can be compiled, but when you run it, it will loop forever

    4. The program can be compiled, but when you run it, you will get a runtime error

  4. Consider the following Java program
    static public void print(int n) {
        if(n == 0) System.out.print(n); 
        if(n > 0) {
            System.out.print(" "+n);
            print(n-1);
        }
        else {
            print(n+1);
            System.out.print(" "+n);
        }
    }
    	 
    
    What do we get on the screen when we call print(5)?

    1. 0 1 2 3 4 5

    2. 5 4 3 2 1 0

    3. 0

    4. 5

  5. Use the same Java program, what do we get on the screen when we call print(-5)?

    1. 0 -1 -2 -3 -4 -5

    2. -5 -4 -3 -2 -1 0

    3. 0

    4. -5


Rong Yang,