ProgrammingHardAccenture · Cognizant pattern
What does f(3) print?
What does f(3) print?
void f(int n) {
if (n > 0) {
f(n - 1);
printf("%d ", n);
f(n - 1);
}
}- A. 1 2 3
- B. 1 2 1 3 1 2 1
- C. 3 2 1 1 2 1
- D. 1 1 2 1 1 2 3
Correct answer: B. 1 2 1 3 1 2 1
f(1) prints 1. f(2) = f(1), 2, f(1) = 1 2 1. f(3) = f(2), 3, f(2) = 1 2 1 3 1 2 1. This is the in-order pattern of the Tower of Hanoi recursion: 2³ - 1 = 7 numbers.
More C Programming questions
- What is printed? c char a[] = "hi", b[] = "hi"; if (a == b) printf("same"); else printf("different");
- What is printed? c #define STR(x) #x #define CAT(a, b) a##b int xy = 7; printf("%s %d", STR(x+y), CAT(x, y));
- What is printed? c int x = 2; switch (x) { case 1: printf("A"); case 2: printf("B"); case 3: printf("C"); break; default: printf("D"); }
- What is printed? c int n = 5; while (n-- > 2) printf("%d", n); printf(" %d", n);
- Given int x = 1, y = 2; const int p = &x; int const q = &x; which pair of statements both fail to compile?
- What is printed? c enum { A, B = 5, C, D = 2, E }; printf("%d %d %d", A, C, E);