ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
int f(int n, int acc) {
if (n == 0) return acc;
return f(n - 1, acc * n);
}
int main(void) {
printf("%d", f(5, 1));
}- A. 1
- B. 5
- C. 120
- D. 24
Correct answer: C. 120
This is tail-recursive factorial using an accumulator: acc carries the running product forward instead of multiplying after the recursive call returns. f(5,1)->f(4,5)->f(3,20)->f(2,60)->f(1,120)->f(0,120), returning 120 immediately at the base case with no further multiplication needed on the way back up.
More C Programming questions
- What is printed? c int f(int n) { int local = n; if (n == 0) return 0; local += f(n - 1); return local; } int main(void) { printf("%d"…
- What is printed? c int f(int n) { if (n == 0) return 1; return n + f(n - 1); } int main(void) { printf("%d", f(100)); }
- What is printed? c int f(int n) { if (n <= 0) return 0; int a = f(n - 1); int b = f(n - 1); return a + b + 1; } int main(void) {…
- What is printed? c void countdown(int n) { if (n < 0) return; printf("%d ", n); countdown(n - 1); } int main(void) { countdown(3)…
- What is printed? c int f(int n) { if (n <= 0) return 0; (n)--; return 1 + f(n); } int main(void) { int x = 5; printf("%d %d", f(&x), x); }
- Assume a 64-bit LP64 ABI with natural alignment (no #pragma pack). What is printed? c struct S { char a; int b; char c; }; printf("%zu"…