Chapter 6: Conditional Statements and Loops

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Advertisements

Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
The University of Texas – Pan American
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
LOGO Conditional Statements & Loops in JavaScript CHAPTER 10 Eastern Mediterranean University School of Computing and Technology Department of Information.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
TK 1914 : C++ Programming Control Structures I (Selection)
JavaScript, Fourth Edition
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Decision Making and Branching (cont.)
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
LESSON 2: CONTROL STRUCTURES JAVASCRIPT. CONTROL STRUCTURES – ALLOWS US TO CHANGE THE ORDERING OF HOW THE STATEMENTS IN OUR PROGRAMS ARE EXECUTED.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - JavaScript: Control Structures II Outline 9.1 Introduction 9.2 Essentials of Counter-Controlled.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
Core Java Statements in Java.
CHAPTER 4 DECISIONS & LOOPS
Chapter 4 – C Program Control
‘C’ Programming Khalid Jamal.
Chapter 3 Control Statements
Chapter 6: Loops.
REPETITION CONTROL STRUCTURE
Chapter 3: Decisions and Loops
Decisions Chapter 4.
Chapter 4: Making Decisions.
Python: Control Structures
CHAPTER 4 Selection CSEG1003 Introduction to Computing
PROGRAM CONTROL STRUCTURE
Chapter 4: Making Decisions.
JavaScript: Control Statements.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
Chapter 19 JavaScript.
Arrays, For loop While loop Do while loop
Loop Control Structure.
Outline Altering flow of control Boolean expressions
Chapter 8 JavaScript: Control Statements, Part 2
Iteration: Beyond the Basic PERFORM
3 Control Statements:.
Repetition Control Structure
3. Decision Structures Rocky K. C. Chang 19 September 2018
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Control Statements Paritosh Srivastava.
REPETITION Why Repetition?
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

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

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

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.

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.

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

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

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

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

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.

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.

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”

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>

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”

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>

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>

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.

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

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.

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.

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

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

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

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

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.

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

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.

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.

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>

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.

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

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

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.

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

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.

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

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

The while Statement: Example 3 In the following example, the program calculates 1+2+3+ … + 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

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);

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

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

The do/while Statement: An Example In the following example, the program calculates 1+2+3+ … + 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

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

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

The for Statement: An Example In the following example, the program calculates 1+2+3+ … + 100 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

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.

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>