ProgrammingHardIBM · Deloitte pattern
What is printed? (recursion where the base case is reached via an off-by-one condition)
What is printed? (recursion where the base case is reached via an off-by-one condition)
int f(int n) {
if (n < 1) return 0;
return n + f(n - 2);
}
int main(void) {
printf("%d", f(6));
}- A. 21
- B. 12
- C. 6
- D. 9
Correct answer: B. 12
f(6)=6+f(4)=6+4+f(2)=6+4+2+f(0, which is <1 so returns 0)=6+4+2+0=12. Note f only ever sees even n here (6,4,2,0), so the sum is 6+4+2=12.
More C Programming questions
- What is printed? (recursion with a pointer parameter used only for read, not accumulation) c int maxOf(int a[], int n) { if (n == 1)…
- What is printed? (recursive function returning a computed value through a chain of ternaries) c int classify(int n) { return n == 0 ? 0…
- What is printed? c #define SQUARE(x) x x int main(void) { int a = 3; printf("%d", SQUARE(a + 1)); }
- What is printed? c #define PRINT(x) printf(#x " = %dn", x) int main(void) { int apple = 10; PRINT(apple); }
- What is printed? c #define CONCAT(a, b) a ## b int xy = 100; printf("%d", CONCAT(x, y));
- What is printed? c #define N 5 #undef N #define N 10 printf("%d", N);