ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
int f(int n) {
if (n == 0) return 1;
return n + f(n - 1);
}
int main(void) {
printf("%d", f(100));
}- A. 5050
- B. 100
- C. Stack overflow: undefined behaviour due to 100 levels of recursion
- D. 5051
Correct answer: D. 5051
f(100) computes 100+99+...+1+1 (the +1 comes from the base case f(0)=1, not 0), which is the sum 1..100 (5050) plus the extra 1 from the base case, giving 5051. 100 levels of recursion is well within any normal stack's capacity, so this is not a stack overflow concern.
More C Programming questions
- 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));
- Assume a 64-bit LP64 ABI with #pragma pack(1) applied to this struct only. What is printed? c #pragma pack(push, 1) struct Packed { char…