CodeBlanks Logo Icon CodeBlanks

Summary - Conditionals

Combine if, switch and pattern matching to write a day-of-week app.

Summary - Conditionals

In this group you learned if, else, switch, the Dart 3 switch expression and the ternary. Now we will combine them to write a day-of-week application.

The app will produce a day name from an integer 1-7. A switch expression is the most fitting structure for matching several values; the _ wildcard catches unexpected values. The goal is to use the right structure in the right place.

Plan

We will build the app step by step: (1) give the int day variable a value; (2) assign the switch (day) expression to the name variable; (3) write a => arm for each number; (4) catch unexpected values with the _ wildcard; (5) print with print(name);.

This structure is the core of a real calendar app too. Turning a number from the user into a day name is common in screen flows. The _ arm lets you catch wrong input gracefully.

Practice Day-of-week app

Declare an int variable day with the value 3. Declare a variable name and assign it to a switch (day) expression: arms 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", _ => "Unknown". Then print name with print(name);. The output on a single line must be Wednesday.

Starter code

main.dart
// Declare day, assign the day name to name with a switch expression, print it

Sample solution

main.dart
int day = 3;
var name = switch (day) {
  1 => "Monday",
  2 => "Tuesday",
  3 => "Wednesday",
  _ => "Unknown",
};
print(name);

Expected output

Wednesday

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which structure best fits turning 1-7 into a day name?

main.dart
int day = 3;
  • if/else chain
  • while loop
  • for loop
  • switch expression Correct answer

Explanation: switch expression is the most readable for multi-value matching.

2 Complete the wildcard arm

Question
var name = switch (day) {
  1 => "Monday",
  2 => "Tuesday",
  3 => "Wednesday",
  ____ => "Unknown",
};
Answer
var name = switch (day) {
  1 => "Monday",
  2 => "Tuesday",
  3 => "Wednesday",
  _ => "Unknown",
};

Explanation: _ is the wildcard meaning 'everything else'.

All lessons in Beginner