(x-hour lecture)
do statement; while (expression);
The test occurs after each iteration. The body executes at least once.
Check out the demo electionyear2.cpp for an example of its usage. Note that the prompt is not repeated, as it was in electionyear.cpp but that the test is repeated. This brings us to the following paradigm:
Follow the general form:
do { cout << "Prompt: "; cin >> value; } while (value is bad);
The general form for this procedure is:
cout << "Nice prompt: "; cin >> value; while (value is bad) { cout << "You idiot prompt: "; cin >> value; }
It is even possible to keep a variable to count how many bad answers have been given, and to give progressively nastier responses, or even to finally give up on the user and terminate the program.
for (initial; condition; update) statement;
Is equivalent to:
initial; while (condition) { statement; update; }
An example:
int i; for (i = 1; i <= 10; i++) cout << i << endl;and
int i; i = 1; while (i <= 10) { cout << i << endl; i++; }do the same thing.
A for-loop is "syntactic sugar" for a while loop. Note that any C++ can go in the initial, condition, and update spaces in the header. This includes creating a variable to be used only within the loop in the initial space.
Check out BusDriversBane.cpp for a for-loop example. TimesTable.cpp is an example of nested for loops (a for loop contained in the body of a for loop).
The debugger is a valuable tool in writing correct problems. The program e.cpp contains some bugs which can be found and corrected with the use of the debugger. Download e.cpp and load it into a project. Try running it with the input 1. The answer is INF, which stands for infinity. Now, run it again, but first go to the project menu, and choose Enable Debugger. You should now get a window with the program in the bottom pane, and variables in the top right pane. There is also a small floating toolbar. The buttons, from left to right, are: Run, Stop, Kill, Single Step, Step Into, and Step Out. You won't be using the last two just yet, but they will come in handy once you start writing functions.
The first thing you need to do is set a breakpoint, where the program will stop executing and drop into the debugger. Try putting one after cin >> x. To do that, click the little dash to the left of the next line down. Now, press the Run button. The program will ask you for an exponent, then drop to the debugger. Use the single step button, and watch the values in the upper right pane carefully as you step through the program. Note which step causes a wrong number to appear. Can you figure out what the problem is? Tune in tomorrow for the exciting conclusion!
To Index Previous Next