LearnFrenzy
Sign in Take a free test

Data Types · Predict the Output · Question 5

Integer division and % with negative numbers in C Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following C program on 64-bit Linux or macOS?

main.c
#include <stdio.h>

int main(void) {
    printf("%d %d %d %d\n", 7 / 2, -7 / 2, 7 % -3, -7 % 3);
    return 0;
}
  • A 3 -3 1 -1 Correct
  • B 3 -4 1 2
  • C 3 -3 -1 1
  • D 4 -4 1 -1
Correct Answer: Option A

Since C99, integer division truncates toward zero (−3.5 → −3), and a % b has the sign of a, so that (a / b) * b + a % b == a always holds.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links