April 4, 2019
while
to for
Rewrite the following while
(or do...while
) loops as for
loops.
for
to while
Rewrite the following for
loops as while
loops:
This lab’s pushing further is about two modifications of for
loops that are sometimes considered as bad design: used poorly, they can make the code harder to read, to debug, and sometimes makes it hard to follow the flow of control of your program. They are introduced because you may see them in your future, but, except for rare cases, should be avoided completely.
The exact structure of for
loops is actually more complex than what we discussed in class. It is
That is, there can be more than one initialization (but only if the variables all have the same datatype) and more than one update. That is, are legal statements like:
or
for (int x = 0, y = 12 ; x != y; x++, y--)
Console.WriteLine($"The difference between {x} and {y} is {x - y}");
Also, the initialization, as well as the update condition, are actually optional: we could have
and
Try to rewrite the four for
loops just given as four for
loops with exactly one initialization and one update in the header of the for
loop.
continue
and break
Programmers can use two keywords in loops, continue
and break
, that modify the control flow. Looking at the following code, try to understand what those statements do.
You can also use break
and continue
in while
loops. Try to rewrite the previous two for
as while
loops: there is a trick to make the while
loop using break
works properly, can you spot it?
Execute the following:
What can you conclude about the value of the cells that were not assigned?