Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Conditional Statements and Loops

Similar presentations


Presentation on theme: "Chapter 6: Conditional Statements and Loops"— Presentation transcript:

1 Chapter 6: Conditional Statements and Loops
CSC160 Chapter 6: Conditional Statements and Loops

2 Outline Flow control introduction Selection control if statement
Nested selection control switch statement Loop control while statement do/while statement for statement Nested loop control

3 Flow Control The order in which statements are executed in a program is called the flow control. In the examples we used before, flow control is sequential, i.e., when one statement is finished executing, control passes to the next statement in the program However, we can change the flow control to non-sequential by using control structures.

4 Flow Control (cont’d) A control structure is a special statement used to alter the normally sequential flow control. It transfers control to a statement other than the one that physically comes next. We have two main control statements: Conditional statements – Program acts differently according to different conditions. Loops – Program performs similar operations for many times.

5 Selection Control Structure
A selection (or branching) control structure is used when we want the computer to choose between alternative actions. We define a condition, whose result is either true or false. The computer makes the decision and executes different sequences of instructions based on the result of the condition. If the condition is true, the computer executes an action (optional) If the condition is false, the computer executes another action

6 Selection Control Structure (cont’d)
Condition true false Action 1 Action 2 Is it raining? true false Stay at home Go outside

7 Conditional Statements
Rather than executing every single line of code in the script as it is, you could have certain sections of the script be executed only when a particular condition is met. if statement switch statement

8 The if Statement The if statement is the fundamental control structure that allows branches in the flow control. With the if statement, we can ask a question and choose a action. If a certain condition is satisfied (true), perform an action; Otherwise (false), perform a different action The if statement comes in two forms The if-then-else form The if-then form

9 The if Statement: if-then-else Form
if (condition) statementblock1 else statementblock2 { statement1; statement2; statementn; } A block of statement If the condition specified in the brackets is true, then the instructions in the first statement block (statementblock1) is performed; Otherwise (false), the second statement block (statementblock2) is executed.

10 The if Statement: if-then-else Form (cont’d)
If there is only one statement inside the block, the curly brackets can be removed. If there are more than one statement inside the block, we must use the curly brackets to surround the statements. The condition inside the brackets can be: A variable with a Boolean value (true or false). An expression that compares two values using a comparison operator. Other logical expressions that include logical operators.

11 The if Statement: if-then-else Form Example 1
Prompt for the input of an integer from the keyboard If the number is greater than zero, print “This is a positive number” Otherwise, print “This is zero or a negative number” true The number is greater than 0 false Print “This is a positive number” Print “This is zero or a negative number”

12 if-then-else: Code (positive number)
<html> <head> <title>Calculation</title> </head> <body> <SCRIPT language="JavaScript"> <!-- var theinput; theinput = prompt("Please input an integer","0"); var x = parseInt(theinput); if (x > 0) // A comparison between two values: x and zero { document.write("This is a positve number"); document.write(“<BR>”); } else document.write("This is zero or a negative number"); //--> </SCRIPT> </body> </html>

13 The if Statement: if-then-else Form Example 2
Prompt for the input of an integer from the keyboard If the number is an even number, print “This is an even number” Otherwise, print “This is an odd number” true false Is x%2 equal to 0? Print “This is an even number” Print “This is an odd number”

14 if-then-else: Code (even number)
<html> <head> <title>Calculation</title> </head> <body> <SCRIPT language="JavaScript"> <!-- var num; num = prompt("Please input an integer",""); var x = parseInt(num); if (x%2 == 0) // A comparison between two values: x%2 and 0 document.write("This is an even number"); else document.write("This is an odd number"); //--> </SCRIPT> </body> </html>

15 if-then-else: Code (using a boolean variable)
<html> <head> <title>Calculation</title> </head> <body> <SCRIPT language="JavaScript"> <!-- var num; num = prompt("Please input an integer",""); var x = parseInt(num); var y; y = (x%2 == 0); if (y) // y contains a Boolean value (true or false) document.write("This is an even number"); else document.write("This is an odd number"); //--> </SCRIPT> </body> </html>

16 The if Statement: if-then-else Form Example 3
In the following example, we prompt for the input of the current month number(1 – 12). Then, we check whether the input number is outside the range [1, 12]. If yes, this number is invalid for the month and we print an error message to the Web page. Otherwise, output the current month to the Web page. The condition in the if statement is specified by a logical expression that contains the logical operator || (OR). More than one logical operators can be used to form a more complicated logical expression to specify the condition in the if statement.

17 The if Statement: if-then-else Form Example 3 (cont’d)
var num = prompt(“Please enter the month”, “”); var month = parseInt(num); if ((month <=0 ) || (month > 12)) { document.write(“Invalid input!”); } else document.write(“The curremnt month is: ”); document.write(month); Invalid input! The input is -1 The current month is: 6 The input is 6

18 The if Statement: if-then Form
if (condition) statementblock1 { statement1; statement2; statementn; } A block of statement statementblock1 specifies the action to perform when the condition exists. statementblock1 can be a single statement, or a sequence of statements that are grouped together.

19 The if Statement: if-then Form (cont’d)
If the condition specified in the brackets is true, then the instructions in statementblock1 will be performed. Otherwise, statementblock1 will be skipped.

20 if-then-else Form vs. if-then Form
In the if-then form, when the condition is false, the program “jumps to” the statement that follows the if block. condition true false statementblock1 statementblock2 The statement that physically follows the if statement if-then-else form condition true false statementblock1 The statement that physically follows the if statement if-then form

21 if-then-else Form VS. if-then Form: Examples
var num = prompt(“Please enter an integer”, “”); var flag = parseInt(num); if (flag > 0) document.write(“It is greater than 0”); else document.write(“It is less than or eqal to 0”); document.write(“<BR>” + “The end”); It is greater than 0 The end. Input is 3 It is less than or equal to 0 Input is -5 If-then-else form var num = prompt(“Please enter an integer”, “”); var flag = parseInt(num); if (flag > 0) document.write(“It is greater than 0”); document.write(“<BR>” + “The end”); It is greater than 0 The end. Input is 3 Input is -5 If-then form

22 Nested if Statements An if statement can be placed inside the block of statements of another if statement. This is used to create a nested control structure. Is it raining? true false Stay at home Go outside Today is Saturday or Sunday Go to school The inner if statement The outer if statement

23 Nested if Statements: An Example
In the following example, we prompt for the input of the current month. The program determines in range (1~3, 4~6, 7~9, or 10~12) the current month is. It is in range 1~3 The input is 1 var num = prompt(“Please enter the month”, “”); var month = parseInt(num); if (month < 7) { if (month < 4) { document.write(“It is in range 1~3”); } else { document.write(“It is in range 4~6”); } } if (month < 10) { document.write(“It is in range 7~ 9”); } { document.write(“It is in range 10~12”); } It is in range 4~6 The input is 6 It is in range 7~9 The input is 8 The input is 12 It is in range 10~12

24 The switch Statement An if statement allows us to have two branches.
The nested if statements allows us to have multiple branches. The switch statement is a selection control structure that allows us to list multiple branches A switch statement evaluates the expression inside the brackets. The value of this expression – an expression whose value is matched with a label (a constant expression) attached to a branch – determines which one of the branches is executed.

25 The switch Statement (cont’d)
switch (expression) { case constant_expression1: statement11 break; case constant_expression2: statement21 case constant_expressionn: statementn1 default: statement01 }

26 The switch Statement (cont’d)
If a match is found, execution begins from the point where the match is found. If no match is found and the default case is provided, execution begins from the point after default: The break statement is used to skip all remaining statements in the switch structure and jump to the statement following the closing curly bracket.

27 The switch Statements: An Example
In the following example, we prompt for the input of the day of the week and print the schedule for that day. We assume that the input “M”, “T”, “W”, “R”, “F”, “SAT”, and “SUN” represent Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday respectively.

28 The switch Statements: An Example (cont’d)
<html> <head> <title>Calculation</title> </head> <body> <SCRIPT language="JavaScript"> <!-- var day = prompt("What is the day of the week?", ""); switch(day) { case "M": document.write("Work"); break; case "T": document.write("Basketball"); case "W": document.write("CSC160"); case "R": document.write("CSC190"); case "F": document.write("Meeting"); case "SAT": document.write("Enjoy the weekend!"); case "SUN": document.write("Enjoy the weekend!"); default: document.write("Invalid input"); } //--> </SCRIPT> </body> </html>

29 Loops A loop is a control structure that causes a statement or a group of statements to be executed repeatedly. It executes the same statement (statements) again and again, as long as a certain condition is satisfied. An example is that I want to walk around a building for 100 circles. Every time I pass the entrance of the building, I ask whether the number of circles is less than 100. If yes, I continue walking around the building. If not, I stop walking.

30 Loops (cont’d) true Number of circles < 100 false
Walk around the building Stop walking and enter the building

31 The while Statement The while statement can be used to implement the loop control structure. The syntax for the while statement is as follows: while (condition) statementblock { statement1; statement2; statementn; } Statement block

32 The while Statement (cont’d)
The statementblock specifies what actions we want to repeat as long as the condition is satisfied. The statementblock can be a single statement, or a sequence of statements that are grouped together.

33 The while Statement (cont’d)
while (condition) blockstatement The statement that follows Is the condition true? statementblock true false The statement that physically follows the while statement

34 while Statement vs. if Statement
condition statementblock true false The statement that physically follows the while statement while condition statementblock true false The statement that physically follows the if statement if While: The statementblock can be executed for at least one time if the condition is satisfied. If: The statementblock can be executed only once if the condition is satisfied.

35 The while Statement: Example 1
In the first example, we keep increasing the value of the variable circles until it reaches 100. var circles = 0; while (circles <100) circles = circles + 1;// a single statement document.write(“Number of circles is: ” + circles); Number of circles is: 100 On the Web page

36 The while Statement: Example 2
In the second example, we calculate 5*10 using the while statement. var i = 0, total = 0; while (i <10) { total = total + 5; i = i + 1; } // a block of statements document.write(“The total (5*10) is: ” + total); The total (5*10) is: 50 On the Web page

37 The while Statement: Example 3
In the following example, the program calculates … + 20 and prints the result to the Web page. <html> <head> <title> JavaScript with loops </title> </head> <body> <SCRIPT language = "JavaScript"> <!-- var sum = 0; var i; i = 1; while (i<=100) { sum = sum + i; i++; } document.write(" The sum is = " + sum); //--> </SCRIPT> </body> </html> On the Web page The sum is 5050

38 The do/while Statement
The do/while statement can be used to implement the loop control structure. The syntax for the do/while statement is as follows: First, the sequence of statements is executed once, no matter whether the condition is true of false. Then repeat this sequence of statements as long as the condition is true. do { statement1; statementn; } while (condition);

39 while Loop vs. do/while Loop
Is the condition true? false The statement that physically follows the while statement Statement1 Statement2 true do/while statement Is the condition true? true false The statement that physically follows the while statement Statement1 Statement2 while statement

40 while Loop vs. do/while Loop Examples
var i = 10; while (i < 10) { i = i + 1; } document.write("i = " + i); i = ? On the Web page var i = 10; do { i = i + 1; } while (i<10); document.write("i = " + i); i = ? On the Web page

41 The do/while Statement: An Example
In the following example, the program calculates … + 10 and prints the result to the Web page <html> <head> <title> JavaScript with loops </title> </head> <body> <SCRIPT language = "JavaScript"> <!-- var sum = 0; var i; i = 1; do { sum = sum + i; i++; } while (i<=10) document.write(" The sum is = " + sum); //--> </SCRIPT> </body> </html> On the Web page The sum is 55

42 The for Statement Another approach to realize the loop structure is the for statement. for (initialization_statement; condition; update_statement) { statement1; statement2; statementn; }

43 The for Statement (cont’d)
true Statement1 Statement2 Is the condition true? Initialization_statement Update_statement false Statements that physically follow the for statement

44 The for Statement: An Example
In the following example, the program calculates … and prints the result to the Web page. <html> <head> <title> JavaScript with loops </title> </head> <body> <SCRIPT language = "JavaScript"> <!-- var sum = 0; var i; for (i=1; i<=100; i++) { sum = sum + i; } document.write("The sum is = " + sum); //--> </SCRIPT> </body> </html> On the Web page The sum is 5050

45 Nested Loops A loop structure can be placed inside the block of statements of another loop structure. In the following example, the program prompts for the user input of an integer. Then the program prints several lines of stars into the web page. The number of lines as well as the number of stars in each line are equal to the number from the input.

46 Nested Loops (cont’d) <html>
<head> <title> JavaScript with loops </title> </head> <body> <SCRIPT language = "JavaScript"> <!-- var i, j; var num = prompt("Please enter an integer", ""); var n = parseInt(num); for (i=1; i<=n; i++) { for (j=1; j<=i; j++) document.write("*"); } document.write("<BR>"); //--> </SCRIPT> </body> </html>


Download ppt "Chapter 6: Conditional Statements and Loops"

Similar presentations


Ads by Google