Menu
Coddy logo textTech

The 'switch' Statement

Part of the Fundamentals section of Coddy's Dart journey — lesson 36 of 94.

The switch statement in Dart offers a cleaner alternative to multiple if-else statements when checking a variable against different values.

void main() {
  String grade = 'B';
  
  switch (grade) {
    case 'A':
      print('Excellent performance!');
      break;
    case 'B':
      print('Good performance!');
      break;
    case 'C':
      print('Average performance.');
      break;
    case 'D':
      print('Below average performance.');
      break;
    default:
      print('Invalid grade.');
      break;
  }
}

When run, it outputs: Good performance!

challenge icon

Challenge

Easy

Create a program that determines a student's grade based on their exam score using a switch statement:

  1. Declare an integer variable named examScore with a value of 85
  2. Create a string variable named grade to store the letter grade
  3. Use a switch statement with the following rules:
    • If examScore is between 90 and 100 (inclusive), set grade to "A"
    • If examScore is between 80 and 89 (inclusive), set grade to "B"
    • If examScore is between 70 and 79 (inclusive), set grade to "C"
    • If examScore is between 60 and 69 (inclusive), set grade to "D"
    • For any other score, set grade to "F"
  4. Print the result in this exact format: Score: 85, Grade: B

Note: You'll need to use integer division to convert the score to a range that works with switch.

Cheat sheet

The switch statement in Dart provides a cleaner alternative to multiple if-else statements when checking a variable against different values.

switch (variable) {
  case 'value1':
    // code to execute
    break;
  case 'value2':
    // code to execute
    break;
  default:
    // code for unmatched cases
    break;
}

Each case must end with a break statement to prevent fall-through. The default case handles values that don't match any specific case.

String grade = 'B';

switch (grade) {
  case 'A':
    print('Excellent performance!');
    break;
  case 'B':
    print('Good performance!');
    break;
  default:
    print('Invalid grade.');
    break;
}

Try it yourself

void main() {
  // Declare the examScore variable here
  int examScore = 85;
  
  // Declare the grade variable here
  String grade;
  
  // Use a switch statement to determine the grade

  
  // Print the result
  print("Score: $examScore, Grade: $grade");
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals