Sunday 21 February 2016

Julia: if-elseif-else statement

if statement
“if” tell the program execute the section of code when the condition evaluates to true.

Synatx
if(Condition)
         statement1
         statement2
         …..
         …..
         statementN

end

julia> a=10;

julia> if(a==10)

           println("a is even number")

           print("a is equal to 10")

       end
a is even number
a is equal to 10

if-else statement
If the condition true, then if block code executed. other wise else block code executed.

Synatx
if(condition)
         statement1
         statement2
         …..
         …..
         statementN
else
         statement1
         statement2
         …..
         …..
         statementN

end


julia> a=10;

julia> if(a==10)

           println("a is even number")

           println("a is 10")

       else

           println("a is odd number")

           println("a is not zero")

       end
a is even number
a is 10


if-elseif-else statement
By using if-elseif-else construct, you can choose number of alternatives.

An if statement can be followed by an optional elseif...else statement, which is very useful to test various conditions

if(condition)
         statements
elseif(condition)
         statements
….
….
else
         statements
end


julia> day=3;

julia> if(day==1)

           println("Monday")

       elseif(day==2)

           println("Tuesday")

       elseif(day==3)

           println("Wednesday")

       elseif(day==4)

           println("Thursday")

       elseif(day==5)

           println("Friday")

       elseif(day==6)

           println("Saturday")

       elseif(day==7)

           println("Sunday")

       else

           println("Invalid number")

       end
Wednesday

Every expression in Julia returns a value, it is same with if condition also.
julia> number=10;

julia> result=if(num%2==0)

                   "Even Number"

               else

                   "Odd Number"

               end
"Even Number"

julia> result
"Even Number


Note
Parentheses around the condition are not needed, using of them improves readability.




Previous                                                 Next                                                 Home

No comments:

Post a Comment