Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 135 ยท Operators

Arithmetic Operators

Learn C's arithmetic operators + - * / %: integer division and truncation, remainders of negative numbers, division by zero, integer promotion and mixed types.

Arithmetic is the first thing most programs do: add up prices, average scores, convert seconds into minutes, find out whether a number is even. C gives you five binary arithmetic operators (+, -, *, / and %) and two unary ones (+ and -). They look exactly like school math, and most of the time they behave like it too.

The interesting part is where they don't. In C, 7 / 2 is 3, -7 % 3 is -1, adding two char values gives an int, and dividing an integer by zero isn't an error message but undefined behavior. This lesson explains each rule, why it exists, and the habits that keep your calculations correct.

The arithmetic operators

Operator Meaning Example Result
a + b addition 17 + 5 22
a - b subtraction 17 - 5 12
a * b multiplication 17 * 5 85
a / b division 17 / 5 3 (integers)
a % b remainder (modulo) 17 % 5 2
-a negation -17 -17
+a unary plus (promotes, otherwise no effect) +17 17

The usual math rules for order apply: *, / and % bind tighter than + and -, and operators of the same level are applied left to right. So 2 + 3 * 4 is 14, and 20 / 4 / 5 is (20 / 4) / 5, which is 1. Use parentheses whenever you want a different order, or when the order isn't obvious to a reader. The full table is in Operator Precedence.

C The five arithmetic operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice %% in the format string: because % starts a conversion in printf, you write it twice to print one percent sign (see Printing Output with printf).

Integer division throws away the fraction

When both operands of / are integers, the result is an integer too. C doesn't round: it truncates toward zero, simply dropping everything after the decimal point. 17 / 5 is 3, not 3.4, and -17 / 5 is -3, not -4. (C89 allowed either direction for negative numbers; C99 and later require truncation toward zero, and every modern compiler does it.)

The remainder operator % gives what's left over, and the two always fit together by this identity:

C
(a / b) * b + a % b == a      // true whenever a / b is defined

That identity decides the sign of the remainder: the result of % has the same sign as the left operand. So -17 % 5 is -2 and 17 % -5 is 2. The % operator works only on integer types; for floating-point remainders use fmod from the math library.

C Division and remainder with negative numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

To test whether a number is odd, write n % 2 != 0, not n % 2 == 1. For negative odd numbers such as -3, n % 2 is -1, so the second version quietly gets them wrong.

A remainder that never goes negative

Many tasks want a result in the range 0 to n - 1 even for negative inputs: wrapping an index around a circular buffer, finding the day of the week ten days before today, or rotating letters in a cipher. Since % can return a negative value, add n and take the remainder again:

C
int wrap(int i, int n) {
    return ((i % n) + n) % n;   // always 0 .. n-1 for n > 0
}

wrap(-3, 7) is 4, while plain -3 % 7 is -3.

Getting a real fraction

If you want 3.4 from 17 / 5, at least one operand must be a floating-point type. Then the other operand is converted too, and the division happens in floating point. You can write a floating literal (17.0 / 5) or cast one variable ((double)a / b), as covered in Type Conversions and Casts.

The classic mistake is converting after the integer division has already thrown away the fraction:

C Averages: convert before you divide

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

sum / count is 346 / 4, which is 86 in integer arithmetic. Storing that in a double gives 86.000000; the .5 is already gone. In the percentage lines, the order of operations also matters: 100 * 3 / 8 multiplies first (giving 37), while 3 / 8 * 100 would give 0.

Mixed types and integer promotion

C never does arithmetic directly on small types such as char, short, unsigned char or bool. Before the operation, each such operand is converted to int (or to unsigned int if int can't hold all its values). This is integer promotion. Then, if the two operands still have different types, the usual arithmetic conversions pick a common type: if either side is a double, both become double; otherwise the "bigger" integer type wins, and unsigned beats signed of the same rank.

Promotion has visible effects. The sum of two unsigned char values doesn't wrap at 255, and sizeof shows that the result is an int:

C Small types are promoted to int

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The digit - '0' trick works because the character codes for '0' to '9' are guaranteed to be consecutive; you'll use it whenever you parse numbers by hand (see Characters and ASCII).

The most surprising conversion happens when a negative int meets an unsigned int: the int is converted to unsigned, so -1 becomes a huge positive number. That trap mostly appears in comparisons, so it's covered in Comparison and Logical Operators.

Overflow: unsigned wraps, signed is undefined

Every integer type has a limited range. When a result doesn't fit:

  • Unsigned arithmetic wraps around modulo 2โฟ. UINT_MAX + 1u is 0, and 0u - 1u is UINT_MAX. This is well defined and often useful (hashes, checksums, counters).
  • Signed overflow is undefined behavior. INT_MAX + 1 isn't guaranteed to become INT_MIN; the optimizer assumes it never happens and may produce code that behaves in ways you can't predict.

The Integer Types and Type Limits lessons show how to check before you compute, including C23's ckd_add, ckd_sub and ckd_mul from <stdckdint.h>, which report overflow instead of causing it.

Division by zero

Dividing an integer by zero (with / or %) is undefined behavior. On most desktop systems the program crashes with a "floating point exception" signal, but nothing is promised, and an optimizer may even remove code around it. There's one more undefined case people forget: INT_MIN / -1 (and INT_MIN % -1), because the true answer, INT_MAX + 1, doesn't fit in an int.

Floating-point division by zero is different. On systems that follow IEEE 754 (practically all of them), 1.0 / 0.0 is positive infinity, -1.0 / 0.0 is negative infinity, and 0.0 / 0.0 is NaN, "not a number". The program keeps running, but the special values spread through later calculations (see Floating-Point Numbers).

C Guarding integer division

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The function reports success through its return value and hands the quotient back through a pointer parameter, a common C pattern you'll study in Pointers and Functions. The exact spelling of NaN in the output (nan or -nan) depends on the C library, so don't compare it as text; use isnan from <math.h>.

Practical habits

  • Decide early whether a calculation is integer or floating point, and make the type of at least one operand say so (2.0, (double)n).
  • Multiply before you divide in integer math when the product can't overflow: n * 100 / total keeps precision that n / total * 100 loses.
  • Check a divisor before dividing, especially when it comes from input.
  • Use unsigned types for bit patterns and wrapping counters, signed types for quantities that can be negative, and don't mix them in one expression.
  • For money, store whole cents in an integer type instead of a double, so that 0.1 + 0.2 problems never show up in a bill.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does printf("%d %d", -7 / 2, -7 % 2); print?

    Integer division truncates toward zero, so -7 / 2 is -3. The remainder has the sign of the left operand, and (-3) * 2 + (-1) == -7.
  2. 2. With int sum = 7, n = 2;, which expression evaluates to 3.5?

    Only the last version converts before dividing. The others do the integer division first (giving 3) and convert afterward.
  3. 3. With unsigned char a = 200, b = 100;, what is sizeof(a + b) on a system with 4-byte ints?

    Both operands are promoted to int before the addition, so the result is an int with the value 300.
  4. 4. Which of these has undefined behavior?

    The mathematical result, INT_MAX + 1, does not fit in an int, so the division overflows. 1.0 / 0.0 is infinity under IEEE 754, unsigned arithmetic wraps by definition, and -17 % 5 is simply -2.

Summary

  • C has + - * / % plus unary - and +; * / % bind tighter than + -, and equal levels group left to right.
  • Integer division truncates toward zero; % gives a remainder with the sign of the left operand, so (a / b) * b + a % b == a.
  • Use ((i % n) + n) % n for a remainder that is never negative, and n % 2 != 0 to test for odd numbers.
  • Convert to floating point before dividing: (double)sum / count.
  • Small integer types are promoted to int, and mixed operands are converted to a common type.
  • Unsigned overflow wraps; signed overflow, integer division by zero and INT_MIN / -1 are undefined behavior. Floating-point division by zero gives infinity or NaN.

Next: Assignment and Increment Operators