ProgrammingHardCompetitive coding (CP)

How many subarrays of {2, 1, 4, 3, 1, 2, 4} have a sum of exactly 7? Compute with this program.

How many subarrays of {2, 1, 4, 3, 1, 2, 4} have a sum of exactly 7? Compute with this program.
#include <stdio.h>
int main(void) {
    int a[] = {2, 1, 4, 3, 1, 2, 4}, c = 0;
    for (int i = 0; i < 7; i++) {
        int s = 0;
        for (int j = i; j < 7; j++) {
            s += a[j];
            if (s == 7) c++;
        }
    }
    printf("%d", c);
}
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 5

Correct answer: C. 3

The matching subarrays are {4, 3}, {2, 1, 4} and {1, 2, 4}, so the count is 3. The inner loop extends each start point one element at a time.

More C Programming questions

Exams that ask this topic