Consider the following C code that uses recursion. What will it print when run?
#include <stdio.h> void printNumbers(int n) { if (n == 0) return; printNumbers(n - 1); printf("%d ", n); } int main() { printNumbers(3); return 0; }
Think about when the printf statement runs during the recursion.
The function calls itself with n-1 before printing. So it prints numbers in ascending order after reaching the base case.
Analyze the output of this C program with nested function calls.
#include <stdio.h> void f1() { printf("A"); } void f2() { printf("B"); f1(); printf("C"); } int main() { f2(); return 0; }
Follow the order of function calls and prints carefully.
f2 prints 'B', calls f1 which prints 'A', then f2 prints 'C'. So output is 'BAC'.
Examine this recursive function. What error will it cause when run?
#include <stdio.h> void recurse(int n) { printf("%d ", n); recurse(n + 1); } int main() { recurse(1); return 0; }
Consider what happens when the function never stops calling itself.
The function calls itself without a base case, causing infinite recursion and stack overflow.
Identify which code snippet will cause stack corruption because of incorrect function pointer usage.
Think about what happens when you call a function pointer set to an invalid address.
Option A sets a function pointer to an invalid address (1234) and calls it, causing stack corruption or crash.
Given this recursive function, how many stack frames exist at the deepest recursion call?
#include <stdio.h> void countDown(int n) { if (n == 0) return; countDown(n - 1); printf("%d ", n); } int main() { countDown(5); return 0; }
Remember the base case call also creates a stack frame.
The function calls itself with n=5 down to n=0. At n=0, the deepest call, there are 6 active stack frames (for n=5,4,3,2,1,0).