First Steps in Programming - Try It Out: Division and the Modulus Operator
(Page 5 of 13 )
Suppose you have a jar of 45 cookies and a group of 7 children. You’ll share out the cookies equally among the children and work out how many each child has. Then you’ll work out how many cookies are left over.
/* Program 2.6 Cookies and kids */
#include <stdio.h>
void main()
{
int cookies = 45; /* Number of cookies in
the jar */
int children = 7; /* Number of children
*/
int cookies_per_child = 0; /* Number of cookies per
child */
int cookies_left_over = 0; /* Number of cookies left
over */
/* Calculate how many cookies each child gets when they
are divided up */
cookies_per_child = cookies/children; /* Number of
cookies per child */
printf("You have %d children and %d cookies", children,
cookies);
printf("\nGive each childcookies.",cookies_per_child);
/* Calculate how many cookies are left over */
cookies_left_over = cookies%children;
printf("\nThere are %d cookies left over.\n",
cookies_left_over);
}
When you run this program you’ll get this output:
======================================================
You have 7 children and 45 cookies
Give each child 6 cookies.
There are 3 cookies left over.
============================================================
HOW IT WORKS
Let’s go through this program step by step. Four integer variables, cookies, children, cookies_per_child, and cookies_left_over, are declared and initialized with the following statements:
int cookies = 45; /* Number of cookies in the jar */
int children = 7; /* Number of children */
int cookies_per_child = 0;
/* Number of cookies per child */
int cookies_left_over = 0;
/* Number of cookies left over */
The number of cookies is divided by the number of children by using the division operator / to produce the number of cookies given to each child: cookies_per_child = cookies/children; /* Number of
cookies per child */
The next two statements output what is happening, including the value stored in cookies_per_child:
printf("You have %d children and %d cookies", children,
cookies);
printf("\nGive each child %d cookies.",cookies_per_child);
You can see from the output that cookies_per_child has the value 6. This is because the division operator always produces an integer result when the operands are integers. The result of dividing 45 by 7 is 6, with a remainder of 3.
You calculate the remainder in the next statement by using the modulus operator:
cookies_left_over = cookies%children;
The expression to the right of the assignment operator calculates the remainder that results when the value of cookies is divided by the value of children.
Finally, you output the reminder in the last statement:
printf("\nThere are %d cookies left over.\n",
cookies_left_over);
More on Division with Integers Let’s look at the result of using the division and modulus operators where one or the other of the operands is negative. With division, if the operands have different signs, the result will be negative. Thus, the expression–45/7 produces the same result as the expression 45/–7, which is –6. If the operands in a division are of the same sign, then the result is positive. Thus, 45/7 produces the same result as –45/–7, which is 6.
With the modulus operator, the sign of the result is always the same as the sign of the left operand. Thus, 45%–7 results in the value 3, whereas –45%7 results in the value –3.
Unary Operators
The operators that you’ve dealt with so far have been binary operators. These operators are called binary operators because they operate on two data items. Incidentally, the items of data that an operator applies to are called operands. For example, the multiplication is a binary operator because it has two operands and the effect is to multiply one operand value by the other. However, there are some operators that are unary, meaning that they need only one operand. You’ll see more examples later, but for now you’ll just take a look at the single most common unary operator.
The Unary Minus Operator You’ll find the unary operator very useful in more complicated programs. It makes whatever is positive negative, and vice versa. You might not immediately realize when you would use this, but think about keeping track of your bank account. Say you have $200 in the bank. You record what happens to this money in a book with two columns, one for money that you pay out and another for money that you receive. One column is your expenditure (negative) and the other is your revenue (positive).
You decide to buy a CD for $50 and a book for $25. If all goes well, when you compare the initial value in the bank and subtract the expenditure ($75), you should end up with what’s left. Table 2-2 shows how these entries could typically be recorded.
Table 2-2. Recording Revenues and Expenditures
Entry Revenue Expenditure Bank Balance Check received $200 CD -Book -Closing balance $200 --$200 $50 $150 $25 $125 $75 $125
If these numbers were stored in variables, you could enter both the revenue and expenditure as positive values and only make the number negative when you wanted to calculate how much was left. You could do this by simply placing a minus sign (-) in front of the variable name.
To output the amount you had spent as a negative value, you could write
int expenditure = 75;
printf("Your balance has changed by %d.", -expenditure);
This would result in the output
======================================================== Your balance has changed by -75.
===============================================================
The minus sign will remind you that you’ve spent this money rather than gained it. Note that the expression-expenditure doesn’t change the value stored in expenditure— it’s still 75. The value of the expressionis –75.
The unary minus operator in the expression-expenditure specifies an action. Instructions must be executed in your program to evaluate this. This is subtly different from when you use the minus operator when you write a negative number such as –75 or –1.25. In this case, the minus doesn’t result in an action and no instructions need to be executed when your program is running. It simply instructs the compiler to create the appropriate negative constant in your program.
This article is excerpted from Beginning C by Ivor Horton (Apress, 2004; ISBN 1590592530). Check it out at your favorite bookstore today. Buy this book now. |
Next: Variables and Memory >>
More Code Examples Articles
More By Apress Publishing