Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Operators  ›  Lesson

Arithmetic Operators

Arithmetic 12 minC's arithmetic operators follow normal precedence, integer division truncates toward zero, and % gives the remainder with the sign of the left operand.

Arithmetic Operators

The logger stores 21.5 degrees as 215, and the display needs "21" and "5" separately. Two operators do it in one line each, but only if you know exactly how C divides whole numbers, including negative ones.

The rule

Integer division drops the fraction; % keeps what was dropped.

C's arithmetic operators:

Operator Meaning Example Result
+ - add, subtract 215 - 12 203
* multiply 21 * 10 210
/ divide 215 / 10 21 (both int)
% remainder (integers only) 215 % 10 5

The rules that matter:

  • Precedence: *, / and % bind tighter than + and -, and operators of equal rank run left to right. 2 + 3 * 4 is 14.
  • Integer division truncates toward zero (guaranteed since C99): 7 / 2 is 3 and -7 / 2 is -3.
  • % takes the sign of the left operand: -7 % 2 is -1. The two always fit together: (a / b) * b + a % b == a.
  • % works only on integer types. For floating-point remainders use fmod from <math.h>.
  • Integer division or remainder by zero is undefined behaviour. Check the divisor first.

The increment and decrement operators add or subtract 1. ++n changes n and gives the new value; n++ changes n but gives the old value:

int n = 5;
int a = n++;   /* a is 5, n is 6 */
int b = ++n;   /* n is 7, b is 7 */

Never modify the same variable twice in one expression without a sequence point between, as in n = n++ + 1; or i++ + i++. That is undefined behaviour, not a puzzle with a right answer.

The shortcut

Split every integer division into quotient and remainder, then check them with the identity quotient * divisor + remainder == original. If the check fails, you have mis-remembered a sign.

Splitting the reading -37 (that is -3.7 degrees)Step 1 of 4
  1. Quotient

    -37 / 10 truncates toward zero: -3.

Drills

Answer fast — trust the rule.

quick drill

What is 17 / 5?

quick drill

What is 17 % 5?

quick drill

What is -17 % 5?

quick drill

What is 2 + 3 * 4 % 5?

quick drill

After int n = 5; int m = n++ * 2;, what are m and n?

Remember

  • Integer division drops the fraction; % keeps what was dropped, with the sign of the left operand.
  • Shortcut: check with quotient * divisor + remainder == original.
  • Trap: dividing by zero, or changing one variable twice in one expression, is undefined behaviour.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainTenths to degrees

The logger stores 215 for 21.5 degrees. Explain how / and % split the reading into 21 and 5, what goes wrong with a reading of -37 if you print them as "%d.%d", and a better way to print it.