Performing Arithmetic

While the principles of arithmetic in C are exactly like those you learned in school, the actual results are more complex because of how C works with the different number types. For this reason, choosing the appropriate data type depends not only on the possible values it might store but also on how it will be used.

The standard operators for performing arithmetic are

  • +, for addition

  • -, for subtraction

  • *, for multiplication

  • /, for division

  • %, for modulus (finding the remainder of a division)

Using these operators, here are some sample calculations:

int a = 3;
int b = 2;
int c;
c = a + b; /* 5 */
c = a - b; /* 1 */
c = b - a; /* -1 */
c = a * b; /* 6 */
c = a / b; /* 1, not 1.5! */
c = a % b; /* 1 */

When you divide one integer ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.