Glossário

Selecione uma das palavras-chave à esquerda…

Programming in JuliaConditionals

Tempo de leitura: ~10 min

Consider a simple computational task performed by commonplace software, like highlighting the rows in a spreadsheet which have a value larger than 10 in the third column. We need a new programming language feature to do this, because we need to conditionally execute code (namely, the code which highlights a row) based on the value returned by the comparison operator. Julia provides if statements for this purpose.

Conditionals

We can use an if statement to specify different blocks to be executed depending on the value of a boolean expression. For example, the following function calculates the sign of the input value x.

function sgn(x)
    if x > 0
        return +1
    elseif x == 0
        return 0
    else
        return -1
    end
end

sgn(-5)

Conditional expressions can be written using ternary conditional «condition» ? «truevalue» : «falsevalue». For example, the following version of the sgn function returns the same values as the one above except when x == 0.

sgn(x) = x > 0 ? +1 : -1

sgn(-5)

Exercises

Exercise
Can the else part of an if statement be omitted? Try running the example below.

x = 0.5
if x < 0
    print("x is negative")
elseif x < 1
    print("x is between 0 and 1")
end

Exercise
Write a function called my_abs which computes the absolute value of its input.

function my_abs(x)
    # add code here
end

using Test
@test my_abs(-3) == 3
@test my_abs(5.0) == 5.0
@test my_abs(0.0) == 0.0

Solution. We use a single if-else expression:

function my_abs(x)
    if x ≥ 0
        x
    else
        -x
    end
end

Exercise
Write a function which returns the quadrant number (1, 2, 3, or 4) in which the point (x,y) is located. Recall that the quadrants are numbered counter-clockwise: the northeast quadrant is quadrant 1, the northwest quadrant is 2, and so on. For convenience, you may assume that both x and y are nonzero.

Consider nesting if-else blocks inside of an if-else block.

function quadrant(x,y)
    # add code here
end

using Test
@test quadrant(1.0, 2.0) == 1
@test quadrant(-13.0, -2) == 3
@test quadrant(4, -3) == 4
@test quadrant(-2, 6) == 2

Solution. Here's an example solution:

function quadrant(x,y)
    if x > 0
        if y > 0
            1
        else
            4
        end
    else
        if y > 0
            2
        else
            3
        end
    end
end
Bruno
Bruno Bruno