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));
}
  1. A. 4
  2. B. 6
  3. C. 8
  4. 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

Exams that ask this topic