Arithmetic - Types of Operators

Chapter chap3 section 5

The operators "+" and "-" are called additive operators. The operators "*" and "/" are called multiplicative operators. There is one further multiplicative operator, this is "%" which is a remaindering or modulo operator. The value of

value1 % value2

is the remainder when value1 is divided by value2. It is guaranteed by the ANSI standard that the value of an expression such as

(a/b)*b + a%b

is equal to a. A programming example is in order.

main()
{
	int	x=20,y=6;
	printf("The quotient of %d divided by %d is %d\n",
			x,y,x/y);
	printf("The remainder of %d divided by %d is %d\n",
			x,y,x%y);
}
resulting in the output
The quotient of 20 divided by 6 is 3
The remainder of 20 divided by 6 is 2
The behaviour of both the "/" and "%" operators is, officially, undefined, if the second operator is zero.

All the multiplicative operators associate or group left-to-right and have the same precedence. This is demonstrated by considering the output of the following program.

main()
{
	int	x=20;
	int	y=3;
	int	z=5;
	printf("Value of \"%d/%d*%d\" is %d\n",
		x,y,z,x/y*z);
	printf("Value of \"%d/%d/%d\" is %d\n",
		x,y,z,x/y/z);
	printf("Value of \"%d%%%d*%d\" is %d\n",
		x,y,z,x%y*z);
}
which produced the output
Value of "20/3*5" is 30
Value of "20/3/5" is 1
Value of "20%3*5" is 10

In the first line of output "20/3" is first calculated giving 6 by the rules of integer division, the result is multiplied by 5. In the second line of output the value of "20/3" is calculated and the result is divided by 5 giving the value 1. In the final line of output the value of "20%3" is calculated, its value is 2 which is then multiplied by 5.

The C programming language has a particularly large set of operators compared with many other programming languages, it is important to keep track of the precedence and grouping of operators when writing complicated expressions.


Assignment Operators