Programming in C

(Barry) #1
The forStatement 49

constitutes the body of the program loop. But what happens if you want to repetitively
execute not just a single program statement, but a group of program statements? This can
be accomplished by enclosing all such program statements within a pair of braces.The
system then treats this group or blockof statements as a single entity. In general, any place
in a C program that a single statement is permitted, a block of statements can be used,
provided that you remember to enclose the block within a pair of braces.
Therefore, in Program 5.3, both the expression that adds ninto the value of
triangularNumberand the printfstatement that immediately follows constitute the
body of the program loop. Pay particular attention to the way the program statements
are indented. It is easy to determine which statements form part of the forloop.You
should also note that programmers use different coding styles. Some prefer to type the
loop this way:


for ( n = 1; n <= 10; ++n )
{
triangularNumber += n;
printf (" %i %i\n", n, triangularNumber);
}


Here, the opening brace is placed on the next line after the for.This is strictly a matter
of taste and has no effect on the program.
The next triangular number is calculated by simply adding the value of nto the pre-
vious triangular number.This time, the “plus equals” operator is used, which was intro-
duced in Chapter 4, “Variables, Data Types, and Arithmetic Expressions.” Recall that the
expression


triangularNumber += n;


is equivalent to the expression


triangularNumber = triangularNumber + n;


The first time through the forloop, the “previous” triangular number is 0 , so the new
val ue of triangularNumberwhen nis equal to 1 is simply the value of n, or 1 .The val-
ues of nand triangularNumberare then displayed, with an appropriate number of blank
spaces inserted in the format string to ensure that the values of the two variables line up
under the appropriate column headings.
Because the body of the loop has now been executed, the looping expression is eval-
uated next.The expression in this forstatement appears a bit strange, however. It seems
like you made a typographical mistake and meant to insert the expression


n = n + 1


instead of the funny-looking expression


++n


The expression ++nis actually a perfectly valid C expression. It introduces you to a new
(and rather unique) operator in the C programming language—the increment operator.The
function of the double plus sign—or the increment operator—is to add 1 to its operand.

Free download pdf