Now that we've gone over making choices in a program, it's time to think about
making a program that can loop. Let's start with the while loop. You
may remember this from Pascal, where you would say something like:
a := 0;
while (a < 20) do
a := a + 1;
This would of course loop 20 times, each time incrementing a by one.
C++, in a similar manner as with if , removes some of the fat and makes
you add parentheses to the statement used to determine if the loop should
keep going (called the conditional statement). Take a look at the above
statement in C++ form:
a = 0;
while (a < 20)
a = a + 1;
Notice how the conditional statement, "a < 20 ", is surrounded
in perentheses, just like you had to do with the if statement. Also, note
that the do keyword was removed. You may be noticing a trend away from
Pascal's English-like syntax into a more cryptic, terse programming language.
This is very much the case.
Let's try using while in a program!
void main(void)
{
float taco;
int chimichanga; / mmm...chimichangas..
taco = 22.2;
chimichanga = 5524;
/* This next part will keep adding
10 to taco until taco is no longer
less than chimichanga */
while (taco < chimichanga)
taco = taco + 10;
}
The above program is pretty simple -- just two variables that get assigned two
values and then are used in a while loop. You should note that, like Pascal,
the order of a while loop is always:
- Test the conditional statement that controls the loop.
- If it's TRUE (ie, non-zero), execute the statement under the conditional.
- If not, exit the while loop.
- If we haven't exited the while loop yet, start back on step one.
|