Control structure: if / else

In this example, we print the month based on the month. Notice that we must use nested elses in order for the last else to work. If there were just one else, it would print out invalid if it wasn't fall.

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

NEXT: Conditional operator: ?