1/14
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
while loop
compound interest algorithm
planning:
add 1 to years
calculate interest
add interest to balance
report the final year value
the loop execute instructions repeatedly while a condition is True
type i: count-controlled loops
called definite loops
a while loop that is controlled by a counter variable
type ii: event-controlled loops
indefinite loops
a while loop is controlled by a loop variable
processing sentinel values
sentinel values are often used when taking input and
you don’t know how many input items are there
use a ‘special’ character or value to signal the end of input
for numeric input of positive numbers it is common to use the value -1
sentinel value denotes the end of a data set, but it’s not part of the data
priming read
some programmers don’t like the trick of initializing the input variable with a value other than a sentinel
an alternative is to change the variable with a read before the loop
modification read
the input operation at the bottom of the loop is used to obtain the next input
generating random numbers
random() returns a floating number that is >= 0 and <1
randint() function
a random integer in a given range
loop algorithm: sum values
initialize total to 0
use while loop with sentinel
loop algorithm: average values
keep a running total
initialize count to 0
increment total and count per input
check for count 0 before divide!
loop algorithm: counting matches
initialize negatives to 0
use a while loop
add to negatives per match
loop algorithm: prompt until a match is found
initialize boolean flag to false
test sentinel in while loop
get input and compare to valid range
if input is in range change flag to true
loop will stop executing when flag changes
loop algorithm: maximum/minimum
get first input value
the largest/smallest
get another input
loop as long as the input is valid (non-sentinel):
compare new input to largest/smallest and update largest/smallest if needed
get another input value
loop algorithm: comparing adjacent values
get first input and store it in value
get another input
loop as long as the input is valid (non-sentinel):
copy value to previous variable
store the new input in value variable
compare value to previous and output message if same
get another input