- Count-Controlled loop: it is executed a specified number of times
- Event-Controlled loop: it is executed a number of times which is not known in advance (everything depends on what is happening in the body of the while loop)
- It uses a variable in the loop test called the loop control variable (or counter)
- The loop control variable has to be initialized before we enter the loop
- The loop control variable has to be inceremented every time the body of the loop is executed
- Things to remember when you use a count-controlled loop
* Initialize the counter so that the condition of the while statement can be tested correctly
* Make sure that the condition of the while statement becomes false at some point (e.g., by incrementing the counter after every iteration)
- Infinite loop
* If the coondition never becomes false, then the loop will be executed forever !! (e.g., if you forget to increment the counter)
- sentinel-controlled
- end-of-file-controlled
- flag-controlled
- It is used when the program needs to read a lot of data but we do not know in advance how many
- The idea is to use a special value (sentinel value) to signal the program that there is no more data to be processed
- Looping continues as long as the data value read is not the sentinel
- When the sentinel is read, execution continues at the statement immediately following the loop
- Priming read
* It is inefficient to initialize variables with values that are never used
* Idea: read the first data item before you enter the while loop
- Things to remember when you use sentinels
* The value used as the sentinel cannot be one of the inputs to be processed
* When the sentinel is read, the while loop exits without processing the sentinel !!
* The user should know in advance what sentinel value is used by your program (i.e., print a message to inform the user)
- Many times, the nature of the problem dictates the value of the sentinel
cin.get(inChar);
while(inChar != '\n')
{
cout << inChar;
cin.get(inChar);
}
- Confusing '==' with '=' can result in an infinite loop !!!
cin >> dataValue;
while (dataValue = 1)
{
.....
cin >> dataValue;
}