Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 3

5 marks

Computer ScienceISC 2020 Specimen Computer Science Paper 1OutputRecursion

What is the output of the following code?

The following is a function of some class. What will be the output of the function test ( ) when…

The following is a function of some class. What will be the output of the function test ( ) when the value of count is equal to 4 ? Show the dry run / working.
void test (int count)
{
    if (count == 0)
        System.out.println(" ");
    else
    {
        System.out.println("Bye" + count);
        test(--count);
        System.out.println(" " + count);
    }
}
Open in the Recursion visualiser

Answer

Answer

Dry run for test(4) (count is reduced by --count before the recursive call, so the line printed after the call shows the reduced value): test(4): count is not 0, prints Bye4, then count becomes 3 and test(3) is called test(3): prints Bye3, count becomes 2, calls test(2) test(2): prints Bye2, count becomes 1, calls test(1) test(1): prints Bye1, count becomes 0, calls test(0) test(0): count == 0, prints a blank line (a space) and returns Back in test(1): prints " 0" Back in test(2): prints " 1" Back in test(3): prints " 2" Back in test(4): prints " 3" Output: Bye4 Bye3 Bye2 Bye1 (blank line) 0 1 2 3 (verified by running the code)