Switch Statement in C++

Level 2135 keystrokes

Uses switch to jump to the case that matches n; n is 2, so Two is printed and break leaves the switch.

C++ code

// Stores the value 2 in n
1int n = 2;
// switch compares n with each case label and jumps to the matching one
2switch (n) {
// Skipped because n is not 1
3 case 1: cout << "One" << endl; break;
// Matches n == 2: prints Two, then break exits the switch
// Without break, execution would fall through into default
4 case 2: cout << "Two" << endl; break;
// default runs only when no case matches; it is not reached here
5 default: cout << "Other" << endl;
6}

Output

Two
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 12
  • ;× 6
  • "× 6
  • :× 3
  • (× 1
  • )× 1
  • {× 1
  • }× 1
  • =× 1

More C++ examples at level 2

← C++ typing practice