March 20, 2018
Rewrite the following while (or do...while) loops as for loops.
Rewrite the following for loops as while loops:
Write a program that asks the user to enter a positive integer, and then uses a for loop to compute the sum of all the integers between 1 and the integer given by the user. For instance, if the user enters 5, your program should display 15 at the screen (i.e., 1 + 2 + 3 + 4 + 5 = 15).
Answer the following questions:
while loop?You can modify your program to answer check your answers to the previous questions. Once you are done, modify your original program with two respects:
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 harder 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.
for loops is actually more complex than what we discussed in class. It isThat 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
Can you rewrite them four as for loops with exactly one initialization and one update?
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?