Course contentsShow
← C
Lesson 314 of 1,2194. Control FlowFree lesson

The Sentinel Value pattern

The Sentinel Value pattern

What you'll learn: How to use a special "end-of-data" marker to process a list of inputs when you don't know the total count in advance.

The Buffet Analogy

Imagine you are at an "all-you-can-eat" buffet. The waiter doesn't know how many plates you will eat. They don't ask for a number upfront; instead, they keep bringing food until you place a specific "I’m done" card on the edge of the table.

That card is a Sentinel Value. It is a piece of data that follows the same format as your real data (it’s a card), but its specific value tells the program: "Stop processing now."

Why use it?

In many programs, you don't know if the user has three items to enter or three hundred. While you could ask the user for the count first, it's often more natural to let them type until they are finished.

To make this work, you choose a value that would be impossible or invalid in a real scenario. For example:

  • If you are entering ages, -1 is a great sentinel because no one is -1 years old.
  • If you are entering prices, 0 or a negative number works well.

Implementing the pattern

The most common way to write this is using a while loop. You grab the first input before the loop starts, check if it's the sentinel, and then keep grabbing new inputs at the very end of the loop body.

#include <stdio.h>

int main() {
    int score = 0;
    int sum = 0;

    printf("Enter exam scores (Type -1 to quit):\n");

    // Get the first input
    scanf("%d", &score);

    // As long as the input isn't our sentinel (-1), keep going
    while (score != -1) {
        sum += score;

        // Get the next input before looping back to the check
        printf("Next score: ");
        scanf("%d", &score);
    }

    printf("Total sum of scores: %d\n", sum);
    return 0;
}

The Pitfall: Choosing a valid value

The biggest mistake beginners make is choosing a sentinel value that could actually be part of the data. If you use 0 as a sentinel for a temperature tracker, your program will crash or stop just because it's freezing outside! Always ensure your sentinel is an "out-of-bounds" value that your logic will never encounter naturally.

Key takeaway

A sentinel value is a dummy data point used as a "stop sign" to terminate a loop when the number of inputs is unknown.