Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

loops
euphoria
communitycreator

How to create an if-elsif-else statement in Euphoria

NDUKWE CHIDERA K.

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.

The if-elsif-else statement

This statement tests a condition and results as true or false. Depending on the result, a block of code will be executed.

Syntax

if  condition then

--code block to execute

elsif condition then

--another code block to execute
else

--fallback code block to execute

end 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 execute
end if

Let’s see the code snippet that illustrates the if-else statement:

--declare a variable of type atom
atom mynum = 5 
--declare a  variable of type sequence
sequence outcome
if mynum = 10 then    
outcome = "if evaluated as true"
elsif mynum <= 3 then
outcome= "if evaluated as false and elsif as true"
else
outcome = "no condition returned true."
end if 
printf(1,"%s",{outcome})

Code explanation

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.

RELATED TAGS

loops
euphoria
communitycreator
RELATED COURSES

View all Courses

Keep Exploring