AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumcoperators

~90s

Dividing a negative number

What does this C program print? Assume a C99 or later compiler.

#include <stdio.h>

int main(void) {
    printf("%d %d", -7 / 2, -7 % 2);
    return 0;
}
Show the answer and the worked solution

Correct answer: C.

-3 -1

Worked solution

  1. -7 / 2 is -3.5 truncated towards zero, which gives -3, not -4.
  2. The remainder must satisfy (-3) * 2 + r = -7, so r = -1.
  3. C99 guarantees exactly this behaviour, so the program prints -3 -1.

Answer: -3 -1.

The idea

C truncates towards zero, so the remainder carries the sign of the dividend. Python floors instead, which is why the same two expressions give -4 and 1 there.

Shortcut. C99 truncates towards zero, so the quotient is −3 and the remainder takes the dividend's sign; check (−3) × 2 + (−1) = −7.

Common trap. "-4 1" carries over Python's floor rules, which round −3.5 down to −4 and give a remainder with the divisor's sign.

Dividing a negative number — Aptitude Question

Dividing a negative number: What does this C program print? Assume a C99 or later compiler. Answer and worked solution on CodeKairo.

Question

What does this C program print? Assume a C99 or later compiler.

#include <stdio.h>

int main(void) {
    printf("%d %d", -7 / 2, -7 % 2);
    return 0;
}

Options

  1. -4 -1
  2. -4 1
  3. -3 -1
  4. -3 1
Show the answer and the worked solution

Correct answer: C. -3 -1

Worked solution

  1. -7 / 2 is -3.5 truncated towards zero, which gives -3, not -4.
  2. The remainder must satisfy (-3) * 2 + r = -7, so r = -1.
  3. C99 guarantees exactly this behaviour, so the program prints -3 -1.

Answer: -3 -1.

The idea

C truncates towards zero, so the remainder carries the sign of the dividend. Python floors instead, which is why the same two expressions give -4 and 1 there.

Shortcut. C99 truncates towards zero, so the quotient is −3 and the remainder takes the dividend's sign; check (−3) × 2 + (−1) = −7.

Common trap. "-4 1" carries over Python's floor rules, which round −3.5 down to −4 and give a remainder with the divisor's sign.

All Programming Fundamentals questions · placement mock tests