Types of Flow of Control

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Repeating Actions While and For Loops
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
1 Flow of control Sequential Executing instructions one by one, in exact order given Selection Choosing to execute a particular set of statements depending.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
Chapter 7 Problem Solving with Loops
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Lecture 4b Repeating With Loops
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Repetition Structures Chapter 9
The switch Statement, and Introduction to Looping
Topics Introduction to Repetition Structures
Python: Control Structures
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 5: Control Structures II
CHAPTER 5A Loop Structure
CS1371 Introduction to Computing for Engineers
Lecture 2 Introduction to Programming
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Algorithm Analysis CSE 2011 Winter September 2018.
Java Programming: Guided Learning with Early Objects
Ch 7: JavaScript Control Statements I.
JavaScript: Control Statements.
Topics Introduction to Repetition Structures
Lecture 4B More Repetition Richard Gesick
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Control Structures - Repetition
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
Java Programming Loops
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
Coding Concepts (Basics)
3 Control Statements:.
Introduction to Problem Solving and Control Statements
Faculty of Computer Science & Information System
Chapter 6: Repetition Statements
Computing Fundamentals
Loop Statements & Vectorizing Code
Chapter 5: Control Structures II (Repetition)
Java Programming Loops
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Loop Statements & Vectorizing Code
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
REPETITION Why Repetition?
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Types of Flow of Control Sequential is restrictive, cannot solve all problems Just as humans change their minds depending on circumstances , machines should too ;-)) Selective Choosing to execute a particular set of statements depending on a condition Use the “IF Statement” or the “Switch Statement” Repetitive Allows Iteration (Controlled Repetition): Executing a set of statements more than one time  Use the “FOR Loop” or the “WHILE Loop”

Iteration = Controlled Repetition Looping = Executing a set of statements more than once, i.e., looping Two types of Loops The “FOR – Loop” : repeat a fixed number of times The “WHILE – Loop”: repeat conditionally, where the condition must be specified explicitly by the programmer  KEY  Ensure that the loop will stop! Note 1: The Loop must include a mechanism for stopping an infinite repetition Note 2: MATLAB array operations often allow to avoid loops

PART I : The For-Loop … more exactly, … technically speaking … the For-end Loop

FOR-Loop Template Repeating a fixed number of times Control repetition with a loop-control variable: - Initialize value - Test value & decide to proceed or not - If proceeding,  Change value  Repeat, starting with the test for <loop ctrl> done statements to execute

Two types of syntax for the For-end Loop 1 – The syntax is based on the use of an index incremented automatically between a Start Value and a Stop Value 2 – The syntax is based on an index defined in a row vector

for index = Start Value: Increment : Stop Value 1 – The syntax is based on the use of an index incremented automatically between a Start Value and a Stop Value for index = Start Value: Increment : Stop Value . . . % Code block end  Details on next slide 2 – The syntax is based on an index pre-defined in a row vector for index = [ v1 v2 v3 v4 …vx] end  Details later

1 – Formal Syntax of the “For-end Loop” based on an index Formal syntax using an index for k = f : s : l . . . % Instruction block end

Examples 1/2 for k = 5:10:35 % StartingValue:Increment:LastValue x = k^2 % Instruction block end k (the index) takes the following values: 5 15 25 35 The resulting values of x are: 25 225 625 1225

Examples 2/2 Non-integer increment is okay Implied increment of 1 for k = 2:0.5:3 disp(k) end for k = 1:4 for k = 0 : -2 : -6 for k = 0:-2:-7 Non-integer increment is okay Implied increment of 1 Negative increment is okay What values does k take? 9

Rules for “For-end Loop” based on an index - 1/3 Index variable name: “i” or “j” should not be used if the current Matlab program uses complex numbers, k is traditional The step value k may be negative If k is omitted, the step value defaults to 1 for k = 1:4 k takes successively the following values: 1, 2, 3, 4 If k is positive, the loop body will not be executed if the start value is greater than the stop value If k is negative, the loop body will not be executed if the start value is less than the stop value

Rules for “For-end Loop” based on an index - 2/3 If the start value = the stop value , the loop body will be executed only once If the values of the step value k, the start value, and the stop value are such that k cannot be equal to the stop value, then, if the step value k is positive, the last pass is the one where the step value k has the largest value that is smaller than the stop value (i.e. k = 6:10:40 produces four passes with k = 6, 16, 26, 36). If the step k value is negative, then, the last pass is the one where k has the smallest value that is larger than the stop value 11

Rules for “For-end Loop” based on an index - 3/3 The value of the index k should not be redefined within the loop If the step value k is not an integer, rounding errors can cause the instruction bock to execute a different number of times from what was intended Each “for command”, a program must have an “end command” The value of the step value k is not displayed automatically. It is possible to display the value in each pass (sometimes useful for debugging) by inserting k as one of the commands within the instruction block On completion of the loop, the step value k retains its last value 12

2 - Syntax of the “For-end Loop” based on a Row Vector for k = [ v1 v2 v3 v4 …vx] . . . % Instruction block end The loop values (k) are exclusively those specified in the row vector The loop is executed length(k) times The for-loop automatically sets the value of the variable to each element of the vector in turn and executes the instruction block with that value.

2 - Syntax of the “For-end Loop” based on a row vector - Example 1 temperatures = [63 72 76 71 64 69]; average = mean(temperatures) for x = temperatures if x > average disp('warmer') else disp('cooler') end end;

2 - Syntax of the “For-end Loop” based on a row vector - Example 2 temperatures = [63 72 76 71 64 69]; average = mean(temperatures) for x = temperatures if x > average disp('warmer') else disp('cooler') end end; initialize scope of loop body of loop

2 - Syntax of the “For-end Loop” based on a row vector - Example 3 for k = [1,3,7,8,9,11] disp(k) end for k = [true true false] k takes on successive values, one at a time What values does k take? What is displayed?

Design Steps for Loops Identify a task that can be accomplished if some steps are repeated (These steps form the loop body) Define a starting point Define a stopping point Keep track of (and measure) progress Make sure the loop will stop!  If necessary use the “Break command” or the “Continue command” (Details later in this chapter)

Example: “Accumulate” a Solution Calculate the average of 10 entered numbers: % Average 10 numbers from user input n = 10; % number of data values total = 0; % initialize accumulator for k = 1:n % read and process input value num = input('Enter a number: '); total = total + num; end avrg = total/n; % average of n numbers fprintf('Average is %f\n', avrg)

A Larger Example A stick of unit length is split into two pieces. The stick is broken at a randomly selected point. On average, how long is the resulting shorter piece? Possible approaches: A physical experiment? A thought experiment?  Is called analysis Computational experiment!  Is called simulation We must do numerous trials, and we need to report how many!

One Simulated Trial % one trial of the experiment breakPt = rand(1); shortPiece = min(breakPt, 1-breakPt); Why? rand(1) returns a 1x1 array of random number value(s) between 0 and 1 min(breakPt, 1-breakPt) returns the minimum of the 2 numbers

Pick random number from 0 to 1 Solution Flow Chart Start For n times Pick random number from 0 to 1 Find shortest Piece Calculate average Print average End

How One Trial Fits into the Algorithm %Repeat n times % one trial of the experiment breakPt = rand(1); shortPiece = min(breakPt, 1-breakPt); %take the average %Print result

Complete Matlab Script n = 10000; % number of trials total = 0; % accumulated length so far for k = 1:n % one trial of the experiment breakPt = rand(1); shortPiece = min(breakPt, 1-breakPt); total = total + shortPiece; end avgLength= total/n; fprintf(‘Average length is %f\n’,avgLength)

PART II : The While-Loop … more exactly, … technically speaking … the While-end Loop

The “While – end” Loop The While – end Loops are used in situations when looping is needed but the number of passes is not known ahead of time. In While – end Loops the number of passes is not specified when the looping process starts. Instead, the looping process continues until a stated condition is satisfied.

Let’s start with an example: A Challenge Suppose for our previous accumulate example, you want to average any set of numbers entered by the user, not just ten…  Solution

The WHILE-end Loop We may not know ahead exactly how many times we want the loop to execute We may want to execute the loop only under certain conditions WHILE-loops generally provide greater control over execution of the loop body, but… the Programmer must initialize, test, & change loop control variable(s) to ensure loop ends!

WHILE-end Loop Template initialize MATLAB construct: <initialization> while <logical expression> <code block> end while <expression> false true statements to execute MUST make changes so that the logical expression will eventually become false!

Formal Syntax of the “While-end Loop” Initialization of the variables used in the conditional expression while conditional expression . . . % Instruction block end % Example x = 2 while x < 10 % Begin While loop x = x ^ 2 % Instruction block end % End While loop  Output: 2 4

A “While-end Loop” executes properly only if: 1/3 The conditional expression in the while command includes at least one variable The variables in the conditional expression have assigned values when MATLAB executes the while command for the first time (i.e., are initialized before the loop starts)

A “While-end Loop” executes properly only if: 2/3 At least one of the variables in the conditional expression is assigned a new value in the instruction block between the while and the end. Otherwise, once the looping starts it will never stop (indefinite loop) since the conditional expression will remain true

A “While-end Loop” executes properly only if: 3/3 How to deal with indefinite loops An indefinite loop can be avoided by counting the passes and stopping the looping if the number of passes exceeds some large value This can be done by adding the maximum number of passes to the conditional expression, or by using the break command Since “to err is human” … no one is free from making mistakes, if a program enters in an indefinite loop, the user can stop the execution by pressing simultaneously: “Ctrl + C” or “Ctrl + Break” keys

While-end Loop: a Simple Example x = 5; %initialization while x < 25 % conditional expression disp(x) % begin loop body x = 2*x - 1; % change loop variable end In a while-loop, YOU, the programmer, must ensure the loop variable has an initial value before the loop starts! Inside the while-end-loop, the instruction block must assign a new value to the variable(s) in the conditional expression In a while-loop, it is crucial for YOU, the programmer, to ensure the loop will end! (Think of using “break” and “continue”)

The While-end Loop: Example 2 Initial: x=5, test x<25? True Pass1: x gets 9, test x<25? True Pass2: x gets 17, test x<25? True Pass3: x gets 33, test x<25? False and thus do NOT perform loop body again! x = 5; k = 0; while x < 25 k = k + 1; y(k) = 3*x; x = 2*x -1; end

Watch Out for Infinite Loops… A loop that never ends… x = 8; while x ~= 0 x = x – 3; end What values does x take? In MS-windows… <control>c is your friend

Example: Calculate Average, Re-visited Find the average of a set of numbers entered by a user Clearly, we need to “repeat” the input statement, but how many times?  That is up to the user! i.e., this is decided at run-time ( = during execution) So how do we know when to stop? 2 choices: ask or designate a signal value

Calculate Average, cont’d Input/Output Algorithm ? set of values … average

Programming While-end Loops YOU, the programmer, must figure out: What will be repeated? What must be initialized? When/how will the loop stop? What order do the repeated statements need to be in? Note: there are many ways to skin a cat!

Will This Work??? % This program calculates the average of a series of numbers entered by the user total = 0; % initialize for accumulator count = 0; % initialize count for how many numbers number = 0; % initialize for the test expression while (number ~= -999) % use -999 as a signal number = input('enter a number (-999 to end): '); count = count + 1; total = total + number; end avrg = total/count; % calculate the average fprintf('Average is %f\n', avrg)

What is Different Here??? total = 0; % initialize accumulator count = 0; % initialize counter of how many numbers % get the first value to initialize for the expression number = input('enter a number (-999 to end): '); while (number ~= -999) count = count + 1; total = total + number; end if count > 0 avrg = total/count; %calculate the average fprintf('Average is %f\n', avrg) else disp('no numbers were entered')

The “BREAK Command” When inside a loop (for or while), the break command terminates the execution of the loop (the whole loop, not just the last pass). When the break command appears in a loop, Matlab jumps to the end command of the loop and continues with the next command (does not go back to the for or while command of that loop). If the break command is inside a nested loop, only the nested loop is terminated. The break command is usually used within a conditional statement. In loops it provides a method to terminate the looping process if some condition is met, e.g., if the number of loops exceeds a predetermined value, or an error in some numerical procedure is smaller than a predetermined value.

The “CONTINUE Command” The “Continue Command” can be used inside a “for loop” or a “while loop” to stop the present pass and start the next pass in the looping process. The “Continue Command” is usually a part of a conditional statement. When Matlab reaches the continue command, it skips to the end of the innermost loop and then starts a new pass.

Again … Design Steps for Loops Identify a task that can be accomplished if some steps are repeated (These steps form the loop body) Define a starting point Define a stopping point Keep track of (and measure) progress Make sure the loop will stop!  If necessary use the “Break command” or the “Continue command”