Main Content Area

Control Structure Cheatsheet

Introduction

Computer programs (also known as software, apps or scripts) are created using programming languages.

A programming language is used to describe exactly what a program does, in the finest of detail. It may include instructions for such things as:

  • what happens when users interact with it
  • how and where its user interface will be displayed
  • how and when it might talk to other software on the network
  • where any needed data will come from and where it will go
  • the decisions that need to be made and how to react to them
  • calculations that need to be made to get some kind of result

Another way to think about this, is that programming code describes a task that you want a computer to perform, or an experience that a computer is to create for users.

This code, will then be translated by other programs into something a computer can understand, which is literally ones and zeros.

What are control structures?

The following quote from Wikipedia may shed some light on this topic.

In computer science, control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. Wikipedia
Midway's Rampage as seen on Sega Master System.
Midway's Rampage game has a similar control flow as the flow chart below. Try it twice; For Science!
Simple control flow diagram.

This flow chart illustrates part of the control flow of a simple video game.

Programs that reach a certain level of complexity behave differently depending on what information they have available to them.

For example, playing the same game twice in sequence can yield vastly different results depending on the player's interactions with the game software.

In order for something like that to happen, decisions must be made by the software.

The flow chart of the simple game illustrates one such scenario. Programming the logic depicted in the flow chart would require loops (the arrow that forms a looping path), conditional statements (the arrows branching apart) and subroutines (boxes that would contain other more detailed logic flows).

This “flow” of decisions and behaviours is known as the control flow of the program.

Therefore, with that in mind, control structures are the elements of a programming language that allow you to direct this flow of control. The most common ones typically break down into the following categories:

Conditional Statements
Allow you to choose which blocks of code to execute based on some pre-determined criteria
Loops and Iteration
Allow you to repeat the execution of blocks of code based on criteria of your choosing
Subroutines, Procedures or Functions
Allow you to execute completely separate blocks of code, then return the original spot in the main program when finished.

Conclusion

Gaining some experience working with these structures and beginning to understand when and how to used them is one of the biggest hurdles faced by novice programmers.

These structures may seem cryptic and confusing at first, but I promise that if you persist, you will have a “eureka” moment at which point they will transform from your enemies into your allies.

Below is a detailed explanation of some of the most important control statements within PHP and JavaScript. You can use these descriptions to figure out which statement may be the best to use in any given scenario.

Conditional Statements

The ‘if’ Statement

What it Does

Selects between blocks of code to execute, based on conditions that you determine.

When to Use it

  • Whenever you need to make a decision within the logic of your software based on a variety of different, possibly unrelated factors.
if( condition_one ){	
	/* (required) This code is executed when 'condition_one' evaluates to true. */
} else if( condition_two ){
	/* (optional) This code is executed when 'condition_one' evaluates to false 
	   and 'condition_two' evaluates to true.
	   
	   Note: You can have zero or any number of 
	   'else if's in an 'if' statement. 
	 */
} else {
	/* (optional) This code is executed if none of the previous 
	   conditions are true.
	    
	   Note: You don't necessarily have to have 
	   an 'else' statement. 
	 */
}

The ‘switch’ Statement

What it Does

Selects between blocks of code to execute, based on the exact value of a single variable.

When to Use it

  • When you ever have an ‘if’ statement in which each condition is a comparison of the same variable to different possible values, especially string values
  • When the equivalent ‘if’ statement code would be longer
  • When writing code to handle keypresses from the user in JavaScript
  • When writing url routing code on a custom ajax server in PHP
switch( our_variable ){
	case 'first-value':
		/* This code is executed when 'our_variable'
		   is equal to 'first-value'  */
	break;
	case 'second-value':
		/* This code is executed when 'our_variable' 
	   	   is equal to 'second-value'
		 
		   Note: You can have any number of 'case' statements
		   in a 'switch' statement.
		 */
	break;
	default:
		/* (optional) this code is executed if our_variable
		   is not equal to any of the 'case' values above 
		   
		   Note: You don't necessarily have to have 
		   a 'default' statement.
		 */
	break;
}

The Ternary Operator

What it Does

Sets a variable to one of two values, based on a condition that you determine. This is a fairly obscure statement, that you may or may not encounter.

When to Use it

  • When you like your code to be difficult to understand for most people :)
  • When your code must be as short as humanly possible and you are dealing with a single condition with two needed result values.
var result = age > 18 ? 'adult' : 'minor';

/* If 'age' has a value greater than 18, 'result' will be 
   set to a value of 'adult' (the value to the left of the colon character). 
   If 'age' doesn't have a value greater than 18, then 
   result will be set to a value of 'minor' (the value to the right of the colon character).
 */
 
 /* The 'if' statement below is logically equivalent 
    to the ternary operator example above. There is more 
    code, but it is easier to understand for most people. */
 var result;
 if( age > 18 ){
 	result = 'adult';
 } else {
 	result = 'minor';
 }

Loops and Iteration

The ‘while’ Loop

What it Does

Repeatedly executes code as long as a condition you define remains true.

When to Use it

  • Whenever you need to repeatedly execute some code.
  • Especially when you are uncertain as to how many times your code needs to be repeated at the time repetition begins
while( condition_one ){
	/* The code in this spot will keep executing repeatedly 
	   as long as 'condition_one' evaluates to true. 
	   
	   Note: 'condition_one' has to be chosen carefully so that
	   it will eventually become false, otherwise the loop will run forever.
	 */
}

The ‘do…while’ Loop

What it Does

Executes your loop code once, then repeatedly executes the same code as long as a condition you define remains true.

When to Use it

  • Whenever you need to repeatedly execute some code, but that code has to execute at least once, no matter what.
do{
	/* The code in this spot will execute once for certain,
	   then will repeatedly execute as long as 'condition_two' evaluates to true. 
	   
	   Note: 'condition_two' has to be chosen carefully so that
	   it will eventually become false, otherwise the loop will run forever.
	 */
} while ( condition_two );

The ‘for’ Loop

What it Does

Repeatedly executes code an exact number of times and keeping count while doing so.

When to Use it

  • Whenever you know exactly how many times you need to execute your code before you start looping.
  • Whenever you need the number of repetitions to correspond to the count of something, for example: loop once for each character in a string variable.
for( var i = 0; i < 10; i++ ){
	/* Code placed here will execute exactly ten times with
	   the way this 'for' loop is set up.
		
	   Notes:	
	   1. 'var i = 0' creates a counter variable, beginning the count at zero.
		
	   2. 'i < 10' defines the condition that, if true, will keep the loop
	   executing repeatedly.  When this condition becomes false, the loop
	   will stop. In this case, the loop will continue while the counter
	   variable's value is less than ten. Make sure to pick a condition that 
	   will definitely become false to avoid infinite loops.
		
	   3. 'i++' means 'add one to the counter' every time we execute the loop.
	*/
}

PHP Exclusive: The ‘foreach’ Loop

What it Does

Repeatedly executes code as many times as there are items in an array; also, keeps track of where in the array you are at each repetition.

This control structure does not exist in JavaScript.

When to Use it

  • Whenever you need to do something to each item in an array, or with each item in an array.
foreach( $our_array as $key => $value ){
	/* Code placed here will execute exactly as many
	   times as there are items within '$our_array'
		
	   Notes:	
	   1. During each repetition of the loop, an array index
	   will be taken from '$our_array' and placed into the '$key'
	   variable, until there are none left.
	   
	   2. During each repetition of the loop, a value
	   will be taken from '$our_array' and placed into the '$value'
	   variable, until there are none left. This value corresponds
	   to the index in note #1 above.
	*/
}

JavaScript Exclusive: The ‘for…in’ Loop

What it Does

Repeatedly executes code as many times as there are properties in a JavaScript Object. In addition it keeps track of which property you are on at each repetition.

This control structure does not exist in PHP.

When to Use it

  • Whenever you need to do something to each property of a JavaScript object, or with each property of a JavaScript object.
for( var property in our_object ){
	/* Code placed here will execute exactly as many
	   times as there are properties within 'our_object'.
	   A PHP analog of this is the key within an associative
	   array as in the foreach loop above.
		
	   Note:	
	   During each repetition of the loop, property name
	   will be taken from 'our_object' and placed into the 'property'
	   variable, until there are none left.
	 */
	   
	 /* The value of the property can be retrieved inside of the loop
	    by using the following code: 
	  */
	 var value = our_object[ property ];
}

Subroutines, Procedures or Functions

What They Do

Subroutines allow you to pause the execution of your main code at a specific spot, execute a block of code independent of the main code, then resume the main code where you paused initially.

When to Use them

  • When you need to use pre-defined functionality that JavaScript or PHP have to offer.
  • When your code becomes complex enough that breaking it into manageable, independent chunks helps to keep it maintainable and organized.
  • When you know you will be reusing a block of code repeatedly throughout your project.

Simple Function Call

/* This JavaScript code will execute the alert function, 
   opening a popup window. */
alert( 'hello' );

Complex Function Call

/* This PHP code retrieves the current year 
   and stores it in a variable. */
$current_year = date( 'Y' );

Custom Function Definition

function do_something( parameter_one, parameter_two ){
	/* 
	   The code in this area will execute whenever the
	   'do_something' function is called within the main
	   code. (see below)

	   Notes:
	   1. 'parameter_one', 'parameter_two' are variables
	   that will be assigned values that correspond
	   to whatever was placed between the parenthesis when
	   the function is called. There can be any number of
	   parameters. (see below)

	   2. The 'return' statement is optional, and allows you
	   to send a single value or variable out of the function.  
	   An array can be used to send out more than one value.

	   3. There can be multiple 'return' statements within a
	   function, but the function immediately exits when
	   a 'return' statement is executed. Anything after
	   that statement will be ignored.
	*/
	
	return a_calculated_result;
}

/* Below is an example of a function call, that would 
   invoke the execution of the function above. 
   
   Notes:
   1. 'our_result' will be assigned a value that comes from 
   the function's 'return' statement.
   2. 'data that is needed.' will be assigned to 'parameter_one',
   while the value of 'a_variable' will be assigned to 'parameter_two'
   within the function. 
 */
var our_result = do_something( 'data that is needed.', a_variable );