if expression statement endIt is used to expression decisions. When the flow of program execution comes to an if statement, the expression is evaluated. If the logical value of the expression is true, statement will be executed. Otherwise, statement is skipped and the program moves to the point after end. For example
x = rand(2); // get two random numbers // test if the point (x[1], x[2]) is inside the unit circle if norm(x) <= 1 in_circle = 1; endIf one wishes to execute certain commands when the expression is true, and some other commands when its false, a variant of the if statement that involves three keywords if, else, and end can be used.
if expression statement group 1 else statement group 2 endFor example,
if norm(x) <= 1 in_circle = 1; else in_circle = 0; endIf the first condition is tested to be false, further condition can be tested using the elseif keyword to determine if the second group of commands are to be executed. The following is the general form of an if statement.
if expression 1 statement group 1 elseif expression 2 statement group 2 elseif expression 2 statement group 2 ... // more elseif's else statement group n end
If expression 1 is true, then statement group 1 is executed. If expression 1 is false and expression 2 is true, then statement group 2 is executed. This goes on until the condition after one of the elseif's is true. If none of expression 1 to expression n-1 is true, statement group n is executed.
Note that each statement group can be one or several statements, and can also have nested control structures.
In the general form, the parts that start with elseif and else are optional.
oz 2009-12-22