What is recursion in C?
A
Calling multiple functions in a loop B
A function calling itself C
Using multiple return statements D
Using global variables
Analysis & Theory
Recursion is a process in which a function calls itself.
Which condition is necessary for a recursive function to stop calling itself?
A
Return statement B
Base case C
Loop condition D
Stack overflow
Analysis & Theory
A base case ensures the function stops calling itself and avoids infinite recursion.
What is the output?
```c
int fact(int n) {
if (n == 1) return 1;
return n * fact(n - 1);
}
int main() {
printf("%d", fact(3));
}
```
A
6 B
3 C
2 D
1
Analysis & Theory
fact(3) = 3 * 2 * 1 = 6
What will happen if there is no base case in a recursive function?
A
It will return 0 B
It will print nothing C
It will cause an infinite recursion and crash (stack overflow) D
It will run successfully
Analysis & Theory
Without a base case, the function calls itself infinitely and eventually causes a stack overflow.
Which of the following is an example of a base case in recursion?
A
return fact(n - 1); B
return 1; C
fact(n); D
int result = 0;
Analysis & Theory
A base case like `return 1;` ends the recursion.
What is the output?
```c
int sum(int n) {
if (n == 0) return 0;
return n + sum(n - 1);
}
int main() {
printf("%d", sum(4));
}
```
A
10 B
4 C
0 D
6
Analysis & Theory
sum(4) = 4 + 3 + 2 + 1 + 0 = 10
What is the output?
```c
void print(int n) {
if (n == 0) return;
printf("%d ", n);
print(n - 1);
}
int main() {
print(3);
}
```
A
3 2 1 B
1 2 3 C
3 3 3 D
0 1 2
Analysis & Theory
The numbers are printed before the recursive call, so output is: 3 2 1
What is the maximum depth of recursion determined by?
A
CPU speed B
Stack size C
Number of variables D
Main function size
Analysis & Theory
Recursion depth is limited by the call stack size, not the CPU or variable count.
Which of these problems is best solved using recursion?
A
Sorting numbers using bubble sort B
Reversing a string C
Computing factorial D
Multiplying two numbers
Analysis & Theory
Factorial is a classic example of a problem naturally suited for recursion.
What is the output?
```c
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
int main() {
printf("%d", fib(4));
}
```
A
3 B
5 C
2 D
4
Analysis & Theory
fib(4) = fib(3) + fib(2) = 2 + 1 = 3