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.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
Fall 2004ENGR 111A MatLab – Palm Chapter 4, Part 2 The if and switch structure Class 10.1 Sections: 4.4 and 4.6.
Val Function A Function performs an action and returns a value The expression to operate upon, known as the argument, (or multiple arguments), must be.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 7 Event-Driven.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
CIS101 Introduction to Computing Week 12 Spring 2004.
Introduction to JavaScript for Python Programmers
Adding Automated Functionality to Office Applications.
Chapter 4 The If…Then Statement
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
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.
CONTROLLING PROGRAM FLOW
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
© Jalal Kawash Programming Peeking into Computer Science 1.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
1 A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 4 JavaScript and.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
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
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
Chapter 3 Control Structures. The If…Then Statement The If…Then statement is a Decision statement = that executes a set of statements when a condition.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
1 CSC 221: Computer Programming I Fall 2011 Python control statements  operator precedence  importing modules  random, math  conditional execution:
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
31/01/ Selection If selection construct.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
Controlling Program Flow with Decision Structures.
1 CSC 121 Computers and Scientific Thinking David Reed Creighton University Conditional Execution.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 5 Making Decisions.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
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.
Visual Basic/ Visual Studio Brandon Large. Connecting to prior knowledge In your notes write down what the two main parts of the computer are. The “software”
Computer Science Up Down Controls, Decisions and Random Numbers.
Slide 1 Chapter 4 The If…Then Statement  Conditional control structure, also called a decision structure  Executes a set of statements when a condition.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
JavaScript Controlling the flow of your programs with ‘if’ statements
Chapter 4 The If…Then Statement
IF statements.
More Selections BIS1523 – Lecture 9.
Conditions and Ifs BIS1523 – Lecture 8.
T. Jumana Abu Shmais – AOU - Riyadh
Conditional Execution
Boolean Expressions to Make Comparisons
Chapter 11 Conditional Execution
Selection Statements Chapter 3.
Chapter 17 JavaScript Arrays
Computers and Scientific Thinking David Reed, Creighton University
Presentation transcript:

Conditional Execution JavaScript V Conditional Execution

Outline Conditional statement Nested If Boolean expressions If-then If-then-else Nested If Boolean expressions

Program execution Unconditional execution Conditional execution interpreter executes each line in sequence Conditional execution evaluate a test execute code only if test is true we can think of this as one step not always executed Need not be a single step might be a chunk of code controlled by the condition call the "body" program step 1 program step 2 program step 3 program step 4 program step 5 condition conditional step program step 2 program step 3 program step 4

Examples if due date on book is before today's date charge overdue fee if day of the week is not sunday or holiday parking meter must be used if even day of the month and date between Nov 1 and April 1 car will be ticketed and towed

JavaScript if statement Example if (condition) statement or if (condition) { statements } Example if (dateToday > dueDate) bookOverdue = true; or { calculateFine (dateToday, dueDate); ... }

If-then-else Conditional execution evaluate a test execute one piece of code if test is true execute another piece if test is false we can think of this as one step one part or the other will be executed If (condition) conditional true step(s) else condition false step(s) program step 2 program step 3 program step 4 program step 1

Examples if the title is a new release if the answer is correct then charge $3.00 and lending period is 2 days else charge $2.00 and lending period is 5 days if the answer is correct then add 1 to score else print help message

JavaScript if statement Example if (condition) { then part } else { else part Example if (newRelease(title)) { charge = 3.00; lendingPeriod = 2; charge = 2.00; lendingPeriod = 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 NOTE: == is for comparisons = is for assignments 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

JavaScript if statement Example if (condition) { then part } else { else part Example if (newRelease(title)) { charge = 3.00; lendingPeriod = 2; charge = 2.00; lendingPeriod = 5;

Stylistic issues Where to put brackets I prefer after condition if (condition) { ... body ... } else { Some prefer on separate lines if (condition) { } else In some cases, you might put whole statement on one line if (condition) { ... body ... }

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

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? 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 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

Example ifdemo.html ifdemo2.html (with else) chill.html

Nested If There may be more than two possibilities to be handled Put one if statement inside another if (temp <= 50) { if (windSpeed <= 3){ windChill = temperature; } else { windChill = ...calculation here...; ... wind chill undefined ... Example: chill2.html

Exercise x = 0; y = 5; output  ? x = 0; y = -5; output  ? if (x >= y) { if (x*10 < 100) { document.write(“ONE”); } else { document.write(“TWO”); document.write(“THREE”); x = 0; y = 5; output  ? x = 0; y = -5; output  ? x = 9; y = 9; output  ? x = 22; y = 21; output  ?

Cascading ifs Easier to read than nested style It is clear that multiple alternatives are involved if (condition1) then { action1 } else if (condition2) then { action2 } else if (condition3) then { action3 } etc Some languages (perl) actually have a special elsif construct

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

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

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

Generalizing Code note that each case in the cascading if-else follows the same pattern if (roll == 1) { document.getElementById('die').src = "http://dave-reed.com/book/Images/die1.gif"; } else if (roll == 2) { document.getElementById('die').src = "http://dave-reed.com/book/Images/die2.gif"; else if (roll == 3) { document.getElementById('die').src = "http://dave-reed.com/book/Images/die3.gif"; else if (roll == 4) { document.getElementById('die').src = "http://dave-reed.com/book/Images/die4.gif"; else if (roll == 5) { document.getElementById('die').src = "http://dave-reed.com/book/Images/die5.gif"; else { document.getElementById('die').src = "http://dave-reed.com/book/Images/die6.gif"; this entire cascading if-else structure could be replaced by the following: document.getElementById('die').src = "http://dave-reed.com/book/Images/die" + roll + ".gif";

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

Examples dice.html twodice.html Exercise (on your own): Reed style note image list access with counter In-class Exercise: with double counter? Exercise (on your own): Rewrite wind chill code as cascading ifs

Equality operators Equal == Not equal != Inequality >, >=, <, <= These are operators just like +, -, etc. What data type do they return? i < 5

Decision Making: Equality and Relational Operators

If Statement Gotcha 1 Type Sensitivity The result of an inequality depend on data type 100 > 18 "100" < "18"

If Statement Gotcha 2 Equality vs assignment Equality test (d == 0) Boolean value Assignment (d = 0) the assignment statement also has a value whatever the new value is bad language design! Unexpected behavior if (done = false) .. do something .. never executed Worse yet "", 0 are automatically converted to false if (p = 5) always executed Check that if statements only use the equality operator ==

Boolean Operators && and || or ! not

Boolean expressions Expressions returning Boolean values can be used as a condition in an if statement if wind speed above 3 and temperature below 50 calculate wind chill if (windSpeed > 3 && temperature < 50) calculate (windSpeed, temperature)

Other Examples twodice.html In-class Exercise: with double counter? die1 = RollDie(); die2 = RollDie(); doubles? die1 == die2 total is 7? die1 + die2 == 7 roll is a 1 and 1? (die1 == 1) && (die2 == 1) roll contains a 3? (die1 == 3) || (die2 == 3) total is 7 or 11? (die1 + die2 == 7) || (die1 + die2) == 11 twodice.html In-class Exercise: with double counter?