Chapter 5. Conditionals and Recursion

The main topic of this chapter is the if statement, which executes different code depending on the state of the program. But first I want to introduce two new operators: floor division and modulus.

Floor Division and Modulus

The floor division operator, ÷ (\div TAB), divides two numbers and rounds down to an integer. For example, suppose the running time of a movie is 105 minutes. You might want to know how long that is in hours. Conventional division returns a floating-point number:

julia> minutes = 105
105
julia> minutes / 60
1.75

But we don’t normally write hours with decimal points. Floor division returns the integer number of hours, rounding down:

julia> hours = minutes ÷ 60
1

To get the remainder, you could subtract one hour in minutes:

julia> remainder = minutes - hours * 60
45

An alternative is to use the modulus operator, %, which divides two numbers and returns the remainder:

julia> remainder = minutes % 60
45

The modulus operator is more useful than it seems. For example, you can check whether one number is divisible by another—if x % y is 0, then x is divisible by y.

Also, you can extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of an integer x (in base 10). Similarly, x % 100 yields the last two digits.

Boolean Expressions

A Boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces ...

Get Think Julia now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.