Using Control Structures. Goals Understand the three basic forms of control structures Understand how to create and manage conditionals Understand how.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Selection (decision) control structure Learning objective
Introduction to C Programming
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
C++ for Engineers and Scientists Third Edition
Introduction to C Programming
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
CIS101 Introduction to Computing Week 12 Spring 2004.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CSCI N201: Programming Concepts Copyright ©2005  Department of Computer & Information Science Using Decision Structures.
Using Control Structures. Goals Understand the three basic forms of control structures Understand how to create and manage conditionals Understand how.
Computer Science Selection Structures.
Chapter 3 Making Decisions
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 4 Selection Structures: Making Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
© 2000 Scott S Albert Selection Structures Structured Programming 256 Chapter 4.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
WRITING CONTROL STRUCTURES (CONDITIONAL CONTROL).
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
JavaScript, Fourth Edition
CSCI N201: Programming Concepts Copyright ©2005  Department of Computer & Information Science Working with Selection Structures.
PEG200/Saidatul Rahah 1.  Selection Criteria › if..else statement › relational operators › logical operators  The if-then-else Statement  Nested if.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Chapter Making Decisions 4. Relational Operators 4.1.
Chapter 4 Control Structures I. Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Using Loops. Goals Understand how to create while loops in JavaScript. Understand how to create do/while loops in JavaScript. Understand how to create.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright ©2005  Department of Computer & Information Science If-Then-Else Structures.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
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++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 7 JavaScript: Control Statements, Part 1
Chapter 3: Decisions and Loops
Chapter 4: Making Decisions.
Chapter 6: Conditional Statements and Loops
Expressions and Control Flow in JavaScript
JavaScript: Control Statements.
Java Programming: Guided Learning with Early Objects
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Using Decision Structures
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Chapter 3: Selection Structures: Making Decisions
Controlling Program Flow
Presentation transcript:

Using Control Structures

Goals Understand the three basic forms of control structures Understand how to create and manage conditionals Understand how to change program execution flow based on conditionals Understand branching ◦ Simple if ◦ Two branch if-else ◦ Multi-branch conditionals  Else if  Nested branching  Case/Switch ◦ Branching and Defensive Programming Practices

Programming and Control Structures All programming languages support Control Structures Essentially, control structures give programmers a toolset for “controlling” what code gets executed, and how many times. There are three basic control structures: ◦ Sequential ◦ Branching ◦ Looping

Control Structures: Sequential Sequential Code – Unless otherwise indicated, programming instructions are executed in order… the first line of code, then the next, then the third. Sequential processing is the default control structure (ie, as a programmer, you get it without asking!)

Control Structures: Branching Branching structures allow the programmer to structure mutually exclusive blocks of code Based on the value of some conditional, either one block of code executes or another…. For example: If it’s raining, take an umbrella. Else, leave the umbrella at home.

Control Structures: Looping Looping structures allow the programmer to create repeating blocks of code. The code can repeat zero or many times, based on the value of some conditional. For example: Would you like to play a game? Game is played and ends, and the user is asked: Would you like to play again? Game is played and ends, and the user is asked: Would you like to play again…

Introducing Decision Structures Decision structures consist “of a test condition together with one or more groups (or blocks) of statements. The result of the ‘test’ determines which of these blocks” the program will execute (Venit) In all decision structures, ONE AND ONLY ONE block executes. The program will then execute the next sequential section of code, after it evaluates a decision structure and executes the appropriate code block.

Types of Decision Structures JavaScript gives us three distinct types of Decision Structures: ◦ Single-Alternative (a.k.a – If-Then) Structure  Contains a single block of executable code that will execute IF AND ONLY IF the associated condition (test) evaluates to TRUE (we don’t care if it evaluates to false). ◦ Dual-Alternative (a.k.a – If-Then-Else) Structure  Contains exactly two blocks of code. One block will execute IF AND ONLY IF the associated condition (test) evaluates to TRUE; the other block will execute IF AND ONLY IF the associated condition (test) evaluates to FALSE.

Types of Decision Structures JavaScript gives us three distinct types of Decision Structures: ◦ Multiple-Alternative (Select Case) Structure  Contains multiple blocks (called cases), each of which will execute IF AND ONLY IF the program matches ONLY one of multiple condition (test) results. ONLY ONE BLOCK (case) will execute.

Humans as “Decision Makers” Human beings are very good at understanding concepts. We understand multiple types of syntax, too. Additionally, we understand meaning. This allows for some “gray area” in our language.

“Concepts” to “Conditions” Consider the following statements: “It’s cool outside.” “The weather is cool outside.” “It’s somewhat chilly out there!” “The temperature is expected to be around 65°”

“Concepts” to “Conditions” What does “cool” mean? Its meaning is arbitrary … Humans can understand multiple types of syntax and are able to extrapolate meaning from different syntax. However, computers don’t “think” on that level. As programmers, we need to refine human language to a more restrictive language that computers understand. One way to do this is to translate concepts to conditions which can be tested …

Using the Relational Operator The relational (comparison) operator compares two values of THE SAME TYPE (i.e. – Strings are compared to strings, integers are compared to integers, etc.) There are several different types of comparison operators (see next slide) Comparison operators HAVE NO PRECEDENCE among themselves and are evaluated LEFT to RIGHT (however, parentheses can be added to alter precedence)

Available Relational Operators Comparison JavaScript Relational Operator Is equal to == Is not equal to != Is less than < Is less than or equal to <= Is greater than > Is greater than or equal to >=

Translating the Concept Remember, that computers don’t understand arbitrary concepts Instead, we need to define the meaning of the concept for the computer Once we define what “cool” means, we can write our conditional statement

The “If” Conditional A single-alternative (If-Then) structure, allows us to specify an action IF AND ONLY IF a condition tests to TRUE. The parts of the If-Then structure: if (condition is true) { perform this action }

What if the “if” condition is not met? It is a good idea to provide an alternative plan if a condition is not met (it evaluates to FALSE). To do this, we use an “If-Then-Else” structure: if (condition is true) { perform action 1 }else{ perform action 2 }

The Conditional Operator Sometimes, it may be convenient for you to use a shortcut for dual alternative (If-Then- Else) structures. The shortcut is called the conditional operator. Its general form looks like this: Condition ? Action If True : Action If False

The Conditional Operator We can rewrite the following code using a conditional operator: strGreeting = “Hello ”; if(strUserName != null) { strGreeting += strUserName; }else{ strGreeting += “there!”; } Example adapted from JavaScript: The Definitive Guide (Flanagan)

The Conditional Operator The previous code using a conditional operator: strGreeting = “Hello ” + (strUserName != null ? strUserName : “there.”); Example adapted from JavaScript: The Definitive Guide (Flanagan)

What about multiple conditions? Sometimes, we need to consider the possibility that we need to evaluate more than value as a response to user input We can do this using nested branching.

Nested Branching Consider the following statements: ◦ “If the temperature outside is greater than 65°, I’ll wear a short- sleeved shirt.” ◦ “If the temperature outside is less than 65°, I’ll wear a sweater.” ◦ “If the temperature outside is less than 65° and is less than 45°, I’ll need to wear a coat.” These statements present us with one condition to test (the temperature), but more than two (three) possible actions!

Nested Branching We could write the code using a bunch of “if” statements, each independent of the other: However, a much more efficient (and cleaner, code-wise) way is to use a nested structure:

Multiple Conditions Sometimes, it’s necessary to combine multiple conditions to form a single, more complex text. It is a good idea to first establish a table (on paper) mapping the multiple conditions, the possible responses and the program’s reaction to responses.

Boolean Operators Sometimes, conditions can be joined together in the same test using Boolean operators: ◦ Logical AND is represented by && Example: if (A = B && C = D) … ◦ Logical OR is represented by || Example: if(A = B || C = D) … ◦ Logical NOT is represented by ! (bang symbol) Example: if( !(A = B) ) … Boolean Precedence: NOT, followed by AND, followed by OR

More on Boolean Operators From Boolean expressions, we can develop Truth Tables: Cond A Cond. B A && B A || B !(A) TTTTF TFFTF FTFTT FFFFT

Multiple Conditions Cond.QuestionYesNoResponse I Weekend? X- Response 1 First day? X- Response 2 II Weekend? X- Response 3 First day? -X Response 4 III Weekend? -X Response 5 First day? X- Response 6 IV Weekend? -X Response 7 First day? -X Response 8

Multiple Conditions After constructing our conditions table, we could use nested branching to solve the problem: A better idea is to use Boolean operators to clarify our code:

Operator Precedence OrderDescriptionOperator 1 Dot Operator. 2 Parenthesis (Work from inside out) () 3 Instance Operator new 4 Multiplication, Division, Modulus * / % 5 Addition, Subtraction, Concatenation + -

Operator Precedence (continued) OrderDescriptionOperator 6Assignment = += -= *= /= %= 7 Comparison Operators, =, = 8Inequality!= 9 Boolean AND && 10 Boolean OR ||

The Switch Structure Similar to multiple if/else statements, in that ONLY ONE BLOCK OF CODE EXECUTES and executes ONLY ONCE. Useful when the program asks the user to choose among more than two choices. Structure is divided into two parts: ◦ Switch statement – sets up the condition (test) ◦ Multiple cases – values to text against the condition

Parts of a Switch Structure Switch keyword – Tells JavaScript to test against a variable value. Cases – Tells the program what to do based on different types of test results. Breaks (CRITICAL) - Tells the program to “break out” of the ENTIRE structure once a case has been evaluates to TRUE and executes. Default – What to do when there are no more cases to evaluate (all previous cases evaluated to FALSE).

Switch Structure Example Code Example

Boolean Values When testing against Boolean values, you can use shortcuts (True Example): if(myVar == true) … is the same thing as if(myVar) … False Example: if(myVar == false) … is the same thing as if(!(myVar)) …

window.confirm() Method Boolean values are returned by the window.confirm() method. window.confirm() takes input from the user, based on which button they choose (OK=TRUE & CANCEL=FALSE) It looks and feels a lot like window.alert(), except that it has both an OK and a CANCEL button

window.confirm() & Boolean Example Code Example

Questions?

Resources JavaScript: The Definitive Guide by David Flanagan (O’Reilly, 2002) JavaScript Concepts & Techniques: Programming Interactive Web Sites by Tina Spain McDuffie (Franklin, Beedle & Associates, 2003) Extended Prelude to Programming: Concepts and Design by Stewart Venit (Scott/Jones, Inc., 2002)