III. Conditional Statement and Loops

What is a Conditional Statement?

A conditional statement is a mechanism that allows for conditional execution of instructions based upon the outcome of a conditional statement, which can either be true or false.

Below is a flowchart illustration of an if statement containing an optional else.

Using If Statements

if ( test_one ) {
    A
} else {
    B
}

C

test_one is evaluated for a truth value (true/false) if it is true A is executed and moves to D if it is false test_two // is evaluated for a truth value. If test_two is true B is executed and moves to D, if it is false D is executed.

Example:

if (i == j) {
    result = 1;
}
elsif (j == k) {
    result =  2;
}
else {
    result = 3;
}

Given i is 1, j is 1, and k is 1. The result would equal 1, since the first condition is true (i does equal j) no of the other
conditions are evaluated.

Given i is 0, j is 1, and k is 1. The result would equal 2, since the first condition is not true (i.e. i does not equal j)
the second condition (else if) is evaluated and is found to be true (j does equal k) and the result is set to 2.

Given i is 0, j is 1, and k is 2. The result would equal 3, since the prior two conditionals did not evaluate to true the final
else directives are executed.

Inline If Statement
Inline if statements are useful if you are interested in conditionally assigning a variable. If more complex instructions are
be executed the above format is recommended.

my_variable = if ( test, A, B );
If test is true my_variable is set to A, otherwise it is set to B.

Example:

role = if( playerID == 1, 1, 2);

Explanation:
The above conditional assignment sets the role to 1 if the player ID is set to 1, otherwise it sets the role to 2 for any other player ID.

Using While Loops

while ( test ){
    A
}

While test is true A will be executed. Note: If a stopping case is not placed in A the while loop will execute indefinitely.

Example:

numberOfSubjects = 10;
array subjectIDs[numberOfSubjects];

i = 1;
while (i <= numberOfSubjects) {
    subjectIDs[i] = i;
    i = i + 1;
}

The above contrived example populates the subjectIDs array of with values ranging from 1 to 10.

 

Using An Iterator to Loop Through Arrays

my_array[array_size];
    iterator(array_index, starting_point, array_size).do{
    my_array[array_index] = some_value;
}

The iterator function loops through an array (my_array) using array_index, from starting_point to array_size, and places some_value in each corresponding element of the array.