|
|
|
|
|
|
|
num1Valid = TRUE;
num2Valid = TRUE;
loopCount = 1;
while (num1Valid && num2Valid && loopCount <= 10)
{
cin >> numl;
if ( !cin || numl >= 100)
num1Valid = FALSE;
else
{
cin >> num2;
if ( !cin || num2 <= 50)
num2Valid = FALSE;
else
{
cout << sqrt(float(num1 + num2)) << endl;
loopCount++;
}
}
} |
|
|
|
|
|
|
|
|
One could argue that the first version is easier to follow and understand than this second version. The primary task of the loop bodycomputing the square root of the sum of the numbersis more prominent in the first version. In the second version, the computation is obscured by being buried within nested Ifs. The second version also has a more complicated control flow. |
|
|
|
|
|
|
|
|
The disadvantage of using break with loops is that it can become a crutch for those who are too impatient to think carefully about loop design. It's easy to overuse (and abuse) the technique. Here's an example, printing the integers 1 through 5: |
|
|
|
|
|
|
|
|
i = 1;
while (TRUE)
{
cout << i;
if (i == 5)
break;
i++;
} |
|
|
|
|
|
|
|
|
There is no real justification for setting up the loop this way. Conceptually, it is a pure count-controlled loop, and a simple For loop does the job: |
|
|
|
|
|
|
|
|
for (i = 1; i <= 5; i++)
cout << i; |
|
|
|
|
|