✏️ Explanatory Question

[Recursion]

Question:

Following method is a part of a class MyArray.

int check(int m[ ], int i)
{
    if(i <= 0)
    {
        return 0;
    }

    return check(m, i-2) + m[i-1];
}

public static void main()
{
    int m[ ] = {1, 2, 3, 4};

    int ans = check(m, m.length);

    System.out.println(ans);
}

(a) Predict the output of the code considering there is no compilation error. Show the working.

(b) Considering the if condition is changed to if(i < 0), how will it affect the output?

👁 1 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation


Answer:

(a) Output:

6

Working:

Initially:

m = {1,2,3,4}

m.length = 4

Function call:

check(m,4)

Recursive Working:

check(m,4)
= check(m,2) + m[3]
= check(m,2) + 4

check(m,2)
= check(m,0) + m[1]
= check(m,0) + 2

check(m,0)
= 0

Substituting values:

check(m,2)
= 0 + 2
= 2

check(m,4)
= 2 + 4
= 6

Therefore:

Output = 6

(b) If condition changed to:

if(i < 0)

Then the recursive calls become:

check(m,4)
→ check(m,2) + 4

check(m,2)
→ check(m,0) + 2

check(m,0)
→ check(m,-2) + m[-1]

Now:

  • m[-1] is invalid
  • Negative array index is not allowed in Java

Therefore, the program will generate:

ArrayIndexOutOfBoundsException

Conclusion:

  • With condition:
    if(i
    output = 6
  • With condition:
    if(i < 0)
    runtime error occurs because:
    m[-1]
    is invalid