ProgrammingVery hardProduct company OA

Assume 8-bit unsigned char. What is printed?

Assume 8-bit unsigned char. What is printed?
unsigned int count = 0;
for (unsigned char i = 250; i != 4; i += 3) count++;
printf("%u", count);
  1. A. 174
  2. B. 88
  3. C. 2
  4. D. The loop never terminates

Correct answer: A. 174

i wraps modulo 256 (unsigned arithmetic after conversion back to unsigned char is well defined). We need the smallest k ≥ 0 with 250 + 3k ≡ 4 (mod 256), i.e. 3k ≡ 10. Because gcd(3, 256) = 1 the step visits every residue, so the loop does terminate: 3⁻¹ ≡ 171 (3·171 = 513), k ≡ 1710 ≡ 174. One lap is not enough: after the first wrap i takes 0, 3, 6, …, after the second 2, 5, 8, …, and only the third lap (1, 4) hits 4. 'Never terminates' would be right for a step such as i += 4, which only ever reaches values ≡ 2 (mod 4).

More C Programming questions

Exams that ask this topic