Programming in C

(Barry) #1
Working with Arithmetic Expressions 35

results in the multiplication of –aby b. Once again, in Appendix A you will find a table
summarizing the various operators and their precedences.


The Modulus Operator


The next arithmetic to be presented in this chapter is the modulus operator, which is
symbolized by the percent sign (%).Try to determine how this operator works by analyz-
ing Program 4.4.


Program 4.4 Illustrating the Modulus Operator


// The modulus operator


#include <stdio.h>


int main (void)
{
int a = 25, b = 5, c = 10, d = 7;


printf ("a %% b = %i\n", a % b);
printf ("a %% c = %i\n", a % c);
printf ("a %% d = %i\n", a % d);
printf ("a / d * d + a %% d = %i\n",
a / d * d + a % d);

return 0;
}


Program 4.4 Output


a % b = 0
a % c = 5
a % d = 4
a / d * d + a % d = 25


The first statement inside maindefines and initializes the variables a,b,c,and din a sin-
gle statement.
As you know, printfuses the character that immediately follows the percent sign to
determine how to print the next argument. However, if it is another percent sign that
follows, the printfroutine takes this as an indication that you really intend to display a
percent sign and inserts one at the appropriate place in the program’s output.
You are correct if you concluded that the function of the modulus operator %is to
give the remainder of the first value divided by the second value. In the first example,
the remainder after 25 is divided by 5 and is displayed as 0. If you divide 25 by 10, you
get a remainder of 5, as verified by the second line of output. Dividing 25 by 7 gives a
remainder of 4, as shown in the third output line.

Free download pdf