ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    unsigned i = 0;
    int a[4] = {1, 2, 3, 4}, s = 0;
    for (int k = 0; k < 6; k++) {
        s += a[i % 4];
        i -= 3;
    }
    printf("%d", s);
}
  1. A. 15
  2. B. 6
  3. C. 13
  4. D. 10

Correct answer: C. 13

UINT_MAX + 1 is a power of two (at least 2^16), so subtracting 3 modulo it is like adding 1 modulo 4: i % 4 runs 0, 1, 2, 3, 0, 1 and the sum is 1 + 2 + 3 + 4 + 1 + 2 = 13. 15 steps the index by +3 instead, 6 assumes unsigned saturates at 0, and 10 sums the array only once.

More C Programming questions

Exams that ask this topic