ISC Class 12 Computer Science (Java) - Recursion Special Question Paper
Specialisation: Recursion (Output-Based Questions)
Class: XII
Board: CISCE (ISC)
Instructions:
Answer all questions. Each question carries equal marks.
Show the dry run where necessary.
Use only recursion. No iteration (loops) allowed.
Questions:
1. Q1. Consider the following recursive function and write the output for f(5):
int f(int n) {
if (n == 0)
return 0;
return n + f(n - 2);
}
2. Q2. Trace and find the output of the following function call: mystery(3)
void mystery(int n) {
if (n > 0) {
mystery(n - 1);
System.out.print(n + " ");
mystery(n - 2);
}
}
3. Q3. Given the function below, find and write the output for foo(4).
void foo(int n) {
if (n == 0) return;
System.out.print(n + " ");
foo(n - 1);
System.out.print(n + " ");
}
4. Q4. Predict the output of the following recursive method when called with test(1, 5):
void test(int a, int b) {
if (a > b) return;
System.out.print(a + " ");
test(a + 1, b);
System.out.print(a + " ");
}
5. Q5. Find the output for the function call: weird(3)
void weird(int n) {
if (n == 0) return;
weird(n - 1);
System.out.print((char)(n + 64) + " ");
weird(n - 1);
}
Solutions:
6. A1. f(5):
Call sequence: f(5) → 5 + f(3) → 5 + 3 + f(1) → 5 + 3 + 1 + f(-1)
Since f(-1) is invalid, assume base case handles n <= 0
So, Output: 5 + 3 + 1 = 9
7. A2. mystery(3):
Call sequence:
- mystery(3)
- mystery(2)
- mystery(1)
- mystery(0)
- print 1
- mystery(-1)
- print 2
- mystery(0)
- print 3
- mystery(1)
- mystery(0)
- print 1
- mystery(-1)
Output: 1 2 3 1
8. A3. foo(4):
Print 4 → foo(3)
Print 3 → foo(2)
Print 2 → foo(1)
Print 1 → foo(0)
Return and print values again: 1 2 3 4
Output: 4 3 2 1 1 2 3 4
9. A4. test(1, 5):
Print 1 → test(2,5) → Print 2 → test(3,5) → Print 3 → test(4,5) → Print 4 → test(5,5) →
Print 5
Then reverse print: 5 4 3 2 1
Output: 1 2 3 4 5 5 4 3 2 1
10. A5. weird(3):
weird(3):
weird(2):
weird(1):
weird(0)
print A
weird(0)
print B
weird(1): same as above
print C
weird(2): same as before
Output: A B A C A B A