Okay, examine this code. None of it should seem strange to you now. There is the addition of the "is not equal" evaluation operator ( != ). You shouldn't have problems understanding that. As long as the user inputs a number that is not equal to the value of 999, the while loop will continue. When the user inputs 999, the while loop conditional expression will evaluate false, and the loop stops.
Once again, I've excluded comments to try to assist you in determining what this code will do. Although I put comments in two places that I need to point out: Priming read and iteration read ("read" meaning for the user to read). The priming read displays to the screen the user instructions and asks for input. This is outside of the while loop, so it is only done once. But after the while loop completes, it needs to ask for more input. Therefore, you must put an iterative read before the end of the while loop, so that it displays the necessary information again, prompting the user for more input each time the loop completes.
Another way to do this would be to put only one read inside of the while structure, at the beginning. But that would be too easy :) - or rather, this example demonstrates using priming and iterative reads this way for when the easy way is not practical for one reason or another. An example would be in your priming read, you display your program name, version, author, etc. You wouldn't want that re-displaying every single loop, now would you?
Do a hand simulation while you read through it. Make up user input numbers as you go along - simulate entering at least three values before simulating the 999 halt value.
#include <iostream> int main () { int inval = 0; int numBig = 0; int numSmall = 0; int sum = 0; int total = 0; // priming read cout << endl << "Enter an integer (999 to halt input): "; cin >> inval; while (inval != 999) { if (inval > 50) numBig++; else numSmall++; sum += inval; total++; // iteration read cout << "Enter another (999 to halt input): "; cin >> inval; } cout << endl << "Total number of inputs: " << total << endl << "Total sum of inputs: " << sum << endl << "Number of inputs over 50: " << numBig << endl << "Number of inputs 50 or less: " << numSmall << endl << endl; return 0; }
Notice how the while statement within the curly-braces is getting longer. Imagine mixing those in with a few for the if / else statements. This is why you should always comment curly-braces to label what they belong to. One forgotten closed curly-brace would likely be a headache trying to locate in larger programs.
You should not have had any problems doing a hand-simulation of this. Now try coding it (again, with your own comments).
After you've run it sucessfully, we are going to move on to something a little different, character input from within a nested while - if / else.