Programming in C

(Barry) #1
The whileStatement 57

Program 5.6 Output


1
2
3
4
5


The program initially sets the value of countto 1 .Execution of the whileloop then
begins. Because the value of countis less than or equal to 5 ,the statement that immedi-
ately follows is executed.The braces serve to define both the printfstatement and the
statement that increments countas the body of the whileloop. From the output of the
program, you can readily observe that this loop is executed precisely 5 times, or until the
val ue of countreaches 6.
You might have realized from this program that you could have readily accomplished
the same task by using a forstatement. In fact, a forstatement can always be translated
into an equivalent whilestatement, and vice versa. For example, the general for
statement


for ( init_expression; loop_condition; loop_expression)
program statement


can be equivalently expressed in the form of a whilestatement as


init_expression;
while ( loop_condition) {
program statement
loop_expression;
}


After you become familiar with the use of the whilestatement, you will gain a better
feel as to when it seems more logical to use a whilestatement and when to use a for
statement.
In general, a loop executed a predetermined number of times is a prime candidate for
implementation as a forstatement. Also, if the initial expression, looping expression, and
looping condition all involve the same variable, the forstatement is probably the right
choice.
The next program provides another example of the use of the whilestatement.The
program computes the greatest common divisorof two integer values.The greatest common
divisor (gcd) of two integers is the largest integer value that evenly divides the two inte-
gers. For example, the gcdof 10 and 15 is 5 because 5 is the largest integer that evenly
divides both 10 and 15.

Free download pdf