C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
Note

Although the printf() statement asks for the number to be between 1 and 100, users
actually can enter any integer. If you use 362880 , you’ll find that it is divisible by all
eight single-digit integers.

The Small-Change Operators: ++ and --


Although the conditional operator works on three arguments, the increment and decrement operators
work on only one. The increment operator adds 1 to a variable, and the decrement operator subtracts
1 from a variable. That’s it. ‘Nuff said. Almost....


Incrementing and decrementing variables are things you would need to do if you were counting items
(such as the number of customers who shopped in your store yesterday) or counting down (such as
removing items from an inventory as people buy them). In Chapter 10, “Powering Up Your Variables
with Assignments and Expressions,” you read how to increment and decrement variables using
compound operators. Here, you learn two operators that can more easily do the same. The increment
operator is ++, and the decrement operator is --. If you want to add 1 to the variable count, here’s
how you do it:


count++;

You also can do this:


++count;

The decrement operator does the same thing, except that the 1 is subtracted from the variable. You can
do this:


count--;

You also can do this:


--count;

As you can see, the operators can go on either side of the variable. If the operator is on the left, it’s
called a prefix increment or prefix decrement operator. If the operator is on the right, it’s known as a
postfix increment or postfix decrement operator.


Note

Never apply an increment or decrement operator to a literal constant or an expression.
Only variables can be incremented or decremented. You will never see this:
--14; /* Don't do this! */
Free download pdf