It is possible to convert back-and-forth between the
while
and
for
loops in a fairly mechanical manner.
For example a while loop like this:
1 2 3 4 5
|
while (numDays < 1)
{
cout << "Please enter valid number of days\n";
cin >> numDays;
}
|
could become an equivalent for loop:
1 2 3 4 5
|
for ( ; numDays < 1; )
{
cout << "Please enter valid number of days\n";
cin >> numDays;
}
|
Notice the semicolons in the
for
statement:
for ( ; numDays < 1; )
.
Here, the first and last parts are left blank. Only the middle part which is the loop condition is used.
It is possible to omit the condition too, giving an empty for statement:
for (;;)
. That is valid, it means repeat forever, effectively the same as
while (true)
.
To convert a for loop to a while loop, can be done like this:
Original loop.
1 2 3 4 5
|
for (int i = 1; i <= numDays; i++)
{
cout << "Day " << i << " you earned " << sum << "pennies\n";
sum = pow(2, i);
}
|
Reposition the first and last parts of the for statement:
1 2 3 4 5 6 7
|
int i = 1;
for (; i <= numDays; )
{
cout << "Day " << i << " you earned " << sum << "pennies\n";
sum = pow(2, i);
i++;
}
|
Change
for
to
while
and omit the semicolons
1 2 3 4 5 6 7
|
int i = 1;
while (i <= numDays)
{
cout << "Day " << i << " you earned " << sum << "pennies\n";
sum = pow(2, i);
i++;
}
|
A more detailed description is given in the tutorial page:
http://www.cplusplus.com/doc/tutorial/control/