(Removing break and continue) A criticism of the break and continue statements is that each is unstructured. These statements can always be replaced by structured statements. Describe in general how you’d remove any break statement from a loop in a program and replace it with some structured equivalent. [Hint: The break statement leaves a loop from within the body of the loop. Another way to leave is by failing the loop-continuation test. Consider using in the loop-continua- tion test a second test that indicates “early exit because of a ‘break’ condition.”] Use the technique you developed here to remove the break statement from the program of Fig. 4.11.
What will be an ideal response?
A loop can be written without a break by placing in the loop-continuation test a second test that indicates “early exit because of a ‘break’ condition.” In the body of the loop, the break statement can be replaced with a statement setting a bool variable (e.g., variable breakOut in the solution below) to true to indicate that a ‘break’ should occur. Any code appearing after the original break in the body of the loop can be placed in a control statement that causes the program to skip this code when the ‘break’ condition is true. Doing so causes the ‘break’ to be the final statement executed in the body of the loop. After the ‘break’ condition has been met, the new “early exit because of a ‘break’ condition” test in the loop-continuation test will be false, causing the loop to terminate. Alternatively, the break can be replaced by a statement that makes the original loop-continuation test immediately false, so that the loop terminates. Again, any code following the original break must be placed in a control statement that prevents it from executing when the ‘break’ condition is true.
```
// Terminating a loop without break.
#include
using namespace std;
int main()
{
int count; // control variable
// indicates whether 'break' condition has been reached
bool breakOut = false;
// indicate early exit because of 'break' condition;
// loop will end when breakOut has been set to true
for ( count = 1; ( count <= 10 ) && ( !breakOut ); count++ )
{
if ( count == 5 ) // 'break' condition
breakOut = true; // indicate that a break should occur
else
cout << count << " "; // skipped when 'break' condition is true
} // end for
cout << "\nBroke out of loop because loop-continuation test "
<< "( !breakOut ) failed" << endl;
} // end main
```
You might also like to view...
To view a list of apps already installed on a SharePoint site, visit the ________ page
A) SharePoint Store B) Home C) Documents D) Site Contents
What is wrong with the following code?
int f1( int x, int y) { x = y * y; return x; int f2( float a, float& b) { if(a < b) b = a; else a=b; return 0.0; } } a. Neither function should return a value b. Function definitions may not be nested c. Both parameters to f2 should be pass-by reference d. in f2, a can not be assigned b. e. nothing is wrong