for loops. challenge: racer ● simulate a race that says “now on lap x” for 10 laps. ● make x...

Post on 12-Jan-2016

215 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

For Loops

Challenge: Racer● Simulate a race that says “Now on lap X” for 10 laps.

● Make X vary, so it says 1, then 2, then 3

● Use only one output statement!

Loops● A loop is used for repetitive behaviour

● A set of commands is placed in a code block

● A condition determines when the block stops repeating

The For Loop

● Used when you know how many times something will happen

● Great for counting● Also often used with lists

Parts of a For Loop

● Sentry Variable● Initial Value● Looping Condition● Increment Statement

Sentry Variable● A special variable designed to control the loop

● In for loops, usually an integer

● Use a meaningful name when practical

● Traditionally use i if no other name makes sense

Initial Value

● Give sentry some meaningful initial value

● Usually 0 or 1

Looping Condition● A condition● Always involves sentry variable● Indicates when loop should continue

● If condition is true, loop will repeat

● When condition becomes false, loop will end

Increment Statement● A line of code● Always involves sentry variable● Changes value of sentry● Usually i++, i--, I += something

● Must make it possible for condition to become false eventually

Racer AlgorithmNew Program Racer by me

New integer variable lap starts at 1

For loop with lap going from 1 to 10 by 1

Output “Now on lap: “ + lap

End For loop

End racer

Challenge: Backwards Racer

● Simulate a race that says “Now on lap X” for 10 laps.

● This time go backwards!● Make X vary, so it says 10, then 9, then 8…

● Use only one output statement!

Counting Backwards● Use same for loop elements● Use larger value for initial sentry value

● Decrement variable each time through

● Check for smaller result

Backwards Racer Algorithm

New Program backRacer by me

New integer variable lap starts at 10

For loop with lap going from 10 to 1 by -1

Output “Now on lap: “ + lap

End For loop

End racer

Counting by 5 Algorithm

New Program byFive by me

New integer variable lap starts at 0

For loop with lap going from 0 to 50 by 5

Output “Now on lap: “ + lap

End For loop

End racer

Code Tracing● Make a chart● Make each variable a column head

● Make a column for each condition

● Make a column for output

Code Tracing Cont’d● Walk through code one line at a time

● Each time a variable changes, change it on the chart

● Each time you get to a condition statement, evaluate the condition

Code Tracing III

● For conditions, write TRUE or FALSE

● Write any output

Code Tracing Example

Ordinary Slide

● Level 1–Level 2

● Level 3

CodeMy code

More Code

More Code

top related