ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
#include <stdio.h>
int trace(int n) {
printf("t%d ", n);
return n == 0;
}
int f(int n) {
if (trace(n) || f(n - 1)) return 1;
return 0;
}
int main(void) {
printf("%d", f(2));
}- A. t2 t1 t0 1
- B. t2 t1 t0 0
- C. t0 t1 t2 1
- D. t2 1 t1 t0
Correct answer: A. t2 t1 t0 1
trace(n) always prints first and is false until n reaches 0, so f(2) recurses through f(1) into f(0) before trace returns true, printing t2 t1 t0 in order; the true result from f(0) then bubbles back up through the || chains, so f(2) returns 1.
More C Programming questions
- What is printed? c #include <stdio.h> void inc(int a[], int n) { if (n == 0) return; a[n - 1]++; inc(a, n - 1); } int main(void) { int…
- What is printed? c #include <stdio.h> void f(int n) { if (n == 0) return; for (int i = 0; i < n; i++) printf(""); f(n - 1); printf("|"); }…
- What is printed? c #include <stdio.h> int cmp = 0; int search(int a, int n, int key) { if (n == 0) return -1; cmp++; if (a[n - 1] == key)…
- What is printed? c #include <stdio.h> void f(int n) { if (n <= 0) { printf("B "); return; } if (n % 2 == 0) printf("E%d ", n); else…
- What is printed? c #include <stdio.h> int digitSum(int n) { if (n == 0) return 0; printf("%d ", n % 10); return n % 10 + digitSum(n / 10)…
- What is printed? c #include <stdio.h> void count(int n) { int local = n; if (n == 0) { printf("local=%d ", local); return; } count(n - 1)…