On sentinel values and infinite loops

    Because I found the following to be very clear in definition, I'll quote it directly - "An infinite loop is an instruction sequence that loops endlessly when a terminating condition has not been set, cannot occur, and/or causes the loop to restart before it ends." (Source) We see this in the form of for, do, and while statements in C#. In each of these types of loops, the contents of the loop will continue to run until a condition is met. Many times, a programmer will create a sentinel value to control how many times a loop will run. Here's an example:

SENTINEL_VALUE = 0
while (SENTINEL_VALUE < 5)
    print "I love programming!"
    SENTINEL_VALUE++

     In this example, we tell the application to print "I love programming", then add 1 to the variable SENTINEL_VALUE, as long as SENTINEL_VALUE is less than 5. But what if we took out the line "SENTINEL_VALUE++"? The application would print "I love programming!", then print it again, and again, and again, until the end of time (or until the user gets mad and closes the application).

     This is an example of an infinite loop. Nothing can stop the application from stating it's love of programming. It just continues to blast the screen with its affection. In this example, we can clearly see we have an infinite loop based on its output on the screen. What if we don't have any output though? What if the only thing in our loop is just adding a number to a variable? Since this is done internally, and not displayed on output, it may be difficult to determine why our application just "froze," and won't move on to the next step. Let me provide another example:

print "Look at me! I'm adding numbers!"
aNumber = 0
SENTINEL_VALUE = 0
while (SENTINEL_VALUE < 5)
    aNumber = aNumber + 1
print "Okay, I'm done adding numbers now!"

    In this loop, we're saying that while SENTINEL_VALUE is less than 5, add 1 to our variable aNumber. This will create an infinite loop though! Why? Because we're not changing our SENTINEL_VALUE while inside the loop. Our terminating condition (stop when SENTINEL_VALUE is 5 or more) is not being met, and we never move on to the next line, "Okay, I'm done adding numbers!" Thankfully, there's a quick alter that will show us just why our application seems to have frozen.

     Since SENTINEL_VALUE is what I'm depending on to terminate my loop, it would be great to know what its value is on each iteration of the loop. What if I could display its value on the screen? Then, with each loop, I'd know exactly what its value is:

while (SENTINTEL_VALUE < 5)
    aNumber = aNumber + 1
    print ("Round " + SENTINTEL_VALUE)

    Ah, so apparently we're stuck at round 0 with each pass! Just that one line of code quickly exposed why the terminating condition was not met to exit the loop.

Comments

Popular posts from this blog

Native, Web, and Hybrid apps

What is a mobile application?

Agilicious - Part 15