cint university / 101 / ced, the cint editor
101-09: choosing among many
This is lesson 101-09 of CU-101.2, checked against cint 0.2.0.
You will sort a number into one of several groups with switch, using ranges of numbers, and make sure every number lands somewhere.
the program
for tens in 4..=10 {
I64 score = tens * 10;
"score {score:>3}: ";
switch (score) {
case 90..=100: "A\n";
case 80..=89: "B\n";
case 70..=79: "C\n";
case 60..=69: "D\n";
default: "F\n";
}
}
Run it:
score 40: F
score 50: F
score 60: D
score 70: C
score 80: B
score 90: A
score 100: A
what happened
The loop makes the scores. tens counts from 4 to 10, and score is ten times tens: 40, 50 and so on up to 100. A range in cint 0.2.0 counts by ones only, so a loop that needs steps of ten counts by ones and multiplies.
switch sorts one number into cases. switch (score) looks at score once and runs the lines of the case that holds it. Each case names a number or a range of numbers:
case 90..=100:holds every score from 90 to 100.case 80..=89:holds 80 to 89,case 70..=79:holds 70 to 79 andcase 60..=69:holds 60 to 69.default:holds every number no other case holds.
Only one case runs. When the lines of a case are done, the switch is done, and the program goes on after its closing brace. Here each case prints one letter and the line ends.
Every number must have a place. A switch without default must have a case for every possible value. With default at the end, every number has somewhere to go.
A switch can do what else if does. This program could be written as a chain of if and else if, as in lesson 101-06. A switch is shorter when every question is about the same number, and cint checks that its ranges do not overlap.
change it
- Make the loop count from 0 to 10 instead. What do scores 0 to 30 get?
- Add a grade
Efor scores from 50 to 59. - Give exactly 100 the grade
A+. What else must change, and why?
what 3 needs
`case 100: "A+\n";` added above the A case is refused, because 100 is already in `case 90..=100:` and two cases cannot hold the same number. cint points at the range in the A case that overlaps the new one:error[C4021]: `switch` rule
--> aplus.ci:6:14
|
6 | case 90..=100: "A\n";
| ^
|
Change the A range to `90..=99` as well.
when it goes wrong
Leave out default, and scores outside 60 to 100 have nowhere to go. cint refuses the program before it runs:
I64 score = 75;
switch (score) {
case 90..=100: "A\n";
case 80..=89: "B\n";
case 70..=79: "C\n";
case 60..=69: "D\n";
}
error[C4020]: `switch` rule
--> nodefault.ci:2:1
|
2 | switch (score) {
| ^
|
A range in a case must be written with ..=. case 90..100: is refused with error C4022.
new words
Next: lesson 101-10, functions.