Julia Project: Gradebook
A gradebook program stores student scores and prints a summary of them. This project combines arrays, a dictionary, functions, and sorting.
Average an array of scores
The Statistics module provides mean. The average of these four scores is exact.
using Statistics
scores = [88, 76, 92, 70]
println(mean(scores))
println(maximum(scores))Print a dictionary in name order
Sorting collect gives the pairs in key order. The loop prints one student per line.
grades = Dict("Ana" => 88, "Ben" => 76, "Cara" => 92)
for (name, score) in sort(collect(grades))
println(name, ": ", score)
endTurn a score into a grade letter
A function holds the ternary chain. Each score is tested from the top grade down.
function letter(score)
return score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"
end
println(letter(92))
println(letter(76))Example
using Statistics
function letter(score)
return score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"
end
scores = [88, 76, 92, 70]
grades = Dict("Ana" => 88, "Ben" => 76, "Cara" => 92, "Dan" => 70)
for (name, score) in sort(collect(grades))
println(name, ": ", score, " (", letter(score), ")")
end
println("Average: ", mean(scores))Key points
- Store the scores in one array for number work like an average.
- Store each student with a score in a dictionary.
- Use mean from the Statistics module to average an array.
- Use a ternary chain inside a function to turn a score into a grade letter.
- Sort collect on a dictionary to print students in name order.
- A pair from a sorted dictionary prints with its key first.
In this example, the dictionary pairs each student with a score and the array holds the same scores for averaging. The sorted loop prints each student in name order with a grade letter from the letter function. The last line prints the class average, 81.5.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
How does the program print students in name order?