Exercise 2
–`do...while'
The structure of the `while' loop is
while (test)
{
// do something
}
The structure of the do...while loop is
do
{
// do something
} while (test);
In the latter case, the loop must be executed at least
once, because the test is not carried out until after the loop.
Consider the following section of program. It is intended
to present the user with a menu. The user makes a selection (getMenuCommand()) and the program carries out the command (doMenuCommand()). If the command was `exit' (assume EXIT is a constant) the loop stops.
do
{
int menuCommand =
getMenuCommand();
doMenuCommand(menCommand);
} while (menuCommand
!= EXIT);
We want the body of the loop to execute at least once, so do...while is appropriate in that it has the maximum
expressive power. However, the same effect could be achieved using for and while loops.
Rewrite the loop using both these methods. Hint: you will need to use a variable, probably
boolean, to control the loop.
Answer
Back
to content
Back to
top
RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights
reserved.
webmaster@globalcampus.com.eg
|