Computer Science and Software Engineering© 2014 Project Lead The Way, Inc. Algorithms: Branching...

Preview:

Citation preview

Computer Science and Software Engineering © 2014 Project Lead The Way, Inc.

Algorithms:Branching and Iteration

(in Scratch)

http://scratch.mit.edu/projects/11516969/

Learn from Scratch!

Edit your picture in paint editor

Algorithms are step-by-step procedures

If-else structure: conditional

• Always evaluates condition at top of the if-else structure

• Boolean expression: true or false

If-else structure• Executes one

chunk or the other

• If-else always executes one chunk: not zero, not two

• If (no else) might execute one or zero chunks

If-else structure

• Continues with next block

Stacked if-else-structures• These are separate structures,

one after another

-240

240

-240

2400 x

y

snapsing

snapsqueak

clapsqueak

clapsing

Nested if-else-structures• One inside the

other

-240

240

-240

2400 x

y

snapHello

clapHello

squeakFella

singFella

Iteration• Iteration: an algorithm that repeats,

one cycle after another

Your turn!

Don’t miss the “else” opportunity• These stacks run slightly differently.

Why?Usually wasteful, risky

Better

Pair of opposite conditions

How to get exactly-one-of-several• If-else selects 1-of-2• If-elseif-else selects 1-of-3

10 20 30

How to get exactly-one-of-several• How about 1-of-4?

1-of-3

10 20 30

1-of-4 ?if

else-if

else-if

else

if

else-if

else

How to get exactly-one-of-several1-of-5

10 20 30

if

else-if

else-if

else

40

else-if

Recommended