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);
}- A. 4
- B. 2
- C. 3
- 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
- What is printed? c #include <stdio.h> int main(void) { int a[] = {1, 3, -1, -3, 5, 3, 6, 7}; int k = 3, dq[8], head = 0, tail = 0, total =…
- How many values x in 0..255 satisfy (x & (uint8t)-x) == x? Assume uint8t is 8 bits. c #include <stdint.h> #include <stdio.h> int…
- What is printed? c #include <stdio.h> int f(int n) { static int calls = 0; calls++; if (n <= 0) return calls; int r = f(n - 2); return r…
- What is printed? c #include <stdio.h> struct P { int v; }; int main(void) { struct P arr[3] = {{1}, {2}, {3}}; int sum = 0; for (struct P…
- What is printed? c #include <stdio.h> int main(void) { char c = 'a'; printf("%d %d", c + 1 == 'b', '9' - '0'); }
- What is printed? c #include <stdio.h> unsigned fibcalls = 0; int fib(int n) { fibcalls++; if (n < 2) return n; return fib(n - 1) + fib(n…