hamburger menu
All Coursesall course arrow
adda247
reward-icon
adda247
    arrow
    arrow
    arrow
    What will be the output of the following recursive C++ code?
    Question

    What will be the output of the following recursive C++ code?

    A.

    -9

    B.

    10

    C.

    -7

    D.

    -5

    E.

    9

    Correct option is A

    Let’s break down the recursive calls for the given input result(20, 1) step by step:
    1. First call: result(20, 1)
    · n = 20 (even): Call result(10, 2) + 1.
    2. Second call: result(10, 2)
    · n = 10 (even): Call result(5, 4) + 2.
    3. Third call: result(5, 4)
    · n = 5 (odd): Call result(2, 8) - 4.
    4. Fourth call: result(2, 8)
    · n = 2 (even): Call result(1, 16) + 8.
    5. Fifth call: result(1, 16)
    · n = 1 (odd): Call result(0, 32) - 16.
    6. Base case: result(0, 32)
    · n = 0: Return 0.
    Now, let’s calculate the returned values step by step:
    · result(0, 32) = 0.
    · result(1, 16) = 0 - 16 = -16.
    · result(2, 8) = -16 + 8 = -8.
    · result(5, 4) = -8 - 4 = -12.
    · result(10, 2) = -12 + 2 = -10.
    · result(20, 1) = -10 + 1 = -9.
    Thus, the final output is -9.
    Important Key Points:
    1. Base case: The recursion stops when n == 0, returning 0.
    2. Even case (n % 2 == 0): Adds k to the result of the recursive call.
    3. Odd case (n % 2 != 0): Subtracts k from the result of the recursive call.
    4. The value of k doubles with each recursive step, significantly affecting the result.
    Knowledge Booster:
    · 10: This would occur if incorrect calculations were made in the addition/subtraction logic during recursion.
    · -7: Represents a logical error if one subtraction step is skipped.
    · -5: Results from a miscalculation in intermediate recursive steps.
    · 9: Would appear if all additions were performed incorrectly, ignoring the subtraction logic.

    Free Tests

    Free
    Must Attempt
    Video Solutions

    RBI Office Attendant 2026 Full Mock Test - 01

    languageIcon English
    • pdpQsnIcon120 Questions
    • pdpsheetsIcon120 Marks
    • timerIcon90 Mins
    languageIcon English
    Free
    Must Attempt
    Video Solutions

    RBI Office Attendant 2026: General English Section Test 01

    languageIcon English
    • pdpQsnIcon30 Questions
    • pdpsheetsIcon30 Marks
    • timerIcon22 Mins
    languageIcon English
    Free
    Must Attempt

    RBI Office Attendant 2026: Quant Section Test 01

    languageIcon English
    • pdpQsnIcon30 Questions
    • pdpsheetsIcon30 Marks
    • timerIcon23 Mins
    languageIcon English
    test-prime-package

    Access ‘SEBI Grade-A Assistant Manager’ Mock Tests with

    • 60000+ Mocks and Previous Year Papers
    • Unlimited Re-Attempts
    • Personalised Report Card
    • 500% Refund on Final Selection
    • Largest Community
    students-icon
    344k+ students have already unlocked exclusive benefits with Test Prime!
    Our Plans
    Monthsup-arrow