computers and scientific thinking1/2/20 4 example within a page 7 here, the if statement is executed...

11
1/2/20 1 Computers and Scientific Thinking David Reed, Creighton University Conditional Execution & Repetition 1 Conditional Execution so far, all of the code you have written has been unconditionally executed n the browser carried out statements in the same set order in contrast, many programming tasks require code that reacts differently under varying circumstances or conditions n e.g., a student's course grade depends upon his/her average n e.g., an ESP test requires recognizing when a subject guessed right n e.g., the outcome of a game depends upon die rolls or player moves conditional execution refers to a program’s ability to execute a statement or sequence of statements only if some condition holds true 2

Upload: others

Post on 01-Feb-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

1

Computers andScientific Thinking

David Reed, Creighton University

Conditional Execution & Repetition

1

Conditional Execution

so far, all of the code you have written has been unconditionally executedn the browser carried out statements in the same set order

in contrast, many programming tasks require code that reacts differently under varying circumstances or conditionsn e.g., a student's course grade depends upon his/her averagen e.g., an ESP test requires recognizing when a subject guessed rightn e.g., the outcome of a game depends upon die rolls or player moves

conditional execution refers to a program’s ability to execute a statement or sequence of statements only if some condition holds true

2

Page 2: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

2

If Statements

in JavaScript, the simplest form of conditional statement is the if statementn one action is taken if some condition is true, but a different action is taken if the

condition is not true (called the else case)n the else case is optional

general form of the if statement:

if (BOOLEAN_TEST) {

STATEMENTS_EXECUTED_IF_TRUE

}

else {

STATEMENTS_EXECUTED_IF_FALSE

}

3

Braces in If Statements

some people prefer braces on separate lines formatted like this:

if (BOOLEAN_TEST)

{

STATEMENTS_EXECUTED_IF_TRUE

}

else

{

STATEMENTS_EXECUTED_IF_FALSE

}

either style is acceptable, but be consistent!n properly aligning the code (with if-else lining up and statements indented) is

central in producing code that is easy to read and modify

technically, you can omit the braces if there is only one statement n however, THIS IS STRONGLY DISCOURAGED!n can lead to tricky errors if the code is ever modified

4

Page 3: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

3

Boolean Tests

the test that controls an if statement can be any Boolean expression (i.e., an expression that evaluates to either true or false)n Boolean tests are formed using relational operators because they test the

relationships between values

5

the Boolean test in an if statement determines the code that will be executed n if the test is true, then the code inside the subsequent curly braces will

executen if the test is false, then the code inside the curly braces following the else will

executen note that if the test is false and there is no else case, the program moves on to

the statement directly after the if

NOTE:

== is for comparisons

= is for assignments

If Statement Examples

6

an if statement is known as a control statement, since its purpose is to control the execution of other statements

Page 4: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

4

Example within a Page

7

here, the if statement is executed when the button is clicked§ what happens if

the text box contains a number < 90?

Nested If Statements

programming tasks often require code that responds to more than one conditionn this can be accomplished by nesting one if statement inside of another

example: three different grade levelsn A-level (grade ≥ 90), passing (60 ≤ grade < 90), failing (grade < 60)n the outer if-else distinguishes A from non-A gradesn the nested if-else further separates non-A grades into passing and failing

8

Page 5: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

5

Cascading If-else Statements

nested if-else structures are known as cascading if-else statements because control cascades down the branchesn the topmost level is evaluated first n if the test succeeds, then the corresponding statements are executed and control

moves to the next statement following the cascading ifn if the test fails, then control cascades down to the next if testn in general, control cascades down the statement from one test to another until

one succeeds or the end of the statement is reached

9

A Cleaner Notation

when it is necessary to handle a large number of alternatives, nested if-else statements can become cumbersome and unwieldyn multiple levels of indentation and curly braces cause the code to look cluttered

make it harder to read/understandn can simplify by removing some unnecessary curly braces & aligning each case to

the left

nested if statements vs. more readable else-ifexample:

10

Page 6: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

6

Dice Stats Example

consider a Web page that simulates the roll of two dicen will use image to display the dicen will use a button to initiate the die rollsn will keep track and display the number of rolls

n when the user clicks the button, two random die rolls are selected, the corresponding images are displayed, and the number of rolls incremented

11

dicestats1

the RandomInt function from random.js is used to select the random roll

since each die image is stored as die#.gif, can assign each image source with one assignment

the number of rolls appears in a span

§ initially 0§ incremented in RollDice each

time the button is clicked

12

Page 7: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

7

dicestats2add a second span to keep track of the number of doubles

in the Roll function, an if statement checks to see if the rolls are the same, if so increments doubleSpan

if not, doubleSpan is unchanged

13

Boolean Expressions

sometimes, simple comparisons between two values may not be adequate to express the conditions under which code should execute

JavaScript provides operators for expressing multipart testsn logical AND (&&): represents the conjunction of two things

p (TEST1 && TEST2) is true if both TEST1 and TEST2 are true

if (roll1 == 4 && roll2 == 4) {

// CODE TO BE EXECUTED WHEN DOUBE FOURS ARE ROLLED}

n logical OR (||): represents the disjunction of two thingsp (TEST1 || TEST2) is true if either TEST1 or TEST2 are true

if (roll1 == 4 || roll2 == 4) {// CODE TO BE EXECUTED WHEN AT LEAST ONE FOUR IS ROLLED

}

n logical NOT (!): represents negationp (!TEST1) is true only if TEST1 is false

if (!(roll1 == 4 || roll2 == 4)) {// CODE TO BE EXECUTED WHEN NEITHER ROLL IS A FOUR

} 14

Page 8: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

8

Slot Machine

15

you are to create a page that simulates a slot machine

displays three random slot images at the click of a buttonn if all three are the same, alert window announces a winner

keeps track of the player's creditsn start the game with 20 creditsn each spin costs 1 credit, three matching slots earns 13 credits (net gain of 12)n should not allow the player to spin if no credits

Conditional Repetition

an if statement is known as a control statementn it is used to control the execution of other JavaScript statements

n provides for conditional executionn is useful for solving problems that involve choices

p either do this or don't, based on some condition (if)p either do this or do that, based on some condition (if-else)

16

closely related to the concept of conditional execution is conditional repetitionn many problems involve repeating some task over and over until a specific

condition is met

n e.g., rolling dice a set number of times and generating statisticsn e.g., rolling dice until a 7 is obtainedn e.g., repeatedly prompting the user for a valid input

n in JavaScript, while loops provide for conditional repetition

Page 9: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

9

While Loops

a while loop resembles an if statement in that its behavior is dependent on a Boolean condition. n however, the statements inside a while loop’s curly braces (a.k.a. the loop body)

are executed repeatedly as long as the condition remains truen general form:

while (BOOLEAN_TEST) {

STATEMENTS_EXECUTED_AS_LONG_AS_TRUE

}

17

when the browser encounters a while loop, it first evaluates the Boolean testn if the test succeeds, then the statements inside the loop are executed in order,

just like an if statementn once all the statements have been executed, program control returns to the

beginning of the loopn the loop test is evaluated again, and if it succeeds, the loop body statements are

executed againn this process repeats until the Boolean test fails

While Loop Example

example: roll two dice a desired number of times

n numRolls keeps track of the number of rolls simulated so farn initially, numRolls is 0 (since no rolls simulated yet)n as long as numRolls < the desired number of rolls,

p simulate a dice roll (and process as needed)p increment numRolls (to count the roll just simulated)

18

numRolls = 0; while (numRolls < desiredRolls) {

// SIMULATE THE DICE ROLL numRolls = numRolls + 1;

}

Page 10: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

10

dicestats3

19

Loop Tests

note: the loop test defines the condition under which the loop continuesn this is often backwards from the way we think about loops

n e.g., read input until you get a positive number (i.e., until input > 0)

while (input <= 0) { . . . }

n e.g., keep rolling dice until you get doubles (i.e., until roll1 == roll2)

while (roll1 != roll2) { . . . }

n e.g., keep rolling dice until you get double fours (i.e., until roll1 == 4 && roll2 = 4)

while (roll1 != 4 || roll2 != 4) { . . . }

20

Page 11: Computers and Scientific Thinking1/2/20 4 Example within a Page 7 here, the if statement is executed when the button is clicked what happens if the text box contains a number < 90?

1/2/20

11

Infinite Loops

the browser will repeatedly execute statements in the body of a while loopas long as the loop test succeeds (evaluates to true)

n it is possible that the test will always succeed and the loop will run forever

n a loop that runs forever is known as an infinite loop (or a black hole loop)

n to guard against infinite loops, make sure that some part of the loop test changes inside the loop

p in the above example, numRolls is not updated in the loop so there is no chance of terminating once the loop starts

n an infinite loop may freeze up the browserp sometimes, clicking the Stop button will suffice to interrupt the browserp other times, you may need to restart the browser

21