Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.
You start with:
// Rust: the editor starts empty - declare the data yourself, for example:
let mut grades = BTreeMap::new();
grades.insert("Math", 92);
grades.insert("English", 78);
grades.insert("Science", 85);
grades.insert("History", 67);
Build:
English: C History: D Math: A Science: B
Rules:
- Visit the subjects in alphabetical order.
- Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
- On each iteration print the subject, a colon and a space, then the grade, for example
English: C.
Use a
BTreeMap<&str, i32> - it stores keys in sorted order.
let mut grades = BTreeMap::new();
grades.insert("Math", 92);
grades.insert("English", 78);
grades.insert("Science", 85);
grades.insert("History", 67);
for (subject, score) in &grades {
let grade;
if *score >= 90 {
grade = "A";
} else if *score >= 80 {
grade = "B";
} else if *score >= 70 {
grade = "C";
} else if *score >= 60 {
grade = "D";
} else {
grade = "F";
}
println!("{}: {}", subject, grade);
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
