Presentation is loading. Please wait.

Presentation is loading. Please wait.

Types of Flow of Control

Similar presentations


Presentation on theme: "Types of Flow of Control"— Presentation transcript:

1 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”

2 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

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

4 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

5 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

6 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

7 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

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

9 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

10 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

11 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

12 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

13 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.

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

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

16 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?

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

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

19 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!

20 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

21 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

22 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

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

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

25 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.

26 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

27 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!

28 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!

29 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

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

31 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

32 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

33 While-end Loop: a Simple Example
x = 5; %initialization while x < % 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”)

34 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

35 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

36 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

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

38 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!

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

40 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')

41 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.

42 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.

43 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”


Download ppt "Types of Flow of Control"

Similar presentations


Ads by Google