1 CSC 121 Computers and Scientific Thinking David Reed Creighton University Conditional Execution.

Slides:



Advertisements
Similar presentations
CSC 121 Computers and Scientific Thinking Fall Conditional Execution.
Advertisements

Computers and Scientific Thinking David Reed, Creighton University Conditional Execution 1.
CSC 221: Computer Programming I Fall 2001  conditional repetition  repetition for: simulations, input verification, input sequences, …  while loops.
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Session 5 JavaScript/JScript: Control Structures II Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
16/27/ :53 PM6/27/ :53 PM6/27/ :53 PMLogic Control Structures Arithmetic Expressions Used to do arithmetic. Operations consist of +,
Objectives You should be able to describe:
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Fundamentals of Python: From First Programs Through Data Structures
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 12: How Long Can This Go On?
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Conditional Execution
Flow of Control Part 1: Selection
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
© Jalal Kawash Programming Peeking into Computer Science 1.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Algorithm Design.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
1 A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 4 JavaScript and.
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 5 JavaScript.
JavaScript, Fourth Edition
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 13 Conditional.
1 CSC 221: Computer Programming I Fall 2011 Python control statements  operator precedence  importing modules  random, math  conditional execution:
Decision Making and Branching (cont.)
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 13 Conditional.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Controlling Program Flow with Decision Structures.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CSC 121 Computers and Scientific Thinking Fall Event-Driven Programming.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
JavaScript: Control Statements.
JavaScript: Control Statements I
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
T. Jumana Abu Shmais – AOU - Riyadh
Iteration: Beyond the Basic PERFORM
3 Control Statements:.
Chapter 6: Repetition Statements
Conditional Execution
Boolean Expressions to Make Comparisons
Chapter 11 Conditional Execution
Chapter 17 JavaScript Arrays
Chapter 13 Conditional Repetition
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
Computers and Scientific Thinking David Reed, Creighton University
Presentation transcript:

1 CSC 121 Computers and Scientific Thinking David Reed Creighton University Conditional Execution

2 so far, all of the code you have written has been unconditionally executed 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 e.g., a student's course grade depends upon his/her average e.g., an ESP test requires recognizing when a subject guessed right 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

3 If Statements in JavaScript, the simplest form of conditional statement is the if statement 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) the else case is optional general form of the if statement:

4 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! 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 however, THIS IS STRONGLY DISCOURAGED! can lead to tricky errors if the code is ever modified

5 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 ) boolean tests are formed using relational operators because they test the relationships between values the boolean test in an if statement determines the code that will be executed if the test is true, then the code inside the subsequent curly braces will execute if the test is false, then the code inside the curly braces following the else will execute 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

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

7 Example within a Page

8 Accessing Text Fields recall that values entered via text boxes/areas are always returned as strings if (document.getElementById('age').value >= 18) { alert("You are old enough to vote."); } else { alert("Sorry. You are too young to vote."); } will say that a 2-year old can vote, but a 102-year old can't! WHY? age = parseFloat(document.getElementById('age').value); if (age >= 18) { alert("You are old enough to vote."); } else { alert("Sorry. You are too young to vote."); } will behave as expected if you wish to treat a value obtained from a text box or text area as a number, you must use the parseFloat function to convert it

9 Nested If Statements programming tasks often require code that responds to more than one condition this can be accomplished by nesting one if statement inside of another example: determining wind-chill  wind-chill is only defined for temperatures less than or equal to 50 degrees  the initial if test is to determine if it is a valid temperature to calculate wind- chill  the nested if statement only executes if the outer test is true

10 Cascading If-else Statements nested if-else structures are known as cascading if-else statements because control cascades down the branches the topmost level is evaluated first if the test succeeds, then the corresponding statements are executed and control moves to the next statement following the cascading if if the test fails, then control cascades down to the next if test in general, control cascades down the statement from one test to another until one succeeds or the end of the statement is reached example: nested if-else structure

11 A Cleaner Notation when it is necessary to handle a large number of alternatives, nested if-else statements can become cumbersome and unwieldy multiple levels of indentation and curly braces cause the code to look cluttered make it harder to read/understand example: nested if statements vs. a more readable else-if

12 Die Roll Example consider a Web page that simulates the roll of a single die will use an image to display the die will use a button to initiate the die roll when the user clicks the button, a random die roll is selected and the corresponding image is displayed

13 Die Roll Page the RandomInt function from random.js is used to select the random roll depending on the roll value, the correct image is displayed since more than two possibilities, a cascading if-else is needed

14 Generalizing Code note that each case in the cascading if-else follows the same pattern if (roll == 1) { document.getElementById('die').src = " } else if (roll == 2) { document.getElementById('die').src = " } else if (roll == 3) { document.getElementById('die').src = " } else if (roll == 4) { document.getElementById('die').src = " } else if (roll == 5) { document.getElementById('die').src = " } else { document.getElementById('die').src = " } this entire cascading if-else structure could be replaced by the following: document.getElementById('die').src = " + roll + ".gif";

15 Counters in software applications, if statements are often used to count occurrences of conditional or user-initiated events e.g., count the number of times dice rolls come up doubles e.g., count the number of times the user guesses a number correctly any variable that is used to record occurrences of an event is known as a counter initially, the counter is set to zero each time the specified action occurs, the counter is incremented after a given time period, the value stored in the counter will tell you the number of times the desired event took place

16 Logical Connectives 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 tests logical AND (&&): represents the conjunction of two things  (TEST1 && TEST2) is true if both TEST1 and TEST2 are true if (roll1 == 4 && roll2 == 4) { // code to be executed when double fours are rolled } logical OR (||): represents the disjunction of two things  (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 } logical NOT (!): represents negation  (!TEST1) is true only if TEST1 is false if (!(roll1 == 4 || roll2 == 4)) { // code to be executed when neither roll is a four }

17 Conditional Repetition an if statement is known as a control statement it is used to control the execution of other JavaScript statements provides for conditional execution is useful for solving problems that involve choices  either do this or don't, based on some condition (if)  either do this or do that, based on some condition (if-else) closely related to the concept of conditional execution is conditional repetition many problems involve repeating some task over and over until a specific condition is met e.g., rolling dice until a 7 is obtained e.g., repeatedly prompting the user for a valid input in JavaScript, while loops provide for conditional repetition

18 While Loops when the browser encounters a while loop, it first evaluates the boolean test if the test succeeds, then the statements inside the loop are executed in order, just like an if statement once all the statements have been executed, program control returns to the beginning of the loop the loop test is evaluated again, and if it succeeds, the loop body statements are executed again this process repeats until the boolean test fails a while loop resembles an if statement in that its behavior is dependent on a boolean condition. 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 true general form:

19 While Loop Example example: roll two dice repeatedly until doubles are obtained sample output: note: even though while loops and if statements look similar, they are very different control statements an if statement may execute its code 1 time or not at all a while loop may execute its code an arbitrary number of times (including not at all)

20 While Loop Page

21 Avoiding redundancy note the redundancy in the code must perform the initial dice roll before the loop begins then, have to repeatedly re-roll inside the loop can avoid this by either: "priming the loop" with default values that allow the loop to execute defining a Boolean "flag" to determine when the loop should continue

22 Loop Tests note: the loop test defines the condition under which the loop continues this is often backwards from the way we think about loops e.g., read input until you get a positive number (i.e., until input > 0) while (input <= 0) {... } e.g., keep rolling dice until you get doubles (i.e., until roll1 == roll2) while (roll1 != roll2) {... } e.g., keep rolling dice until you get double fours (i.e., until roll1 == 4 && roll2 = 4) while (roll1 != 4 || roll2 != 4) {... } DeMorgan's Law: !(X && Y) == (!X || !Y) !(X || Y) == (!X && !Y)

23 Counter-Driven Loops since a while loop is controlled by a condition, it is usually impossible to predict the number of repetitions that will occur e.g., how many dice rolls will it take to get doubles? a while loop can also be used to repeat a task some fixed number of times implemented by using a while loop whose test is based on a counter general form of counter-driven while loop: the counter is initially set to 0 before the loop begins, and is incremented at the end of the loop body  the counter keeps track of how many times the statements in the loop body have executed  when the number of repetitions reaches the desired number, the loop test fails and the loop terminates

24 Counter-Driven Loops examples :

25 Counter-Driven Loops Page

26 Infinite Loops the browser will repeatedly execute statements in the body of a while loop as long as the loop test succeeds (evaluates to true) it is possible that the test will always succeed and the loop will run forever a loop that runs forever is known as an infinite loop (or a black hole loop) to guard against infinite loops, make sure that some part of the loop test changes inside the loop  in the above example, repCount is not updated in the loop so there is no chance of terminating once the loop starts an infinite loop may freeze up the browser  sometimes, clicking the Stop button will suffice to interrupt the browser  other times, you may need to restart the browser

27 Variables and Repetition any variable can be employed to control the number of loop repetitions and the variable can be updated in various ways example: countdown

28 Countdown Page

29 Example: Hailstone Sequences an interesting unsolved problem in mathematics: hailstone sequence 1. start with any positive integer 2. if the number is odd, then multiply the number by three and add one; otherwise, divide it by two 3. repeat as many times as desired for example: 5, 16, 8, 4, 2, 1, 4, 2, 1, 4, 2, 1, … it is conjectured that, no matter what positive integer you start with, you will always end up in the loop this has been verified for all starting number up to 1,200,000,000,000 but, it still has not been proven to hold for ALL starting numbers we can define a JavaScript function for experimenting with this problem  the hailstone function will generate the sequence given a starting number