ProgrammingHardAccenture · Cognizant pattern
What is printed?
What is printed?
int f(int n) {
static int s = 0;
s += n;
if (n > 0) f(n - 1);
return s;
}
...
printf("%d ", f(3));
printf("%d", f(3));- A. 6 12
- B. 3 3
- C. 6 6
- D. 6 18
Correct answer: A. 6 12
All recursive calls share the one static s. The first f(3) adds 3 + 2 + 1 + 0, and the outer call returns s after the recursion: 6. The second f(3) starts from 6 and adds 6 more: 12.
More C Programming questions
- What is printed? c printf("%d", 2 + 3 << 1 & 7);
- How many of these are correct in C? (i) A global variable without an initialiser starts as 0. (ii) A static local variable is initialised…
- What is f in the declaration int (f)(int); ?
- What is printed? c int a[] = {5, 10, 15}; int p = a; int x = p++; int y = (p)++; int z = ++p; printf("%d %d %d %d", x, y, z, a[1]);
- With 32-bit unsigned int, what is printed? c unsigned int x = 0; x--; printf("%u %d", x, x > 0);
- With ASCII and 4-byte int, what is printed? c char c = 'A'; c = c + 32; printf("%c %zu", c, sizeof(c + 1));