Julia, lesson 3
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.
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 "".
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.
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.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+, -, * | add, subtract, multiply | 7 * 3 | 21 |
/ | divide, always a Float64 | 7 / 2 | 3.5 |
÷ or div(a, b) | integer division, rounding toward zero | 17 ÷ 5 | 3 |
% or rem(a, b) | remainder | 17 % 5 | 2 |
^ | power | 2 ^ 10 | 1024 |
÷ 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.
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.75nums = parse.(Int, split(readline())) # "3 4 5" becomes [3, 4, 5]2
35Slices each: S
Leftover: L3
5Slices each: 4
Leftover: 4