JavaScript: Control Statements I

Transcription

1 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1

2 7.2 Algorithms 3 Any computable problem can be solved by executing a series of actions in a specific order A procedure for solving a problem in terms of the actions to execute and the order in which the actions are to execute is called an algorithm Specifying the order in which statements are to be executed in a computer program is called program control 7.3 Pseudocode 4 Pseudocode An artificial and informal language that helps programmers develop algorithms Carefully prepared pseudocode may be converted easily to a corresponding JavaScript program Normally describes only executable statements the actions that are performed when the program is converted from pseudocode to JavaScript and executed 2

3 5 Software Engineering Observation 7.1 Pseudocode is often used to think out a program during the program-design process. Then the pseudocode program is converted to a programming language such as JavaScript. 7.4 Control Structures 6 Sequential execution Execute statements in the order they appear in the code Transfer of control Changing the order in which statements execute All programs can be written in terms of only three control structures sequence selection repetition 3

4 7.4 Control Structures (Cont.) 7 Flowchart A graphical representation of an algorithm or of a portion of an algorithm Drawn using certain special-purpose symbols, such as rectangles, diamonds, ovals and small circles Symbols are connected by arrows called flowlines, which indicate the order in which the actions of the algorithm execute 7.4 Control Structures (Cont.) 8 In a flowchart that represents a complete algorithm, an oval symbol containing the word Begin is the first symbol used; an oval symbol containing the word End indicates where the algorithm ends. In a flowchart that shows only a portion of an algorithm, the oval symbols are omitted in favor of using small circle symbols, also called connector symbols. Perhaps the most important flowcharting symbol is the diamond symbol, also called the decision symbol, which indicates that a decision is to be made. 4

5 9 Indicates a portion of an algorithm Fig. 7.1 Flowcharting JavaScript s sequence structure. 7.4 Control Structures (Cont.) 10 JavaScript provides three selection structures. The if statement either performs (selects) an action if a condition is true or skips the action if the condition is false. Called a single-selection structure because it selects or ignores a single action or group of actions. The if else statement performs an action if a condition is true and performs a different action if the condition is false. Double-selection structure because it selects between two different actions or group of actions. The switch statement performs one of many different actions, depending on the value of an expression. Multiple-selection structure because it selects among many different actions or groups of actions. 5

6 7.4 Control Structures (Cont.) 11 JavaScript provides four repetition statements, namely, while, do while while, for and for in in. Keywords cannot be used as identifiers (e.g., for variable names). 12 Common Programming Error 7.1 Using a keyword as an identifier is a syntax error. 6

7 Fig. 7.2 JavaScript keywords. 13 JavaScript keywords break case catch continue default delete do else false finally for function if in instanceof new null return switch this throw true try typeof var void while with Keywords that are reserved but not used by JavaScript abstract boolean byte char class const debugger double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile 2008 Pearson Education, Inc. All rights reserved. 7.4 Control Structures (Cont.) 14 Single-entry/single-exit control structures make it easy to build programs. Control structures are attached to one another by connecting the exit point of one control structure to the entry point of the next. Control-structure stacking. There is only one other way control structures may be connected Control-structure nesting 7

8 7.5 if Selection Statement 15 The JavaScript interpreter ignores white-space characters blanks, tabs and newlines used for indentation and vertical spacing Programmers insert white-space characters to enhance program clarity A decision can be made on any expression that evaluates to a value of JavaScript s boolean type (i.e., any expression that evaluates to true or false). The indentation convention you choose should be carefully applied throughout your programs It is difficult to read programs that do not use uniform spacing conventions 16 Good Programming Practice 7.1 Consistently applying reasonable indentation conventions throughout your programs improves program readability. We suggest a fixed-size tab of about 1/4 inch or three spaces per indent. 8

9 17 If grade >= 60, execute this statement Otherwise Fig. 7.3 Flowcharting the single-selection if statement. 18 Software Engineering Observation 7.2 In JavaScript, any nonzero numeric value in a condition evaluates to true, and 0 evaluates to false. For strings, any string containing one or more characters evaluates to true, and the empty string (the string containing no characters, represented as "") evaluates to false. Also, a variable that has been declared with var but has not been assigned a value evaluates to false. 9

10 7.6 if...else Selection Statement 19 Allows the programmer to specify that different actions should be performed when the condition is true and when the condition is false. 20 Good Programming Practice 7.2 Indent both body statements of an if...else statement. 10

11 7.6 if...else Selection Statement (Cont.) 21 Conditional operator (?:?:) Closely related to the if else statement JavaScript s only ternary operator it takes three operands The operands together with the?: operator form a conditional expression The first operand is a boolean expression The second is the value for the conditional expression if the boolean expression evaluates to true Third is the value for the conditional expression if the boolean expression evaluates to false 22 Otherwise If the condition is met This is executed This is executed Fig. 7.4 Flowcharting the double-selection if else statement. 11

12 7.6 if...else Selection Statement (Cont.) 23 Nested if else statements Test for multiple cases by placing if else statements inside other if else structures The JavaScript interpreter always associates an else with the previous if, unless told to do otherwise by the placement of braces ({} {}) The if selection statement expects only one statement in its body To include several statements, enclose the statements in braces ({ and }) A set of statements contained within a pair of braces is called a block 24 Good Programming Practice 7.3 If there are several levels of indentation, each level should be indented the same additional amount of space. 12

13 25 Software Engineering Observation 7.3 A block can be placed anywhere in a program that a single statement can be placed. 26 Software Engineering Observation 7.4 Unlike individual statements, a block does not end with a semicolon. However, each statement within the braces of a block should end with a semicolon. 13

14 27 Common Programming Error 7.2 Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors. 7.6 if...else Selection Statement (Cont.) 28 A logic error has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing, but the program produces incorrect results. 14

15 29 Good Programming Practice 7.4 Some programmers prefer to type the beginning and ending braces of blocks before typing the individual statements within the braces. This helps avoid omitting one or both of the braces. 30 Software Engineering Observation 7.5 Just as a block can be placed anywhere a single statement can be placed, it is also possible to have no statement at all (the empty statement) in such places. The empty statement is represented by placing a semicolon (;) where a statement would normally be. 15

16 31 Common Programming Error 7.3 Placing a semicolon after the condition in an if structure leads to a logic error in singleselection if structures and a syntax error in double-selection if structures (if the if part contains a nonempty body statement). 7.7 while Repetition Statement 32 while Allows the programmer to specify that an action is to be repeated while some condition remains true The body of a loop may be a single statement or a block Eventually, the condition becomes false and repetition terminates 16

17 33 Common Programming Error 7.4 If the body of a while statement never causes the while statement s condition to become true, a logic error occurs. Normally, such a repetition structure will never terminate an error called an infinite loop. Both Internet Explorer and Firefox show a dialog allowing the user to terminate a script that contains an infinite loop. 34 Common Programming Error 7.5 Remember that JavaScript is a case-sensitive language. In code, spelling the keyword while with an uppercase W, as in While, is a syntax error. All of JavaScript s reserved keywords, such as while, if and else, contain only lowercase letters. 17

18 35 And evaluate if this statement is still true Break out of the cycle when the statement is false If this statement is true Execute this statement Fig. 7.5 Flowcharting the while repetition statement. 7.8 Formulating Algorithms: Counter- Controlled Repetition 36 Counter-controlled repetition Often called definite repetition, because the number of repetitions is known before the loop begins executing A total is a variable in which a script accumulates the sum of a series of values Variables that store totals should normally be initialized to zero before they are used in a program A counter is a variable a script uses to count typically in a repetition statement 18

19 7.8 Formulating Algorithms: Counter- Controlled Repetition 37 Uninitialized variables used in mathematical calculations result in logic errors and produce the value NaN (not a number) JavaScript represents all numbers as floatingpoint numbers in memory Floating-point numbers often develop through division The computer allocates only a fixed amount of space to hold such a value, so the stored floatingpoint value can only be an approximation 38 Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. 7.6 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem. 19

21 41 Fig. 7.7 Counter-controlled repetition to calculate a class average (Part 3 of 3). 42 Common Programming Error 7.6 Not initializing a variable that will be used in a calculation results in a logic error that produces the value NaN Not a Number. You must initialize the variable before it is used in a calculation. 21

22 43 Software Engineering Observation 7.6 If the string passed to parseint contains a floating-point numeric value, parseint simply truncates the floating-point part. For example, the string "27.95" results in the integer 27, and the string " " results in the integer 123. If the string passed to parseint is not a numeric value, parseint returns NaN (not a number). 44 Common Programming Error 7.7 Using floating-point numbers in a manner that assumes they are represented precisely can lead to incorrect results. Real numbers are represented only approximately by computers. For example, no fixed-size floating-point representation of π can ever be precise, because π is a transcendental number whose value cannot be expressed as digits in a finite amount of space. 22

23 7.9 Formulating Algorithms: Sentinel- Controlled Repetition 45 Sentinel-controlled repetition Special value called a sentinel value (also called a signal value, a dummy value or a flag value) indicates the end of data entry Often is called indefinite repetition, because the number of repetitions is not known in advance Choose a sentinel value that cannot be confused with an acceptable input value 46 Common Programming Error 7.8 Choosing a sentinel value that is also a legitimate data value results in a logic error and may prevent a sentinel-controlled loop from terminating properly. 23

24 7.9 Formulating Algorithms: Sentinel- Controlled Repetition (Cont.) 47 Top-down, stepwise refinement A technique that is essential to the development of well-structured algorithms Approach begins with pseudocode of the top, the statement that conveys the program s overall purpose Divide the top into a series of smaller tasks and list them in the order in which they need to be performed the first refinement Second refinement commits to specific variables 48 Software Engineering Observation 7.7 Each refinement, as well as the top itself, is a complete specification of the algorithm; only the level of detail varies. 24

25 49 Error-Prevention Tip 7.1 When performing division by an expression whose value could be zero, explicitly test for this case, and handle it appropriately in your program (e.g., by printing an error message) rather than allowing the division by zero to occur. 50 Good Programming Practice 7.5 Include completely blank lines in pseudocode programs to make the pseudocode more readable. The blank lines separate pseudocode control structures and separate the program phases. 25

26 51 Software Engineering Observation 7.8 Many algorithms can be divided logically into three phases: an initialization phase that initializes the program variables, a processing phase that inputs data values and adjusts program variables accordingly, and a termination phase that calculates and prints the results. Initialize total to zero Initialize gradecounter to zero 52 Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print No grades were entered Fig. 7.8 Sentinel-controlled repetition to solve the class-average problem. 26

27 53 Software Engineering Observation 7.9 The programmer terminates the top-down, stepwise refinement process after specifying the pseudocode algorithm in sufficient detail for the programmer to convert the pseudocode to a JavaScript program. Then, implementing the JavaScript program will normally be straightforward. 54 Good Programming Practice 7.6 When converting a pseudocode program to JavaScript, keep the pseudocode in the Java-Script program as comments. 27

28 55 Software Engineering Observation 7.10 Experience has shown that the most difficult part of solving a problem on a computer is developing the algorithm for the solution. Once a correct algorithm is specified, the process of producing a working JavaScript program from the algorithm is normally straightforward. 56 Software Engineering Observation 7.11 Many experienced programmers write programs without ever using programdevelopment tools like pseudocode. As they see it, their ultimate goal is to solve the problem on a computer, and writing pseudocode merely delays the production of final outputs. Although this approach may work for simple and familiar problems, it can lead to serious errors in large, complex projects. 28

31 61 Good Programming Practice 7.7 In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user what the sentinel value is. 62 Common Programming Error 7.9 Omitting the braces that delineate a block can lead to logic errors such as infinite loops. 31

32 7.10 Formulating Algorithms: Nested Control Statements 63 Control structures may be nested inside of one another Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition 64 Fig Examination-results problem pseudocode. 32

34 67 Fig Examination-results calculation (Part 3 of 3). 68 Good Programming Practice 7.8 When inputting values from the user, validate the input to ensure that it is correct. If an input value is incorrect, prompt the user to input the value again. 34

35 7.11 Assignment Operators 69 JavaScript provides the arithmetic assignment operators +=, -=, *=, /= and %=, which abbreviate certain common types of expressions. 70 Performance Tip 7.1 Programmers can write programs that execute a bit faster when the arithmetic assignment operators are used, because the variable on the left side of the assignment does not have to be evaluated twice. 35

37 7.12 Increment and Decrement Operators 73 The increment operator, ++, and the decrement operator, --, increment or decrement a variable by 1, respectively. If the operator is prefixed to the variable, the variable is incremented or decremented by 1, then used in its expression. If the operator is postfixed to the variable, the variable is used in its expression, then incremented or decremented by 1. Fig Increment and decrement operators. 74 Operator Example Called Explanation ++ ++a preincrement Increment a by 1, then use the new value of a in the expression in which a resides. ++ a++ postincrement Use the current value of a in the expression in which a resides, then increment a by b predecrement Decrement b by 1, then use the new value of b in the expression in which b resides. -- b-- postdecrement Use the current value of b in the expression in which b resides, then decrement b by Pearson Education, Inc. All rights reserved. 37

39 77 Fig Preincrementing and postincrementing (Part 2 of 2). 78 Good Programming Practice 7.9 For readability, unary operators should be placed next to their operands, with no intervening spaces. 39

40 7.12 Increment and Decrement Operators (Cont.) 79 When incrementing or decrementing a variable in a statement by itself, the preincrement and postincrement forms have the same effect, and the predecrement and postdecrement forms have the same effect When a variable appears in the context of a larger expression, preincrementing the variable and postincrementing the variable have different effects. Predecrementing and postdecrementing behave similarly. 80 Common Programming Error 7.10 Attempting to use the increment or decrement operator on an expression other than a lefthand-side expression commonly called an lvalue is a syntax error. A left-hand-side expression is a variable or expression that can appear on the left side of an assignment operation. For example, writing ++(x + 1) is a syntax error, because (x + 1) is not a lefthand-side expression. 40

41 Fig Precedence and associativity of the operators discussed so far. 81 Operator Associativity Type right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality?: right to left conditional = += -= *= /= %= right to left assignment 2008 Pearson Education, Inc. All rights reserved. 41

Programming Languages: Java Lecture 1 Introduction to Java Instructor: Omer Boyaci 1 2 Course Information History of Java Introduction First Program in Java: Printing a Line of Text Modifying Our First

Java How to Program, 9/e Education, Inc. All Rights Reserved. 1 Any computing problem can be solved by executing a series of actions in a specific order. An algorithm is a procedure for solving a problem

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ program,

Adjusted/Modified by Nicole Tobias Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types

switch Multiple-Selection Statement (This feature is rarely useful, although it s perfect for programming the iterative song The Twelve Days of Christmas!) If no match occurs, the default case is executed,

14 Chapter 2 Values, Variables, and Types In this chapter we explore the primitive building blocks that are used to develop Java programs. We experiment with the following concepts within DrJava s interactive

Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

7 Introduction to C++ 7.1 Introduction C++ is an extension to C Programming language. It was developed at AT&T Bell Laboratories in the early 1980s by Bjarne Stroustrup. It is a deviation from traditional

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

INTERNATIONAL EDITION Internet & World Wide Web HOW TO PROGRAM Fifth Edition Paul Deitel Harvey Deitel Abbey Deitel Deitel Series Page How To Program Series C++ How to Program, 8/E C How to Program, 6/E

T U T O R I A L 7 Objectives In this tutorial, you will learn to: Understand basic problemsolving techniques. Understand control structures. Understand and create pseudocode. Use the If Then and If Then

Control Structures Processing and Java There is no difference between Processing syntax and Java syntax Processing has it s own IDE and provides lots of methods to do drawing and animation The main IDEs

Page 1 of 63 [Page 185] Chapter 5. Control Statements: Part 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William

Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

Variables and Constants Variable A location in computer's memory in which a value may be stored from which that value may be retrieved Storage of Variables Setting Aside Memory Defining a variable in C++

Control Statements: Part 2, Solutions 5 Let s all move one place on Lewis Carroll The wheel is come full circle William Shakespeare How many apples fell on Newton s head before he took the hint! Robert

Going from Python to C Darin Brezeale December 8, 2011 Python is a high-level, interpreted language. C has many of the same types of programming constructs as in Python: arrays, loops, conditionals, functions,

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

Chapter Four MULTIPLE CHOICE 1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d. iteration 2. The decision structure

Group 1 Question 1. What is the correct value to return to the operating system upon the successful completion of a program? A. -1 B. 1 C. 0 D. Programs do not return a value. Question 2. What is the only

Adjusted/Modified by Nicole Tobias Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use

Computers in Engineering Pseudocode and C Language Review Pseudocode Pseudocode is an artificial and informal language that helps you develop algorithms Pseudocode is similar to everyday English; it is

While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true

Lesson Outcomes At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable (LCV) Use increment (++) and decrement (--) operators Program

Program Control Essentials of repetition Loop control variable Counts the number of repetitions in the counter-controlled loop Controls the execution of loop Sentinel value Indicates the end of data when

CHAPTER 2 PROBLEM SOLVING This chapter will cover the following topics: Problem Solving Concepts for the Computer Pre-Programming Phase Programming Or Implementation Phase What Problem Can Be Solved By

- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

C++ Basics C++ Basics: 2.1 Variables and Assignments Variables and Assignments Input and Output Data Types and Expressions Simple Flow of Control Program Style A C++ variable can hold a number or other

Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

Chapter 6 Repetition 6-1 Repetition in C++ The final control/logic structure is repetition: Repetition repeating a block of code until a condition is met There are three repetition statements available

What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

- 1 - GETTING STARTED WITH C++ Programming is a core activity in the process of performing tasks or solving problems with the aid of a computer. An idealised picture is: PROBLEM COMPUTER SOLUTION Unfortunately

Notes on Algorithms, Pseudocode, and Flowcharts Introduction Do you like hot sauce? Here is an algorithm for how to make a good one: Volcanic Hot Sauce (from: http://recipeland.com/recipe/v/volcanic-hot-sauce-1125)

Chapter 4 Operators & Arithmetic 4-1 Arithmetic in C++ Arithmetic expressions can be made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition)

2 Introduction to C++ Programming OBJECTIVES In this chapter you will learn: To write simple computer programs in C++. To write simple input and output statements. To use fundamental types. Basic computer

Learn the Java Programming Language This portion of my site is dedicated to teach the basics of the Java programming language. It is geared towards non-programmers so if you already have some programming

C programming Intro to syntax & basic operations Example 1: simple calculation with I/O Program, line by line Line 1: preprocessor directive; used to incorporate code from existing library not actually

[Page 70 (continued)] Exercises 2.7 Discuss the meaning of each of the following objects: a. std::cin b. std::cout 2.8 Fill in the blanks in each of the following: a. are used to document a program and

Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify

Unit-4 Expressions and Assignment Statements Introduction Expressions are the fundamental means of specifying computations in a programming language. To understand expression evaluation, need to be familiar

C AND C++ PROGRAMMING Bharathidasan University A Courseware prepared by University Informatics Centre Part I - Programming in C Getting Started This courseware is intended to be an introduction to C programming

Chapter 3 Operators and Control Flow I n this chapter, you will learn about operators, control flow statements, and the C# preprocessor. Operators provide syntax for performing different calculations or

Chapter 4 C Program Control Objectives of this chapter: Repetitions will be considered in greater detail for.. repetition do while repetition Also multiple selection switch case statement will be learned.