Programming in C

(Barry) #1

50 Chapter 5 Program Looping


Because addition by 1 is such a common operation in programs, a special operator was
created solely for this purpose.Therefore, the expression ++nis equivalent to the expres-
sion n = n + 1. Although it might appear that n = n + 1is more readable, you will
soon become familiar with the function of this operator and will even learn to appreci-
ate its succinctness.
Of course, no programming language that offered an increment operator to add 1
would be complete without a corresponding operator to subtract 1.The name of this
operator is the decrement operatorand is symbolized by the double minus sign. So, an
expression in C that reads
bean_counter = bean_counter - 1
can be equivalently expressed using the decrement operator as
--bean_counter
Some programmers prefer to put the ++or --after the variable name, as in n++or
bean_counter--.This is acceptable, and is a matter of personal preference.

Aligning Output


One slightly disturbing thing that you might have noticed in Program 5.3’s output is the
fact that the 10th triangular number does not quite line up under the previous triangular
numbers.This is because the number 10 takes up two print positions, whereas the previ-
ous values of n,1 through 9, took up only one print position.Therefore, the value 55 is
effectively “pushed over” one extra position in the display.This minor annoyance can be
corrected if you substitute the following printfstatement in place of the corresponding
statement from Program 5.3.
printf ("%2i %i\n", n, triangularNumber);
To ver ify that this change does the trick, here is the output from the modified program
(we’ll call it Program 5.3A).

Program 5.3A Output
TABLE OF TRIANGULAR NUMBERS

n Sum from 1 to n
--- ---------------
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
Free download pdf