Step 1 of 6 · Reading · ~3 min
Learn
Control Flow
If/Else and Switch
By the end of this lesson you can make a program choose between paths with if, combine conditions with && and ||, and use switch when one value has several known cases.
if / else if / else
if (score >= 90) {
Console.WriteLine("A");
} else if (score >= 80) {
Console.WriteLine("B");
} else {
Console.WriteLine("F");
}
Conditions are checked top to bottom and the first true branch runs; the rest are skipped. The comparison operators are ==, !=, <, >, <= and >=. Unlike C and C++, the condition must be a bool: the typo if (x = 5) (assignment instead of comparison) is a compile error, not a silent bug. And unlike Java, == on two strings compares their contents, so "Mon" == "Mon" is true.
Combining conditions
&& means "and", || means "or", ! means "not". They are short-circuit operators: in a && b, if a is false then b is never evaluated. That makes this safe:
if (people != 0 && total / people > 10) { /* ... */ } // no division when people is 0
When you mix them, && binds tighter than ||, just as * binds tighter than +. Consider a ticket rule: children (under 5) and seniors (65 and up) ride free, but only on a weekday:
bool free = weekday && age < 5 || age >= 65; // parsed as (weekday && age < 5) || age >= 65
bool free2 = weekday && (age < 5 || age >= 65); // what the rule says
The first form lets every senior ride free on weekends, because && grouped the wrong pair. When a rule mixes && and ||, add parentheses so the grouping is yours, not the compiler's.
For a one-line choice between two values there is the conditional operator: string label = age < 18 ? "minor" : "adult";.
switch: choosing between known values
When one value is compared against a list of specific candidates, switch reads better than a ladder of else if:
switch (code) {
case 200:
case 201:
case 204:
Console.WriteLine("success");
break;
case 404:
Console.WriteLine("missing");
break;
default:
Console.WriteLine("other");
break;
}
- Stacked labels (
case 200: case 201:) let several values share one body. - Every non-empty case must end with
break(orreturn). C# refuses to compile silent fall-through from one body into the next. defaulthandles every value that matched no case. It is theelseof the switch.
The compact switch expression (code switch { 404 => ... }) belongs to newer C# versions; the compiler on this course's grader predates it, so use the statement form.
Common mistakes
- Wrong grouping of
&&and||. The code compiles and gives wrong answers for exactly the inputs where the groups differ. Test the boundary values. - No
default/ finalelse. A value you did not plan for prints nothing, and silence is worse than an error message. - A
casethat does not end inbreak. The compiler stops you: "Control cannot fall through from one case label". =where you meant==. Compile error in C#, but still worth recognizing.
Your exercise
The starter reads a month number and a year. Print how many days that month has, using switch for the month and a compound condition for the one month that depends on the year. The most likely mistakes are the century years and a month number that does not exist.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…