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

Question 2(iv)

3 marks

Computer ScienceISC 2023 Specimen Computer Science Paper 1Case basedRecursion

Answer the questions on the code given below.

int quiz( int n) { if ( n <= 1 ) return n; else return (--n % 2) + quiz(n/10); } The following…

int quiz( int n)
{
    if ( n <= 1 )
        return n;
    else
        return (--n % 2) + quiz(n/10);
}
The following function quiz( ) is a part of some class. Assume ‘n’ is a positive integer, greater than 0. Answer the given questions along with dry run / working.
(a)[2]
What will the function quiz( ) return when the value of n=36922?
(b)[1]
State in one line what does the function quiz( ) do, apart from recursion?
Open in the Recursion visualiser

Answer

Answer (a)

quiz(36922) returns 3 (verified by running the code for real). Dry run: quiz(36922) = (36921%2) + quiz(3692) = 1 + quiz(3692) quiz(3692) = (3691%2) + quiz(369) = 1 + quiz(369) quiz(369) = (368%2) + quiz(36) = 0 + quiz(36) quiz(36) = (35%2) + quiz(3) = 1 + quiz(3) quiz(3) = (2%2) + quiz(0) = 0 + quiz(0) quiz(0) = 0 (base case, n<=1) Unwinding: quiz(3)=0, quiz(36)=1, quiz(369)=1, quiz(3692)=2, quiz(36922)=3 Return value: 3

Answer (b)

Apart from recursion, at each call the function decrements n by 1 and, if that decremented value is odd, adds 1 to a running total; it then continues on the value obtained by discarding the last digit of the decremented value (integer division by 10), repeating until the remaining value is <= 1. It finally returns the total count of decremented values that were odd along this chain.