ProgrammingHardTCS NQT · Infosys
How many binary strings of length 4 have exactly two 1s? The program counts them recursively. What is printed?
How many binary strings of length 4 have exactly two 1s? The program counts them recursively. What is printed?
#include <stdio.h>
int cnt(int n, int ones, int zeros) {
if (n == 0) return ones == 2 && zeros == 2;
return cnt(n - 1, ones + 1, zeros) + cnt(n - 1, ones, zeros + 1);
}
int main(void) {
printf("%d", cnt(4, 0, 0));
}- A. 4
- B. 6
- C. 8
- D. 10
Correct answer: B. 6
The recursion chooses for each position a 1 or a 0 and counts the leaves with two of each, which is C(4, 2) = 6.
More C Programming questions
- What is printed? c #include <stdio.h> int v[] = {1, 2, 3}; int cnt(int i, int s) { if (i == 3) return s % 2 == 0; return cnt(i + 1, s) +…
- What is printed? c #include <stdio.h> int used[3]; int count(int d) { if (d == 3) return 1; int t = 0; for (int i = 0; i < 3; i++) { if…
- What is printed? Assume uint8t is 8 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint8t x = 0x0F; uint8t r =…
- How many set bits does this loop count in 0xFFFF0000? c #include <stdio.h> int main(void) { unsigned x = 0xFFFF0000u; int c = 0; while (x)…
- What is printed? Assume unsigned int is 32 bits. c #include <stdio.h> int main(void) { unsigned a = 65536u; printf("%u", a a); }
- What is printed? c #include <stdio.h> int main(void) { printf("%d", sizeof(char) - 2 > 0); }