开发者

Sentinel while loop for C++

开发者 https://www.devze.com 2022-12-19 06:37 出处:网络
Can anyone tell me what is sentinel while loo开发者_如何学编程p in C++? Please give me an example using sentinel while loop.A \"sentinel\" in this context is a special value used to indicate the end o

Can anyone tell me what is sentinel while loo开发者_如何学编程p in C++? Please give me an example using sentinel while loop.


A "sentinel" in this context is a special value used to indicate the end of a sequence. The most common sentinel is \0 at the end of strings. A "sentinel while loop" would typically have the form:

while (Get(input) != Sentinel) {
  Process(input);
}


A sentinel is a special value, e.g. boolean value, extremely big or small. It is used to determine when to stop the loop.

A good example is in the implementation of merge sort, e.g. read page 4 of http://www.cs.princeton.edu/courses/archive/spr07/cos226/lectures/04MergeQuick.pdf.


while (score != -1)
{
    total += score;
    game ++;

    cout << "Enter the point for game " << game << ":";
    cin >> score;

    
}

cout << "The total score are: " << total << endl;


It's usually a boolean (true or false) variable that is set to false when a condition is not satisfied and set to true when it is. Then we can loop so long as the sentinel is false.

Example:

bool acceptedAnswer = false;
while (acceptedAnswer == false)
{
  refreshPage();
  if (hasBeenAccepted())
  {
     acceptedAnswer = true;
  }
}


As an addendum to JRL's answer..

Please note that there was nothing wrong with asking this question, but in the future you may find more immediate help by going to dictionary.com and looking up words you don't know.

edit: in this case, the dictionary leaves nothing for you to think on. Here is definition 3 :)

3 Also called  tag.  Computers. a symbol, mark, or other labeling device indicating the beginning or end of a unit of information.


A sentinal is a special value in a list of items that will always cause the iterator to stop.

For example, the zero terminator in an ASCIIZ string acts as a sentinal.

Linked lists often have NULL pointers and so.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号