Flow Control

© 2017 Morgan C. Benton code4your.life

Flow

Control

One of the most basic elements of programming is the ability to control the order in which instructions are executed, how many times they are executed, or if they are executed at all.

© 2017 Morgan C. Benton code4your.life

Types of Flow Control

  • Conditional Execution: if/then, switch
  • Iteration/Loops: for, foreach, while
  • Structured exception/error handling

© 2017 Morgan C. Benton code4your.life

Conditional Execution

© 2017 Morgan C. Benton code4your.life

if (/* conditional expression */) {
  // code to execute IF the
  // conditional expression
  // is TRUE
} else {
  // code to execute otherwise
}
switch (/* variable */) {
  case X:
    // code to execute if the
    // variable == X
    break;
  case Y:
    // code to execute if the
    // variable == Y
    break;
  default:
    // code to execute if the
    // variable did NOT equal
    // X or Y
}

Conditional Expressions

Expressions that evaluate to TRUE or FALSE

© 2017 Morgan C. Benton code4your.life

Values that are generally evaluated as "true"

  • TRUE
  • Non-zero numeric value
  • Non-empty string
  • Non-empty array

Values that are generally evaluated as "false"

  • FALSE
  • Zero
  • An empty string
  • An empty array
  • Null, nil, or undefined

Code Examples of
If/Then Statements

© 2017 Morgan C. Benton code4your.life

If/Then Statements in JavaScript, Java, and R

if (/* conditional statement */) {
  // do this...
}

if (/* conditional statement */) {
  // do this...
} else {
  // do this...
}

if (/* conditional statement */) {
  // do this...
} else if (/* another conditional */) {
  // do this...
} else {
  // do this...
}
switch (var1) {
  case val1:
    // do this...
    break;
  case val2:
  case val3:
    // do this...
    break;
  default:
    // do this...
}

if (var1 == val1) {
  // do this...
} else if (var1 == val2 || var1 == val3) {
  // do this...
} else {
  // do this...
}

© 2017 Morgan C. Benton code4your.life

If/Then in PHP

if (/* conditional statement */) {
  // do this...
}

if (/* conditional statement */) {
  // do this...
} else {
  // do this...
}

if (/* conditional statement */) {
  // do this...
} elseif (/* another conditional */) {
  // do this...
} else {
  // do this...
}
switch ($var1) {
  case $val1:
    // do this...
    break;
  case $val2:
  case $val3:
    // do this...
    break;
  default:
    // do this...
}

if ($var1 == $val1) {
  // do this...
} elseif ($var1 == $val2 || $var1 == $val3) {
  // do this...
} else {
  // do this...
}

© 2017 Morgan C. Benton code4your.life

If/Then in Go

if /* conditional statement */ {
  // do this...
}

if /* conditional statement */ {
  // do this...
} else {
  // do this...
}

if /* conditional statement */ {
  // do this...
} else if /* another conditional */ {
  // do this...
} else {
  // do this...
}
switch var1 {
  case val1:
    // do this...
  case val2:
  case val3:
    // do this...
  default:
    // do this...
}

if var1 == val1 {
  // do this...
} else if var1 == val2 || var1 == val3 {
  // do this...
} else {
  // do this...
}

© 2017 Morgan C. Benton code4your.life

If/Then in Python

if conditional:
  # do this...

if conditional:
  # do this...
else:
  # do this...

if conditional1:
  # do this...
elif conditional2:
  # do this...
else:
  # do this...
# Python does not have a 
# switch/case statement

© 2017 Morgan C. Benton code4your.life

If/Then in Ruby

if conditional then
  # do this...
end

if conditional then
  # do this...
else
  # do this...
end

if conditional1 then
  # do this...
elsif conditional2 then
  # do this...
else
  # do this...
end

unless conditional then
  # do this...
else
  # do this...
end
case var
  when val1
    # do this...
  when val2, val3
    # do this...
  else
    # do this...
end

if var == val1
  # do this...
elsif var == val2 or var == val3
  # do this...
else
  # do this...
end

© 2017 Morgan C. Benton code4your.life

Iteration with Loops

  • Computers are good at repeating things over and over
  • In general, iterative structures are called "loops"
  • There are several different kinds of loops:
    • for
    • while/until, do...while/do...until
    • foreach, for...in, for...of
    • functional style
  • Key idea: every loop must have a terminal condition
  • There can be normal and early termination

© 2017 Morgan C. Benton code4your.life

Loop Diversity

  • There are many different kinds of loops used in various programming languages
  • Make sure you do your homework and study up on all of the different kinds available in each new language you investigate

© 2017 Morgan C. Benton code4your.life

Code Examples of
Loops

© 2017 Morgan C. Benton code4your.life

For Loops (C-Style)

  • For loops have (up to) three parts:
    • initialization(s)
    • end condition
    • increment/decrement

© 2017 Morgan C. Benton code4your.life

for (/* initializer(s) */; /* end condition */; /* increment */) {
    // do this...
}

// typical example
for (i = 0; i < 10; i += 1) {
    // do this 10 times
}

// this type of loop is common in Java, JavaScript, PHP, and Go
// BE CAREFUL with the syntax, which varies slightly across languages

Foreach Loops

  • Use for iterating over collections
    (arrays, vectors, objects, etc.)

© 2017 Morgan C. Benton code4your.life

// PHP
foreach($items as $key => $item) {
  // loops over each item in the
  // array of items; $key is set
  // to the array index or object
  // property name
  echo $item;
  echo $items[$key];
}
// JavaScript
for(var i in items) {
  // loops over each item in the
  // array of items; i is set
  // to the array index or object
  // property name
  console.log(items[i]);
}

for(var item of items) {
  // loops over each item in the
  // array of items; item is set
  // to the value of each of the
  // items in the collection
  console.log(item);
}
# Ruby
items.each do |item|
  puts item
end
# Python
for item in items:
  print(item)

Other "For" Loops

  • Generally includes:
    • A "counter" variable
    • Some range to be traversed/counted

© 2017 Morgan C. Benton code4your.life

# Python
for i in range(1, 6):
  # iterates 5 times over
  # values 1 to 5
  print(i)
# Ruby
for i in 1..5
  # iterates over
  # values 1 to 5
  puts i
end

5.times do |i|
  # iterates over
  # values 0 to 4
  puts i
end

1.upto(5) do |i|
  # iterates over
  # values 1 to 5
  puts i
end
# R
for (i in 1:5) {
  # iterates over
  # values 1 to 5
  print(i)
}

While/do...While Loops

  • Only requires that a terminating condition be specified

© 2017 Morgan C. Benton code4your.life

i = 0;
while (i < 10) {
  // do something

  // incrementer inside
  // the loop block
  i += i;
}
// NOTE: do..while ALWAYS executes
// at least once, since condition is
// not checked until the end
i = 10;
do {
  // do something

  // incrementer inside
  // the loop block
  i += i;
} while (i < 10);

Functional Style "Loops"

  • For/foreach/while loops are concerned about the order in which statements are executed
  • Functional style loops only care that the same transformation is applied to each element

© 2017 Morgan C. Benton code4your.life

// JavaScript
// .map() applies a function to
// all elements of an array
var cm2in = x => x * 0.3937;
var cms = [10, 15, 20];
var ins = cms.map(cm2in);
// ins == [3.937, 5.905, 7.874]
# R
cms <- c(10, 15, 20)
ins <- sapply(cms, function(x) x * 0.3937)
[1] 3.9370 5.9055 7.8740

Looping Pitfalls

  • "off by one" errors
  • failure to terminate, i.e. infinite loops

© 2017 Morgan C. Benton code4your.life

// off-by-one error example
for (i = 0; i <= 5; i += 1) {
  // how many times does this
  // code get executed?
  console.log(i);
}

// output
0
1
2
3
4
5

// 6 times!
// infinite loop example
for (i = 1; i != 10; i += 2) {
  // how many times does this
  // code get executed?
  console.log(i);
}

// output
1
3
5
7
9
11
...

// infinite times!

Exception Handling

  • An "exception" is when something goes wrong at runtime, usually caused by something outside of the programmer's control, like user input
  • It's possible to plan for such situations, there will be an entire other video on exceptions

© 2017 Morgan C. Benton code4your.life

// in JavaScript (very similar in Java and PHP)
try {
  // do something risky that might cause
  // an error at runtime
} catch(err) {
  // handle the error if something goes
  // wrong so your program doesn't just
  // unceremoniously quit on you
}

Summary

  • Controlling the flow of your code is a fundamental skill when writing programs
  • Conditional execution (if/then) and iteration (loops) are the primary means of accomplishing this
  • Exception handling is another important tool that will be covered in more detail in another video

© 2017 Morgan C. Benton code4your.life

Flow Control

By Morgan Benton

Flow Control

Introduction to the concept of flow control in computer programming. Example code in a variety of languages is provided to demonstrate the major types of flow control: if/then statements, switch, for loops, foreach loops, and while loops.

  • 1,278