ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
int f(int n) {
if (n == 0) return 0;
int x = f(n - 1);
printf("%d ", n);
return x + n;
}
int main() { printf("= %d", f(4)); }- A. 1 2 3 4 = 10
- B. 4 3 2 1 = 10
- C. 1 2 3 4 = 4
- D. 4 3 2 1 = 4
Correct answer: A. 1 2 3 4 = 10
The recursive call f(n-1) happens BEFORE the printf, so the prints happen during unwinding in increasing order: the n=1 frame's printf runs first (after its own f(0) returns), then n=2, then n=3, then n=4: '1 2 3 4 '. The sum returned accumulates 1+2+3+4=10.
More C Programming questions
- What is printed? c int depth = 0; void f(int n) { depth++; if (n == 0) return; f(n - 1); } int main() { f(3); printf("%d", depth); }
- What is printed? c void f(int n) { if (n <= 0) return; printf("%d ", n); if (n % 2 == 0) f(n / 2); else f(n - 1); } int main() { f(6); }
- Assume a 64-bit LP64 ABI. What is printed? c int x = 5, y = 10, z = 15; int arr[3] = {&x, &y, &z}; int p = arr; printf("%d %d %d", arr[1]…
- Assume a 64-bit LP64 ABI. Which declaration makes p an array of 5 pointers to int, and which makes q a pointer to an array of 5 ints?
- Assume a 64-bit LP64 ABI. What is printed? c int mat[2][3] = {{1, 2, 3}, {4, 5, 6}}; int (rowPtr)[3] = mat; printf("%d %d %d %zu"…
- Assume a 64-bit LP64 ABI. What is printed? c int a[4] = {1, 2, 3, 4}; int p = a + 3; int q = a; printf("%ld %d %d", (long)(p - q), p, (p…