ProgrammingVery hardCompetitive coding (CP)

How many subarrays of {1, -1, 2, -2, 3} have sum zero? Compute with this program.

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

Correct answer: B. 3

The zero-sum subarrays are [1, -1], [2, -2] and [1, -1, 2, -2], which is three.

More C Programming questions

Exams that ask this topic