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

(Romina) #1
TABLE 10.1 Compound Assignment Operators

This second sample program produces the exact same result as the first program in the chapter; it just
uses compound operators to increase and decrease the counter. In addition, some of the compound
operator statements are located right in the printf() statements to show you that you can combine
the two lines of code into one.


Click here to view code image


// Example program #2 from Chapter 10 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter10ex2.c
/* This program also increases a counter from 1 to 5, printing updates
and then counts it back down to 1. However, it uses compound
operators*/
#include <stdio.h>
main()
{
int ctr = 0;
ctr += 1; // increases counter to 1
printf("Counter is at %d.\n", ctr);
ctr += 1; // increases counter to 2
printf("Counter is at %d.\n", ctr);
printf("Counter is at %d.\n", ctr += 1);
ctr += 1; // increases counter to 4
printf("Counter is at %d.\n", ctr);
printf("Counter is at %d.\n", ctr += 1);
ctr -= 1; // decreases counter to 4
printf("Counter is at %d.\n", ctr);
printf("Counter is at %d.\n", ctr -= 1);
printf("Counter is at %d.\n", ctr -= 1);
printf("Counter is at %d.\n", ctr -= 1);
return 0;
}

Watch That Order!


Look at the order of operators table in the previous chapter (Table 9.1) and locate the compound
assignment operators. You’ll see that they have very low precedence. The +=, for instance, is several

Free download pdf