Running Totals and Sentinel Values

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

Running Totals and Sentinel Values give more control and flexibility to loop operations. Running totals are counters that are used to keep track of the number of times a loop or operation is run. This may or may not count the total of times a loop is executed. Some cases may require an operation to take place only on odd iterations, such as count the number of odd numbers between 1 and 20.

Sentinel Values are used to create an end case for a loop. For example, say we are looping through a String which terminates in an "end of line" character. If we do not want to process the end of line character, we can use a sentinel value. Now, we traverse the String character by character, and when the end of line character is examined, the sentinel value forces the loop to terminate.

Note: This example requires the knowledge of arrays.

 int[] numbers = {5,1,2,6,8,2,-1}
int sentinel = -1;
int counter = 0;

while(numbers[counter] != sentinel)
{
     // do stuff
     counter++;
} 

Sentinels can be very useful and can take the form of a boolean variable. This makes the control statement of the while loop much simpler and changing the value from true to false is the same as changing the value counter, from the above example, to -1.


This example can be easily modified to incorporate the "end of line" situation described above.

 String myString = "The end of line character is after the period.\n";
char sentinel = '\n';
int counter = 0;

while (myString.charAt[counter] != sentinel)
{
     // do stuff
     counter++;
} 

Note: Running totals and sentinel values can be misused and can lead to breakdowns in code execution. If you are unfamiliar with their usage, start with a simple example such as the ones above and progress from there.

Previous Page: Multiple Control Statements Next Page: User Defined Methods