switch: looking at one variable

In this example, we print the month based on the month using switch. Compare this to the example using nested if/else.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Input a month, print the season
#include <iostream>
using namespace std;
int main() {
  int month;
  cout<<"Enter the number of a month:";
  cin>>month;
  switch(month) {
    case 1: case 2: case 12: cout<<"Winter\n"; break;
    case 3: case 4: case 5: cout<<"Spring\n"; break;
    case 6: case 7: case 8: cout<<"Summer\n"; break;
    case 9: case 10: case 11: cout<<"Fall\n"; break;
    default: cout<<month<<" is not a valid month\n";
  }
  system("pause");
  return 0;
} // main
CODE

NEXT: For Loops