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

Question 2(iii)

3 marks

Computer ScienceISC 2026 Improvement Computer Science Paper 1Case basedRecursion

Answer the questions on the code given below.

public int justDoIt(int num) { if (num == 0) return 0; int c = justDoIt(num / 2); int bit = num %…

public int justDoIt(int num)
{
    if (num == 0)
        return 0;
    int c = justDoIt(num / 2);
    int bit = num % 2;
    System.out.print(bit);
    return c + (bit == 1 ? 1 : 0);
}
The following function justDoIt() is a part of some class. Assume num is a positive integer. Answer the questions given below along with dry run / working.
(a)[2]
What will the function justDoIt( ) return when num = 126?
(b)[1]
What is the function justDoIt( ) performing apart from recursion?
Open in the Recursion visualiser

Answer

Answer (a)

Dry run of justDoIt(126) (verified by running the code): justDoIt(126) → calls justDoIt(63); bit=126%2=0 → prints '0' justDoIt(63) → calls justDoIt(31); bit=63%2=1 → prints '1' justDoIt(31) → calls justDoIt(15); bit=31%2=1 → prints '1' justDoIt(15) → calls justDoIt(7); bit=15%2=1 → prints '1' justDoIt(7) → calls justDoIt(3); bit=7%2=1 → prints '1' justDoIt(3) → calls justDoIt(1); bit=3%2=1 → prints '1' justDoIt(1) → calls justDoIt(0); bit=1%2=1 → prints '1' justDoIt(0) → returns 0 (base case) As the calls unwind, the bits print in order: 1111110 (this is 126 written in binary), and the count c accumulates 1 for every bit equal to 1 — there are six 1's among the seven bits. Return value: 6

Answer (b)

Apart from recursion, the function displays (prints) the binary equivalent of num, one bit at a time from the most significant bit to the least significant bit, and it counts and returns the number of 1's (set bits) present in that binary representation.