You are on page 1of 9

MECN2012: Computing

Skills and Software


Development
Lecture 5:
Flow Control Conditions & The
SWITCH-CASE Algorithm

Flow Control Conditions


Most flow control conditions are based on
variable values
Loops especially are controlled using the
changing values of marker variables
2 methods commonly used:
Counter-based
Value-based

Care must be taken in specifying flow


control conditions to avoid implicit
conditions and infinite loops

Flow Control Conditions


Counter-based:
Based on a counter variable initialised
before or at the start of the loop
Counter variable increased with each
iteration of the loop
Loop normally terminated once the
required number of iterations have been
performed
Sometimes based on decreasing
counters
Typical discriminator: counter

Flow Control Conditions


Value-based:
Based on a variable which must be
initialised before the start of the loop
Variable is modified during iteration of loop
Loop terminated once a certain value is
attained or exceeded
Typically used in terms of differences in
value between iterations being smaller
than a fixed value (accuracy)
Typical discriminator: variable accuracy

Flow Control Conditions


Modification of discriminating variables
essential to prevent infinite loops
Infinite loops require external control (if
possible) to stop (break)
Counter-based infinite loops easily averted by
ensuring increment / decrement of counter
inside of loop
Value-based infinite loops more likely in cases
where behaviour of discriminating value is
unknown / may never meet criterion e.g.
numerical harmonics of PDEs

The SWITCH-CASE Algorithm


Most basic algorithm
Tests a single variable for equality (==)
against a list of possible discrete values
Any number of possible cases can be
defined
A default case must be defined for
instances where there is no match
between the variable value and the
listed cases

The SWITCH-CASE Algorithm


Basic syntax:
switch variable
case (value1)
(Case 1 code)
case (value2)
(Case 2 code)

otherwise
(Default code)
end

The SWITCH-CASE Algorithm


If any of the case expressions are
true (1) then the code for that case
will be executed and then execution
will continue following the end
statement
Since SWITCH-CASE tests explicit,
discrete values 2 cases cannot both
be valid
If none of the case conditions are
met then the default code is

The SWITCH-CASE Algorithm


e.g. Printing out phrases based on
numbers
switch
Test
Test
Screen
case 1
0
Hello
1
Hello
case 2
2
Goodbye
Goodbye
3
otherwise

end

You might also like