ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
int f(int n) {
int local = n;
if (n == 0) return 0;
local += f(n - 1);
return local;
}
int main(void) {
printf("%d", f(4));
}- A. 4
- B. 14
- C. 24
- D. 10
Correct answer: D. 10
Each call has its OWN automatic local variable (unlike a static one), so there is no sharing between stack frames. local accumulates n + (n-1) + ... + 0 as the recursion unwinds: 4+3+2+1+0 = 10.
More C Programming questions
- 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"…
- Assume a 64-bit LP64 ABI with natural alignment. What is printed? c struct S { int a; char b; int c; }; printf("%zu", sizeof(struct S));