Programming in C

(Barry) #1

54 Chapter 5 Program Looping


What triangular number do you want? 75
Triangular number 75 is 2850

What triangular number do you want? 83
Triangular number 83 is 3486

The program consists of two levels of forstatements.The outermost forstatement
for ( counter = 1; counter <= 5; ++counter )
specifies that the program loop is to be executed precisely five times.This can be seen
because the value of counteris initially set to 1 and is incremented by 1 untilit is no
longer less than or equal to 5 (in other words, until it reaches 6 ).
Unlike the previous program examples, the variable counteris not used anywhere
else within the program. Its function is solely as a loop counter in the forstatement.
Nevertheless, because it isa variable, it must be declared in the program.
The program loop actually consists of all the remaining program statements, as indi-
cated by the braces. It might be easier for you to comprehend the way this program
operates if you conceptualize it as follows:
For 5 times
{
Get the number from the user.

Calculate the requested triangular number.

Display the result.
}
The portion of the loop referred to in the preceding as Calculate the requested triangular
numberactually consists of setting the value of the variable triangularNumberto 0 plus
theforloop that calculates the triangular number.Thus, you see that you have a for
statement that is actually contained withinanother forstatement.This is perfectly valid
in C, and nesting can continue even further up to 127 levels!
The proper use of indentation becomes even more critical when dealing with more
sophisticated program constructs, such as nested forstatements.You can easily determine
which statements are contained within each forstatement. (To see how unreadable a
program can be if correct attention isn’t paid to formatting, see exercise 5 at the end of
this chapter.)

forLoop Variants


Some syntactic variations are permitted in forming the forloop.When writing a for
loop, you might discover that you have more than one variable that you want to initial-
ize before the loop begins or more than one expression that you want to evaluate each
time through the loop.

Program 5.5 Continued
Free download pdf