90 likes | 235 Views
Sentinel Values and Running Totals. Sentient – to be aware Ex: Humans are “sentient” beings. We are aware! Sentinel Value: A special value that cannot be mistaken as a regular value. Ex: -1 A value that signals when the end of a list of values can be reached.
E N D
Sentient – to be aware • Ex: Humans are “sentient” beings. We are aware! • Sentinel Value: • A special value that cannot be mistaken as a regular value. Ex: -1 • A value that signals when the end of a list of values can be reached. • In regards to loops, it is a value that causes a loop to terminate.
In the movie “The Matrix” there were machines called “Sentinels” that attacked human spaceships, thereby causing the humans to terminate.
Ex. of Sentinel Value: //In this example, entering -1 causes the loop to end. while (intNumber != -1) { System.out.println(“Hello!”); System.out.print(“To end this loop enter -1: ”); intNumber = keyboard.nextInt(); }
Running Total: • A sum of numbers that accumulates with each iteration of a loop. • It is called “running” because the numbers are gathered and summed during the “running” of a loop. • Accumulator: • The variable used to keep the running total. • Decumulator: • The variable used to keep the balance when subtracting from a total.
Ex. of a running total: int intCounter = 1; while (intCounter < 5) { intTotal = intTotal + 5 //This is the accumulator intCounter ++; }
Deciding Which Loop To Use • “while” loop: • A pretest loop. • Ideal if you do NOT want the loop to iterate in the beginning if a condition is FALSE. • Also ideal if you want a sentinel value to terminate the loop. • “do-while” loop: • A posttest loop. • Ideal if you want the loop to iterate at least once.
Deciding Which Loop To Use • “for” loop: • A pretest loop. • Has built in expressions for initializing, testing, and updating. • Ideal for when the EXACT number of iterations is known.