Search⌘ K
AI Features

Sentinel Loops

Explore the concept of sentinel loops in C++, where loop termination depends on special sentinel values rather than fixed iterations. Learn to implement while loops for flexible control flow, understand common pitfalls, and practice solving problems like summing inputs and calculating averages using sentinel-controlled loops.

The sentinel value

Sometimes, the loop doesn’t have a fixed number of repetitions. Instead, an indicator value stops the loop. This special value is called the sentinel value. For example, we don’t know how much data is in a file without reading it all. However, we know that every file ends with an end-of-file (EOF) mark. So, the EOF mark is the sentinel value in this case.

Note: We should select a sentinel value that’s not expected in the normal input.

The while loop

We use the while loop when the termination of the loop depends on the sentinel value instead of a definite number of iterations. As a simple example, we want to display the reverse sequence of digits in a positive integer value input by the user.

#include <iostream>
using namespace std;

int main()
{
  int a;
  cout << "Input a number: "; // Taking an input in a variable a
  cin >> a;
  while (a > 0) // This loop will terminate when the value of a is not greater than 0.
  { 
    cout << a % 10;
    a = a / 10; // Dividing by 10 and assigning the value back to a
  }
  cout << endl;
  return 0;
}
The reverse of an integer value

In the program above:

  • Line 6: We declare an integer variable a.
  • Line 7: We prompt the user to input a number.
  • Line 8: We take the input number from the user and store it in a.
  • Line 9: This is the loop statement, while, followed by a conditional expression and then an opening brace, { on line 10.

Note: There is no ...