ProgrammingHardIBM · Deloitte pattern
What is printed? (recursion with an early return skipping the rest of the function)
What is printed? (recursion with an early return skipping the rest of the function)
int f(int n) {
if (n < 0) return -1;
if (n == 0) return 0;
int r = f(n - 1);
if (r == -1) return -1;
return r + n;
}
int main(void) {
printf("%d", f(4));
}- A. -1
- B. 4
- C. 10
- D. 0
Correct answer: C. 10
No n ever goes negative here (f is only ever called with n, n-1, ... down to 0), so the -1 short-circuit path is never taken; this just computes 4+3+2+1+0 = 10.
More C Programming questions
- What is printed? (binary string of n using recursion, division by 2) c void toBinary(int n) { if (n == 0) return; toBinary(n / 2)…
- What is printed? (two mutually exclusive recursive branches selected by a condition, with accumulation via return value) c int f(int n) {…
- What is printed? (recursion where the base case is reached via an off-by-one condition) c int f(int n) { if (n < 1) return 0; return n +…
- 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)); }