Julia Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" line. If you get stuck, open the solution — but try for a few minutes first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Temperature table | loops, ranges, @printf |
| 2 | Vowel counter | strings, count, in |
| 3 | FizzBuzz | conditionals, join |
| 4 | Word frequency | dictionaries, split, sorting |
| 5 | Matrix diagonal | matrices, comprehensions |
| 6 | Statistics report | Statistics, broadcasting |
| 7 | Shapes with dispatch | structs, abstract types, methods |
| 8 | A countdown iterator | interfaces, iterate |
1. Temperature table
Print a conversion table from Celsius to Fahrenheit for 0, 10, 20, 30 and 40 °C using F = C × 9/5 + 32. Format each row as 0 C = 32.0 F (Celsius right-aligned in 3 characters, Fahrenheit in 5 with 1 decimal).
Expected first line: 0 C = 32.0 F, last line: 40 C = 104.0 F.
using Printf
# TODO: loop over 0:10:40 and use @printf("%3d C = %5.1f F\n", ...)
for c in [0]
f = 0.0 # TODO: apply the formula
println(c, " C = ", f, " F")
end0 C = 0.0 F
Show solution
using Printf
for c in 0:10:40
f = c * 9 / 5 + 32
@printf("%3d C = %5.1f F\n", c, f)
end2. Vowel counter
Write count_vowels(text) that returns how many vowels (a e i o u, upper or lower case) a string contains.
Expected: count_vowels("Programming in Julia") is 7.
function count_vowels(text)
# TODO: count the characters of lowercase(text) that are in "aeiou"
return 0
end
println(count_vowels("Programming in Julia"))
println(count_vowels("AEIOU xyz"))0
0
Show solution
count_vowels(text) = count(c -> c in "aeiou", lowercase(text))
println(count_vowels("Programming in Julia")) # 7
println(count_vowels("AEIOU xyz")) # 53. FizzBuzz
For the numbers 1 to 15, produce Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Print them on one line separated by spaces.
Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
function fizzbuzz(n)
# TODO: return "Fizz", "Buzz", "FizzBuzz" or string(n)
return string(n)
end
println(join([fizzbuzz(n) for n in 1:15], " "))1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
function fizzbuzz(n)
n % 15 == 0 && return "FizzBuzz"
n % 3 == 0 && return "Fizz"
n % 5 == 0 && return "Buzz"
return string(n)
end
println(join([fizzbuzz(n) for n in 1:15], " "))4. Word frequency
Count how often each word appears in the text (ignore case and the punctuation . and ,), then print the three most frequent words as word: count, most frequent first. Break ties alphabetically.
Expected:
the: 4
cat: 2
dog: 2text = "The cat saw the dog. The dog, the cat and a bird."
counts = Dict{String, Int}()
# TODO: clean the text, split it into words and count them
for word in split(lowercase(text))
end
top = sort(collect(counts), by = p -> (-p.second, p.first))
for (word, n) in first(top, 3)
println(word, ": ", n)
end
println(length(counts), " distinct words")0 distinct words
Show solution
text = "The cat saw the dog. The dog, the cat and a bird."
counts = Dict{String, Int}()
cleaned = replace(lowercase(text), "." => "", "," => "")
for word in split(cleaned)
counts[word] = get(counts, word, 0) + 1
end
top = sort(collect(counts), by = p -> (-p.second, p.first))
for (word, n) in first(top, 3)
println(word, ": ", n)
end
println(length(counts), " distinct words") # 7cat and dog both appear twice; sorting by (-count, word) puts cat first.
5. Matrix diagonal
Build the 4×4 matrix whose element (i, j) is i * 10 + j with a comprehension, then print its diagonal and the sum of the anti-diagonal (top-right to bottom-left).
Expected: diagonal: [11, 22, 33, 44] and anti-diagonal sum: 110.
n = 4
M = zeros(Int, n, n) # TODO: replace with a comprehension
println(M)
println("diagonal: ", [M[i, i] for i in 1:n])
println("anti-diagonal sum: ", 0) # TODO[0 0 0 0; 0 0 0 0; 0 0 0 0; 0 0 0 0]
diagonal: [0, 0, 0, 0]
anti-diagonal sum: 0
Show solution
using LinearAlgebra # for diag
n = 4
M = [i * 10 + j for i in 1:n, j in 1:n]
println(M)
println("diagonal: ", diag(M))
println("anti-diagonal sum: ", sum(M[i, n + 1 - i] for i in 1:n))The anti-diagonal is 14 + 23 + 32 + 41 = 110.
6. Statistics report
Given exam scores, print the mean (2 decimals), the median, the number of scores above the mean, and the scores rescaled to the range 0–1 with (x - min) / (max - min), rounded to 2 decimals.
Expected:
mean = 71.25
median = 71.0
above mean: 4
scaled: [0.0, 0.41, 0.65, 1.0, 0.3, 0.59, 0.85, 0.24]using Statistics, Printf
scores = [48, 67, 78, 94, 62, 75, 87, 59]
@printf("mean = %.2f\n", 0.0) # TODO
println("median = ", 0) # TODO
println("above mean: ", 0) # TODO
println("scaled: ", scores) # TODO: broadcast the formulamean = 0.00
median = 0
above mean: 0
scaled: [48, 67, 78, 94, 62, 75, 87, 59]
Show solution
using Statistics, Printf
scores = [48, 67, 78, 94, 62, 75, 87, 59]
m = mean(scores)
@printf("mean = %.2f\n", m)
println("median = ", median(scores))
println("above mean: ", count(>(m), scores))
lo, hi = extrema(scores)
println("scaled: ", round.((scores .- lo) ./ (hi - lo), digits=2))7. Shapes with dispatch
Define an abstract type Shape with subtypes Circle(r), Rect(w, h) and Triangle(a, b, c) (side lengths). Write an area method for each (use Heron's formula for the triangle: with s = (a+b+c)/2, area = √(s(s-a)(s-b)(s-c))). Print each shape's type and area rounded to 2 decimals, then the total.
Expected:
Circle: 12.57
Rect: 12.0
Triangle: 6.0
total: 30.57abstract type Shape end
struct Circle <: Shape; r::Float64 end
# TODO: define Rect and Triangle
area(c::Circle) = 0.0 # TODO: π r²
# TODO: area methods for Rect and Triangle
shapes = Shape[Circle(2)] # TODO: add Rect(3, 4) and Triangle(3, 4, 5)
for s in shapes
println(nameof(typeof(s)), ": ", round(area(s), digits=2))
end
println("total: ", round(sum(area, shapes), digits=2))Circle: 0.0
total: 0.0
Show solution
abstract type Shape end
struct Circle <: Shape; r::Float64 end
struct Rect <: Shape; w::Float64; h::Float64 end
struct Triangle <: Shape; a::Float64; b::Float64; c::Float64 end
area(c::Circle) = π * c.r^2
area(r::Rect) = r.w * r.h
function area(t::Triangle)
s = (t.a + t.b + t.c) / 2
return sqrt(s * (s - t.a) * (s - t.b) * (s - t.c))
end
shapes = Shape[Circle(2), Rect(3, 4), Triangle(3, 4, 5)]
for s in shapes
println(nameof(typeof(s)), ": ", round(area(s), digits=2))
end
println("total: ", round(sum(area, shapes), digits=2))8. A countdown iterator
Make Steps(start, step) iterable so that it counts down from start by step while the value stays positive. collect(Steps(10, 3)) should be [10, 7, 4, 1], and sum(Steps(20, 5)) should be 50.
struct Steps
start::Int
step::Int
end
# TODO: define Base.iterate(s::Steps, state=s.start)
# return nothing when state <= 0, otherwise (state, state - s.step)
Base.iterate(s::Steps, state=s.start) = nothing
Base.IteratorSize(::Type{Steps}) = Base.SizeUnknown() # the length isn't known in advance
Base.eltype(::Type{Steps}) = Int
println(collect(Steps(10, 3)))
println(sum(Steps(20, 5); init=0))Int64[]
0
Show solution
struct Steps
start::Int
step::Int
end
Base.iterate(s::Steps, state=s.start) = state <= 0 ? nothing : (state, state - s.step)
Base.IteratorSize(::Type{Steps}) = Base.SizeUnknown()
Base.eltype(::Type{Steps}) = Int
println(collect(Steps(10, 3))) # [10, 7, 4, 1]
println(sum(Steps(20, 5); init=0)) # 50IteratorSize tells collect that the length isn't known in advance (otherwise it would call length, which Steps doesn't define), and eltype makes it build a Vector{Int} instead of a Vector{Any}.
Test yourself
Which expression counts the vowels in a lowercase string s?
- length(s, "aeiou")
- count(c -> c in "aeiou", s)
- sum(s .== "aeiou")
- find("aeiou", s)
What does [i * 10 + j for i in 1:2, j in 1:3] produce?
- [11 12 13; 21 22 23]
- [11, 12, 13, 21, 22, 23]
- [11 21; 12 22; 13 23]
- an error
In exercise 8, what must iterate return to stop the iteration?
- false
- 0
- nothing
- an empty tuple