Eric Roberts and Jerry Cain

Slides:



Advertisements
Similar presentations
Statement-Level Control Structures
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 4—Statement Forms The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Statement Forms C H A P T E R 4 The statements.
Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
ㅎㅎ logical operator if if else switch while do while for Third step for Learning C++ Programming Repetition Control Structures.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Chapter 4—Statement Forms The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Statement Forms C H A P T E R 4 The statements.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
CSCI 161 Lecture 7 Martin van Bommel. Control Statements Statements that affect the sequence of execution of other statements Normal is sequential May.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Control Statements Eric Roberts CS 106A January 15, 2016.
Expressions Eric Roberts CS 106A January 13, 2016.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Control Statements Eric Roberts CS 106A January 15, 2010.
Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
Five-Minute Review 1.What are classes and objects? What is a class hierarchy? 2.What is an expression? A term? 3.What is a variable declaration? 4.What.
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)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Discussion 4 eecs 183 Hannah Westra.
Five-Minute Review What are classes and objects? What is a class hierarchy? What is an expression? A term? What is a variable declaration? What is an assignment?
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
CHAPTER 4 Selection CSEG1003 Introduction to Computing
EGR 2261 Unit 4 Control Structures I: Selection
Boolean Expressions and If
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Expressions and Control Flow in JavaScript
JavaScript: Control Statements.
JavaScript: Control Statements I
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Control Structures – Selection
Five-Minute Review What is a class hierarchy?
Chapter 4: Control Structures I (Selection)
Java - Data Types, Variables, and Arrays
Chapter 8 JavaScript: Control Statements, Part 2
CS1100 Computational Engineering
Chapter 7 Additional Control Structures
During the last lecture we had a discussion on Data Types, Variables & Operators
T. Jumana Abu Shmais – AOU - Riyadh
3 Control Statements:.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 7 Conditional Statements
slides courtesy of Eric Roberts
Statement-Level Control Structures
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Chapter8: Statement-Level Control Structures April 9, 2019
Chap 7. Advanced Control Statements in Java
CSC215 Lecture Control Flow.
Controlling Program Flow
Chapter 4—Statement Forms
Presentation transcript:

Eric Roberts and Jerry Cain Control Statements Eric Roberts and Jerry Cain CS 106J April 11, 2017

Once upon a time . . .

Holism vs. Reductionism In his Pulitzer-prizewinning book, computer scientist Douglas Hofstadter identifies two concepts—holism and reductionism—that turn out to be important as you begin to learn about programming. Hofstadter explains these concepts using a dialogue in the style of Lewis Carroll: I will be glad to indulge both of you, if you will first oblige me, by telling me the meaning of these strange expressions, “holism” and “reductionism”. Achilles: Crab: Holism is the most natural thing in the world to grasp. It’s simply the belief that “the whole is greater than the sum of its parts”. No one in his right mind could reject holism. Anteater: Reductionism is the most natural thing in the world to grasp. It’s simply the belief that “a whole can be understood completely if you understand its parts, and the nature of their ‘sum’”. No one in her left brain could reject reductionism.

Control Statements

Statement Types in JavaScript Statements in JavaScript fall into three basic types: Simple statements Compound statements Control statements Simple statements are typically assignments, function calls, or applications of the ++ or -- operators. Simple statements are always terminated with a semicolon. Compound statements (also called blocks) are sequences of statements enclosed in curly braces. Control statements fall into two categories: Conditional statements that specify some kind of test Iterative statements that specify repetition

Boolean Expressions JavaScript defines two types of operators that work with Boolean data: relational operators and logical operators. There are six relational operators that compare values of other types and produce a true/false result: = == Equals < Less than !== Not equals <= Less than or equal to >= Greater than or equal to > Greater than For example, the expression n <= 10 has the value true if n is less than or equal to 10 and the value false otherwise. p || q means either p or q (or both) There are also three logical operators: && Logical AND || Logical OR ! Logical NOT p && q means both p and q !p means the opposite of p

Notes on the Boolean Operators Remember that JavaScript uses = for assignment. To test whether two values are equal, you must use the = = = operator. It is not legal in JavaScript to use more than one relational operator in a single comparison. To express the idea embodied in the mathematical expression 0 ≤ x ≤ 9 0 <= x && x <= 9 you need to make both comparisons explicit, as in The || operator means either or both, which is not always clear in the English interpretation of or. Be careful when you combine the ! operator with && and || because the interpretation often differs from informal English.

Short-Circuit Evaluation JavaScript evaluates the && and || operators using a strategy called short-circuit mode in which it evaluates the right operand only if it needs to do so. For example, if n is 0, the right operand of && in n !== 0 && x % n === 0 is not evaluated at all because n !== 0 is false. Because the expression false && anything is always false, the rest of the expression no longer matters. One of the advantages of short-circuit evaluation is that you can use && and || to prevent errors. If n were 0 in the earlier example, evaluating x % n would result in a division by zero.

The if Statement The simplest of the control statements is the if statement, which occurs in two forms. You use the first when you need to perform an operation only if a particular condition is true: if (condition) { statements to be executed if the condition is true } if (condition) { statements to be executed if the condition is true } else { statements to be executed if the condition is false } You use the second form whenever you need to choose between two alternative paths, depending on whether the condition is true or false:

Functions Involving Control Statements The body of a function can contain statements of any type, including control statements. As an example, the following function uses an if statement to find the larger of two values: function max(x, y) { if (x > y) { return x; } else { return y; } As this example makes clear, return statements can be used at any point in the function and may appear more than once.

The switch Statement JavaScript then looks for a case clause that matches expression. If expression is equal to v2, JavaScript chooses the second clause. When JavaScript executes a switch statement, it begins by evaluating expression. The switch statement provides a convenient syntax for choosing among a set of possible paths: If none of the values in the case clauses match the expression, JavaScript evaluates the statements in the default clause. JavaScript evaluates statements in the case or default clause until it reaches a break or a return statement. The switch statement provides a convenient syntax for choosing among a set of possible paths: switch ( expression ) { case v1: statements to be executed if expression = v1 break; case v2: statements to be executed if expression = v2 . . . more case clauses if needed . . . default: statements to be executed if no values match } switch ( expression ) { case v1: statements to be executed if expression = v1 break; case v2: statements to be executed if expression = v2 . . . more case clauses if needed . . . default: statements to be executed if no values match }

Example of the switch Statement The switch statement is useful when a function must choose among several cases, as in the following example: function monthName(month) { switch (month) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return undefined; }

The while Statement The while statement is the simplest of JavaScript’s iterative control statements and has the following form: while ( condition ) { statements to be repeated } while ( condition ) { statements to be repeated } When JavaScript encounters a while statement, it begins by evaluating the condition in parentheses. If the value of condition is true, JavaScript executes the statements in the body of the loop. At the end of each cycle, JavaScript reevaluates condition to see whether its value has changed. If condition evaluates to false, JavaScript exits from the loop and continues with the statement following the end of the while body.

Logging Output on the Console One of the easiest ways to illustrate the operation of the iterative control structures is to display a message on the JavaScript console on every cycle of the loop. The easiest way to do so is to invoke the console.log method, which displays one string value on the console. For example, calling console.log("hello, world"); prints the string "hello, world" on the console. Calls to the console.log method often use concatenation to assemble the string, as in this call from the next slide: console.log("digitSum(" + n + ") = " + result); The console.log method is useful in debugging. extremely

The digitSum Function n result 19 1729 n result n sum 1729 19 1 17 172 17 172 1729 11 19 9 18 digitSum(1729) = 19

The for Statement The for statement in JavaScript is a powerful tool for specifying the structure of a loop independently from the operations the loop performs. The syntax looks like this: for ( init ; test ; step ) { statements to be repeated } for ( init ; test ; step ) { statements to be repeated } JavaScript evaluates a for statement as follows: Evaluate init, which typically declares a control variable. 1. Evaluate test and exit from the loop if the value is false. 2. Execute the statements in the body of the loop. 3. Evaluate step, which usually updates the control variable. 4. Return to step 2 to begin the next loop cycle. 5.

Exercise: Reading for Statements Describe the effect of each of the following for statements: for (var i = 1; i <= 10; i++) 1. This statement executes the loop body ten times, with the control variable i taking on each successive value between 1 and 10. for (var i = 0; i < N; i++) 2. This statement executes the loop body N times, with i counting from 0 to N - 1. This version is the standard Repeat-N-Times idiom. for (var n = 99; n >= 1; n -= 2) 3. This statement counts backward from 99 to 1 by twos. for (var x = 1; x <= 1024; x *= 2) 4. This statement executes the loop body with the variable x taking on successive powers of two from 1 up to 1024.

The factorial Function The factorial of a number n (which is usually written as n! in mathematics) is defined to be the product of the integers from 1 up to n. Thus, 5! is equal to 120, which is 1 x 2 x 3 x 4 x 5. function fact(n) { var result = 1; for (var i = 1; i <= n; i++) { result = result * i; } return result; The following function definition uses a for loop to compute the factorial function:

The factorialTable Function min max i 8 7 min max i n result i n result i run this loop six more times 5040 1 7 8 6 1 7 7 1 6 1 120 5040 720 24 2 1 6 7 8 5 4 3 2 1 1 -> factorialTable(0, 7); 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 ->

Comparing for and while The for statement for ( init ; test ; step ) { statements to be repeated } is functionally equivalent to the following code using while: init; while ( test ) { statements to be repeated step; } The advantage of the for statement is that everything you need to know to understand how many times the loop will run is explicitly included in the header line.

The Checkerboard Program import "graphics"; const GWINDOW_WIDTH = 500; /* Width of the graphics window */ const GWINDOW_HEIGHT = 300; /* Height of the graphics window */ const N_COLUMNS = 8; /* Number of columns */ const N_ROWS = 8; /* Number of rows */ const SQUARE_SIZE = 35; /* Size of a square in pixels */ function Checkerboard() { var gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT); var x0 = (gw.getWidth() - N_COLUMNS * SQUARE_SIZE) / 2; var y0 = (gw.getHeight() - N_ROWS * SQUARE_SIZE) / 2; for (var i = 0; i < N_ROWS; i++) { for (var j = 0; j < N_COLUMNS; j++) { var x = x0 + j * SQUARE_SIZE; var y = y0 + i * SQUARE_SIZE; var sq = GRect(x, y, SQUARE_SIZE, SQUARE_SIZE); sq.setFilled((i + j) % 2 !== 0); gw.add(sq); }

The End