‹ Back to the paper
Following method is a part of a class MyArray. int check(int m[ ], int i) { if (i <= 0) { return 0…
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)[1.0]
Predict the output of the code considering there is no compilation error. Show the working.
(b)[1.0]
Considering the if condition is changed to `if(i < 0)`, how will it affect the output?
Answer
Answer (a)
AIOutput: 6
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): since i=0 <= 0, returns 0
So check(m,2) = 0 + 2 = 2, and check(m,4) = 2 + 4 = 6. ans = 6
Answer (b)
AIWith if(i < 0), the base case i=0 is no longer true (0 is not < 0), so recursion does not stop there: check(m,0) calls check(m,-2) + m[-1], and m[-1] is an invalid array index. The program throws an ArrayIndexOutOfBoundsException (index -1) instead of returning a value, so it crashes rather than printing 6.
From ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024), question 56.