Next: Comparison Operators Up: Basic C Programming Previous: Printing Out and Inputting Variables

Arithmetic Operations

As well as the standard arithmetic operators (+ - * /) found in most languages, C provides some more operators. There are some notable differences with other languages!

Assignment is = i.e. i=4; ch = 'y';

Increment ++, Decrement -- . Both are more efficient than their long hand equivalents, for example:- x++ is faster than x=x+1.

The ++ and -- operators can be either in post-fixed or pre-fixed. With pre-fixed the value is computed before the expression is evaluated whereas with post-fixed the value is computed after the expression is evaluated.

In the example below, ++z is pre-fixed and the w-- is post-fixed:

int x,y,w;

main()

This would be equivalent to:

int x,y,w;

main()

The % (modulus) operator only works with integers.

Division / is for both integer and float division. So be careful !

The answer to: x=3/2 is 1 even if x is declared a float!!

RULE: If both arguments of / are integer then do integer division.

So make sure you do this. The correct (for division) answer to the above is x=3.0/2 or x=3/2.0 or (even better) x=3.0/2.0.

There is also a convenient shorthand way to express computations in C.

It is very common to have expressions like: i=i+3 or x=x*(y+2)

This can written in C (generally) in a shorthand form like this:

expr1 op = expr2

which is equivalent to (but more efficient than):

expr1 = expr1 op expr2

So we can rewrite i=i+3 as i+= 3

and x=x+(y+2) as x* =y+2.

NOTE: x*=y+2 means x=x*(y+2) and NOT x=x*y+2!


drago@scri.fsu.edu
Jan. 1997