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

~75s

Precedence of the arithmetic operators

What does this C program print?

#include <stdio.h>

int main(void) {
    int r = 10 - 4 * 2 + 18 / 3 % 4;
    printf("%d", r);
    return 0;
}
Show the answer and the worked solution

Correct answer: B.

4

Worked solution

  1. The high-precedence operators go first: 4 * 2 = 8 and 18 / 3 = 6.
  2. % has the same precedence as / and associates left to right, so the 6 is then reduced: 6 % 4 = 2.
  3. What remains is 10 - 8 + 2, evaluated left to right: 2 + 2 = 4.

Answer: 4.

The idea

Remainder is not below division in the precedence table, it is beside it, so left-to-right associativity decides the order. Rewriting the line with explicit brackets before evaluating anything is the safe habit.

Shortcut. Only 18 / 3 % 4 needs thought: / and % share a level and go left to right, so it is 6 % 4 = 2, and the line is 10 − 8 + 2 = 4.

Common trap. 8 comes from doing % before /: 3 % 4 = 3, then 18 / 3 = 6, giving 10 − 8 + 6 = 8.

Precedence of the arithmetic operators — Aptitude Question

Precedence of the arithmetic operators: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

int main(void) {
    int r = 10 - 4 * 2 + 18 / 3 % 4;
    printf("%d", r);
    return 0;
}

Options

  1. 2
  2. 4
  3. 6
  4. 8
Show the answer and the worked solution

Correct answer: B. 4

Worked solution

  1. The high-precedence operators go first: 4 * 2 = 8 and 18 / 3 = 6.
  2. % has the same precedence as / and associates left to right, so the 6 is then reduced: 6 % 4 = 2.
  3. What remains is 10 - 8 + 2, evaluated left to right: 2 + 2 = 4.

Answer: 4.

The idea

Remainder is not below division in the precedence table, it is beside it, so left-to-right associativity decides the order. Rewriting the line with explicit brackets before evaluating anything is the safe habit.

Shortcut. Only 18 / 3 % 4 needs thought: / and % share a level and go left to right, so it is 6 % 4 = 2, and the line is 10 − 8 + 2 = 4.

Common trap. 8 comes from doing % before /: 3 % 4 = 3, then 18 / 3 = 6, giving 10 − 8 + 6 = 8.

All Programming Fundamentals questions · placement mock tests