Exercise – Complete a challenge activity to differentiate between do and while iteration statements
Code challenges will reinforce what you’ve learned and help you gain some confidence before continuing on.
Examine the difference between do and while statement iterations
As you have seen, C# supports four types of iteration statements: for
, foreach
, do-while
, and while
. Microsoft’s language reference documentation describes these statements as follows:
- The
for
statement: executes its body while a specified Boolean expression (the ‘condition’) evaluates to true. - The
foreach
statement: enumerates the elements of a collection and executes its body for each element of the collection. - The
do-while
statement: conditionally executes its body one or more times. - The
while
statement: conditionally executes its body zero or more times.
The for
and foreach
iterations seem to be clearly differentiated from each other and from the do-while
and while
iterations. The definitions for the do-while
and while
statements, however, appear to be quite similar. Knowing when to choose between a do-while
and a while
seems more arbitrary, and can even be a bit confusing. Some challenge projects may help to make the differences clear.
In this challenge, you’ll be presented with conditions for three separate coding projects. Each project will require you to implement an iteration code block using either a do-while
or a while
statement. You’ll need to evaluate the specified conditions in order to choose between the do-while
and while
statements. You can switch after you start if your first choice isn’t working out as well as you had hoped.
Note
The conditions for your coding project can be used to help you select between the do-while
and while
statements. What you know, or don’t know, about the Boolean expression that will be evaluated can sometimes help you to select between the do-while
and while
statements. In this challenge exercise, the project conditions include information that will be used to construct the Boolean expression.