Branching is a very important concept in programming. It is the bedrock of automation. Branching provides the opportunity for programs to control the actions of a computer depending on the outcome of a particular condition.
In a branch statement, a condition is placed in the block that will cause a specific code block to be executed depending on the outcome evaluation. This outcome can either be true or false.
In Euphoria, there are a few branching structures. However, in this shot, we will discuss the if-else statement.
This statement tests a condition and results as true or false. Depending on the result, a block of code will be executed.
if condition then--code block to executeelsif condition then--another code block to executeelse--fallback code block to executeend if
In simple terms, the if
statement checks the condition
. The then
keyword gives the statement the next action to perform. This action executes an indicated code block code block to execute
.
If the condition
does not evaluate as true
, the elsif
condition is checked. If the elsif
condition is true, another code block to execute
will be executed.
When none of these conditions are evaluated as true, the else
block named fallback code block to execute
will be executed. This is a fallback or default code block. The if
statement comes to an end with the end if
keyword.
We can create a simple if
statement without an elsif
or else
block. We do this by adding the end if
keyword instead of the else
block. It looks like this:
if condition then--code block to executeend if
Let’s see the code snippet that illustrates the if-else
statement:
--declare a variable of type atomatom mynum = 5--declare a variable of type sequencesequence outcomeif mynum = 10 thenoutcome = "if evaluated as true"elsif mynum <= 3 thenoutcome= "if evaluated as false and elsif as true"elseoutcome = "no condition returned true."end ifprintf(1,"%s",{outcome})
An if-elsif-else
statement first checks if the defined atom mynum
equals 10
.We also use the elseif
block to check the atom against the number 3 for a less or equal relationship. If all this is not evaluated as true, a default else block is returned. At every check, the outcome
variable is given a value. The final content of the outcome
variable is output to the screen using the printf
function.