Reputation: 198
Using the conversion from the for-loop to the while-loop in the example below, can // fixed block
be any valid block of code given that you can add any other blocks of code before or after it in the while-loop?
for (int i = 0; i < 10; i++) {
// fixed block
}
int i = 0;
while (i < 10) {
// any block
// fixed block
// any block
}
To show that the answer may not trivially be "yes", I thought of a block of code that may be a counter example:
for (int i = 0; i < 10; i++) {
i = i * 2;
if (1 < 2) {
print(i);
continue;
}
}
The if-statement is there so that in the while-loop you can add a block of code after the continue;
statement without getting a possible compiler error/warning. The output of the for-loop is 0, 2, 6 and 14. Adding i++;
either before or after the fixed block of code in the while-loop doesn't work, showing that the answer may not be trivial.
Upvotes: 0
Views: 5783
Reputation: 7102
Sure they can, just set up a similar exit condition. I don't think the inverse (while
loops converted to for
loops) is true though.
Also, yes, you're blocks of code will function the same in both cases, if the code is valid (logically and syntactically), then yes it will work.
Upvotes: 1