Introduction to Programming for Laymen

sarkinen.com > johan > Teaching > Programming

10. Flow Control Statements

< 9. Pseudocode 11. End of Course >

Flow Control Statements

"The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language." (The Java™ Tutorials, Oracle)

BLT
Bacon, Lettuce, Tomato (BLT)

Flow control is what really differentiates programming languages from other formal languages like query- (e.g. SQL) and markup- (e.g. HTML). And the core concepts of branching, looping, and testing are sometimes abbreviated BLT. Same as the core components of a good sandwich.

http://www.google.com/search?q=blt+branching+programming

http://computer.howstuffworks.com/c8.htm

 

Flow control can be categorized into the following basic types:
  1. Decision-Making statements: if-then, if-then-else, switch/case
  2. Looping statements: for, while, do-while, repeat-until
  3. Branching statements, Jump Statements: function calls, break, continue, return, goto
  4. Exception-handling statements: try-exception, begin-exception

Also included in this section is brief notes on SQL and procedural extensions.

Construct Existence Description

Decision-making Statements

IF-THEN
'All languages'

Execute some code if condition is true.

IF (condition) THEN
  ...
END IF
IF-THEN-ELSE
'All languages'

Execute some code if condition is true else (i.e. condition is false) execute some other piece of code.

IF (condition) THEN
  ...
ELSE
   ...
END IF
IF-THEN-ELSIF-
THEN...
'Some'

Simply extending the above but is really unnessary as can easily be created anyway.

Language w/ 'ELSIF' Language w/o 'ELSIF'
IF (condition) THEN
  ...
ELSIF (condition) THEN
  ...
ELSIF (condition) THEN
  ...
ELSE
  ...
END IF
IF (condition) THEN
  ...
ELSE IF (condition) THEN
  ...
ELSE IF (condition) THEN
  ...
ELSE
  ...
END IF

 

SWITCH / CASE

'Most languages'

 

(Note on Perl below)

This type of conditional handling can easily be implemented using IF-THEN-ELSE statements but provide easier-to-read code.

SWITCH ( variable ) 
  CASE (variable matching 1) DO
     ...
     END CASE
  CASE (variable matching 2 DO
     ...
     END CASE
      ...
  DEFAULT:  (optional is most languages)
    ... (do if not matching any case)
    END DEFAULT CASE
END CASEd
A real example (in JavaScript):
action = prompt("action");

switch( action ) 
{
  case 1:   // "case A"
    document.writeln("numeric number one");
    break;
  case 2:   // "case B"
    document.writeln("numeric number two");
    break;
  case "1": // "case C"
    document.writeln("alphanumeric number one");
    break;
  case "2": // "case D"
    document.writeln("alphanumeric number two");
    break;
}

Note: some languages (e.g. C and C++) are very strict in what data types may be used for switch variables/cases and only allow integers. Other language - like our JavaScript example above - allow both integers and strings (and even mixed, as in the example).

 

Which of the four cases - "case A" through "case D" do you think will execute if you enter the number 1 in the prompt? Try running the code in Workbench 3L. Do you see the importance of data types?! And what type a certain function / method may be returning...

 

See also BREAK below.

 

Note on Perl: Perl does not natively include a switch construct.

- More at http://perldoc.perl.org/perlsyn.html#Switch-statements.

- As one example of discussions: Perl has no switch statements. How do I avoid a long if-else-if pattern? - http://perlmeme.org/howtos/syntax/switch_statements.html

Looping Statements

FOR ...
'All languages'

Loop or iteration statement as this type is called - repeated execution of some code for a defined number of times.

 

This form should be used when you have a specific and known number of times you want to repeat a task.

FOR (every month in year) DO
  print month
END FOR
The general syntax in many programming languages is:
FOR (initialization of counter; test condition; change of counter) DO
  ...
END FOR
Example (JavaScript; prints numbers 0 through 9):
for (n = 0; n < 10; n++)
{
document.writeln(n);
}
WHILE
'All languages'

Another loop statement and this may or may not execute code depending on the condition.

 

Note that the condition is tested before the block and if condition is already false, nothing will be executed. This is a 'zero+ type', i.e. it can execute zero or more times.

WHILE (condition is true) DO
  ...
END WHILE

Warning/Note: this type of loops can create end-less loops if the condition never became false.

DO-WHILE

DO-UNTIL

REPEAT-UNTIL
'Form Varies'

Yes another loop statement but this flavor always execute the code at least once ('one+ type') as the test condition is at the end.

 

I.e. the condition is tested after the block.

 

  DO-WHILE DO-UNTIL REPEAT-UNTIL
 
DO 
  ..
WHILE (condition is true)
DO 
  ..
UNTIL (condition is true)
REPEAT 
  ..
UNTIL (condition is true)
C/C++ - -
Java - -
JavaScript - -
Perl
PHP - -
other

(in most

if not all

languages)

VBScript (different
syntax than
pseudocode show)
Pascal

 

And same as with the WHILE-loop - watch out for creating end-less loops that never exit the loop.

Branching Statements, Jump Statements

Called branching statements in (some) Java literature and jump statements in some C/C++ literature. We prefer the Jump nomenclature ourselves.

These statements unconditionally changes the flow control of your program.

CALL
'Most languages' Function call - call a subroutine / function / method. See return below for more.
BREAK
'Most languages'

Typical use is in SWITCH-CASE statements to break (end execution) of a specific CASE but can also have use in other forms of flow control statements, depending on language. For C/C++:

"A break statement terminates the smallest enclosing while, do, for or switch statement. Execution resumes at the statement immediately following the terminated statement." [C++ Primer]

Note that a CASE without a BREAK may be an allowed syntax (in th specific language) and that flow then fall-through to the next CASE and this code is also executed. Which sometimes is the intended functionality (but often viewed as poor programming) but more often a difficult to find bug, simply missed including a BREAK.

CONTINUE
'Most languages'

Another quote from C++ Primer, for C/C++:

"A continue statement causes the current iteration of the nearest enclosing while, for, or do loop to terminate.

 

In while and do loops, execution resumes with the evaluation of the control expression.

 

In for loops, continue causes execution to resume with the evaluation of expression-2.

 

Unlike the break statement, which terminates the loop, the continue statement terminates only the current iteration."

This statement is maybe mostly good for improving readability of code.

RETURN
'Most languages'

This statement is used in functions (a.k.a. methods, subroutines, ...) to exit the function, return execution to the point where the function was called from. In general, the following is good to know about returning from functions, and return statement:

 

  1. One variant of return statement is simply returning execution - return;
  2. Another variant is returning with a value - (e.g.) - return(result);
  3. A function without any explicit return statement returns execution at the end of function.
  4. A program's main program, where execution starts, is also a function and if using a return statement here, the program exits (finishes).

 

Example (in JavaScript):

function calcCircumference( diameter )
{
  circumference = diameter * 3.14159; // pi
  return( circumference );
}

// main code
diameter = prompt("Enter diameter");
circumference = calcCircumference( diameter );
alert("The circumference of a circle with diameter " 
  + diameter + " is " +  circumference );

 

GOTO
'Most languages' We really don't want to talk about this... GOTO and LABEL (nor mentioned further here) is simply poor programming. Using GOTO creates programs difficult to maintain and debug and its use is discouraged in all serious literature on programming.

'Most languages' and not 'All languages' as some languages are more restrictive to these forms of less obvious change of flow.

[C++ Primer] C++ Primer 2nd Edition, by Stanley Lippman (1991)

Exception-handling Statements

This type of statement is found in newer, more modern, languages (i.e. C - from the 1970s - does NOT have it, but C++ - from the 1980s - does have it).

TRY-CATCH
'Some languages'

As this is an introductory course, for the time being we're only showing an example (JavaScript syntax):

try {
  undefinedfunction()
  alert('I guess you do exist')
}
catch(e) {
 alert('An error has occurred: '+e.message)
}
finally {
 alert('I am alerted regardless of the outcome above')
}

For the interested student, ee Exception Handling in C without C++ - http://www.on-time.com/ddj0011.htm.

 

SQL

Original SQL doesn't have any flow control statements - for good and obvious reasons: it's not a programming language but a formal query language. However, some implementations extend SQL:

Procedural extensions

SQL is designed for a specific purpose: to query data contained in a relational database. SQL is a set-based, declarative query language, not an imperative language such as C or BASIC. However, there are extensions to Standard SQL which add procedural programming language functionality, such as control-of-flow constructs.

(From wikipedia.org/wiki/SQL)

As example (from searchsqlserver.techtarget.com/tutorial/Flow-control-statements):

Flow-control statements from T-SQL are rather rudimentary compared to similar commands in other modern programming languages such as Visual Basic and C#. Their use requires knowledge and some skill to overcome their lack of user friendliness. However, on a positive note, they allow the creation of very complex procedures. This section covers the use of the following Transact-SQL statements and programming constructs:

  • Comments
  • Statement block
  • If…Else
  • While…Break
  • Break
  • Continue
  • GoTo
  • WaitFor
  • Begin…End

 

More Resources


< 9. Pseudocode11. End of Course >
Updated 2016-06-02

sarkinen.com | Personnel | Businesses | General/Adm | webmaster | J&P Group (JandP.biz)
Copyright © 1999-2016 J. Sarkinen. All rights reserved.