Friday, July 11, 2008

5.2 "For", "While" and "Do ... While" Loops

We have already been introduced to "for" loops in Lecture 2 and to "while" loops in Lecture 4. Notice that any "for" loop can be re-written as a "while" loop. For example, Program 2.2.2 from Lecture 2, which was: #include
using namespace std;
int main()
{
int number;
char character;

for (number = 32 ; number <= 126 ; number = number + 1) {

character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";
cout << number << " in the computer.\n";
}
return 0;
}
Program 2.2.2
can be written equivalently as #include
using namespace std;

int main()
{
int number;
char character;

number = 32;
while (number <= 126)
{
character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";
cout << number << " in the computer.\n";
number++;
}
return 0;
}
Program 5.2.1
Moreover, any "while" loop can be trivially re-written as a "for" loop - we could for example replace the line while (number <= 126)
with the line for ( ; number <= 126 ; )
in the program above.
There is a third kind of "loop" statement in C++ called a "do ... while" loop. This differs from "for" and "while" loops in that the statement(s) inside the {} braces are always executed once, before the repetition condition is even checked. "Do ... while" loops are useful, for example, to ensure that the program user's keyboard input is of the correct format: ...
...
do
{
cout << "Enter the candidate's score: ";
cin >> candidate_score;
if (candidate_score > 100 candidate_score < 0)
cout << "Score must be between 0 and 100.\n";
}
while (candidate_score > 100 candidate_score < 0);
...
...
Program Fragment 5.2.2a
This avoids the need to repeat the input prompt and statement, which would be necessary in the equivalent "while" loop: ...
...
cout << "Enter the candidate's score: ";
cin >> candidate_score;
while (candidate_score > 100 candidate_score < 0)
{
cout << "Score must be between 0 and 100.\n";
cout << "Enter the candidate's score: ";
cin >> candidate_score;
}
...
...
Program Fragment 5.2.2b

0 comments: