‹ Back to the paper
The following function quiz( ) is a part of some class. Assume ‘n’ is a positive integer, greater…
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.
int quiz( int n)
{
if ( n <= 1 )
return n;
else
return (--n % 2) + quiz(n/10);
} (a)[2.0]
What will the function quiz( ) return when the value of n=36922?
(b)[1.0]
State in one line what does the function quiz( ) do, apart from recursion?
Answer
Answer (a)
AIquiz(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)
AIApart 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.
From ISC 2023 Specimen Computer Science Paper 1, question 2(iv).