Learn/Julia/3. Reading input and arithmetic
Lesson 3 of 8
Sign in

Julia, lesson 3

Reading input and arithmetic

Programs get their data from somewhere. In this course it comes from standard input (stdin), the stream a program reads when you type into it or pipe data into it.

Reading lines

readline() reads one line from stdin and returns it as a String, without the newline at the end. Call it again to get the next line:

readlines() reads all remaining lines at once and returns them as a vector of strings, which is handy when you do not know how many lines are coming. When the input runs out, readline() returns an empty string "".

Text into numbers

Input is always text, and "7" + 1 is an error. Convert with parse, telling it which type you want:

2 exercises to try what you just read.

Exercise 1

Add two numbers

Press Ctrl Enter or Check to test your code.

Exercise 2

Pizza party

Press Ctrl Enter or Check to test your code.

If the text is not a valid number, parse stops the program with an error that shows the bad text. That is useful: you find out immediately instead of computing with garbage.

When one line holds several numbers separated by spaces, split cuts it into pieces and parse.(Int, ...) (note the dot) parses every piece:

The dot means "apply this to each element". You will see it again with collections.

Arithmetic

OperatorMeaningExampleResult
+, -, *add, subtract, multiply7 * 321
/divide, always a Float647 / 23.5
÷ or div(a, b)integer division, rounding toward zero17 ÷ 53
% or rem(a, b)remainder17 % 52
^power2 ^ 101024

÷ is typed as \div then Tab in the Julia REPL and most editors; div(17, 5) does the same and is easier to type anywhere. A neat Julia touch: a number right before a variable means multiplication, so 2x is 2 * x.

Precedence follows maths: ^ first, then *, /, ÷, %, then + and -. Update a variable in place with +=, -=, *= and friends: score += 10.

Useful functions include abs, sqrt, min, max, and the rounding family. round(Int, 2.7) gives the integer 3, floor(Int, 2.7) gives 2, and round(2.756, digits=2) gives 2.76.

Further reading

  • Julia docs: readline, readlines and parse
  • Julia manual: Mathematical operations
  • Julia manual: Integers and floating-point numbers

Read two whole numbers, one per line, and print their sum.

Sample input:

Sample output:

Read the number of pizzas and the number of people, one per line. Each pizza has 8 slices. Everyone gets the same whole number of slices, and the rest are left over. Print two lines:

Sample input:

Sample output:

(3 pizzas make 24 slices; 24 ÷ 5 is 4 each, with 4 left.)

name = readline()
println("Hello, $name!")
n = parse(Int, readline())          # "12"   becomes 12
price = parse(Float64, readline())  # "2.75" becomes 2.75
nums = parse.(Int, split(readline()))   # "3 4 5" becomes [3, 4, 5]
2
3
5
Slices each: S
Leftover: L
3
5
Slices each: 4
Leftover: 4