6.16 The equivalence of for and while loops, mentioned in Example 6.64, is not p
ID: 3731539 • Letter: 6
Question
6.16 The equivalence of for and while loops, mentioned in Example 6.64, is not precise. Give an example in which it breaks down. Hint: think about the continue statement. A much simpler form of combination loop appears in C and its successors. Semantically, the C for loop is logically controlled. It was designed, however, to make enumeration easy. Our Modula-2 example EXAMPLE 6.64 Combination (for) loop in C FOR i := first TO last BY step DO END would usually be written in C as for (i = first; iExplanation / Answer
From given data:
They are breaks down only when i == last. But if there is in ... the code you are using break statement then also it breaks.
For example:
If (i==2)
breaks;
This line breaks both loops.
Note: if you modify the' i ' value in between these loops and' i ' exceed the last then loops are breaks n vote.
However, if you declare the loop like so:
For (int i = first; i <= last; i+=step)
You manage to keep i within the scope of the loop, instead of letting it escape to the rest of the code.
Also, in a while loop, you have the variable declaration, the condition, and the increment in 3 different places. With the for loop, it is all in one convenient, easy-to-read place.
Last thought:
One more important note. There is a semantic difference between the two. While loops, in general, are meant to have an indefinite number of iterations. (ie. until the file has been read..no matter how many lines are in it), and for loops should have a more definite number of iterations.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.