// to C, 3rd Edition
// File Chapter10ex1.c
/* This program increases a counter from 1 to 5, printing updates
and then counts it back down to 1. */
#include <stdio.h>
main()
{
int ctr = 0;
ctr = ctr + 1; // increases counter to 1
printf("Counter is at %d.\n", ctr);
ctr = ctr + 1; // increases counter to 2
printf("Counter is at %d.\n", ctr);
ctr = ctr + 1; // increases counter to 3
printf("Counter is at %d.\n", ctr);
ctr = ctr + 1; // increases counter to 4
printf("Counter is at %d.\n", ctr);
ctr = ctr + 1; // increases counter to 5
printf("Counter is at %d.\n", ctr);
ctr = ctr - 1; // decreases counter to 4
printf("Counter is at %d.\n", ctr);
ctr = ctr - 1; // decreases counter to 3
printf("Counter is at %d.\n", ctr);
ctr = ctr - 1; // decreases counter to 2
printf("Counter is at %d.\n", ctr);
ctr = ctr - 1; // decreases counter to 1
printf("Counter is at %d.\n", ctr);
return 0;
}
The following lines show the program’s output. Notice that ctr keeps increasing (in computer lingo,
it’s called incrementing) by 1 with each assignment statement until it reaches 5 , and then decreases
(called decrementing) by 1 with each assignment statement until it reaches 1. (Subtracting from a
counter would come in handy if you needed to decrease totals from inventories as products are sold.)
Counter is at 1.
Counter is at 2.
Counter is at 3.
Counter is at 4.
Counter is at 5.
Counter is at 4.
Counter is at 3.
Counter is at 2.
Counter is at 1.
Other times, you’ll need to update a variable by adding to a total or by adjusting it in some way. The
following assignment statement increases the variable sales by 25 percent:
Click here to view code image
sales = sales * 1.25; /* Increases sales by 25 percent */