Control structure: if / else

We want to test if a number is a valid month. In the first example, we test if the month is valid, using && (and). The number is a valid month if it is greater than or equal to 1 AND it is less than of equal to 12.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Input a valid month
#include <iostream>
using namespace std;
int main() { 
  int month;
  cout<<"Enter the number of a month:";
  cin>>month;
  if (month >=1 && month <=12)
     cout<<month<<" is a valid month.\n";
  else
     cout<<month<<" is NOT a valid month.\n";
  system("pause");
  return 0;
} // main
CODE

In the second example we test if the month is invalid using || (or). A month is invalid if it is less than 1 OR greater than 12.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Input a valid month
#include <iostream>
using namespace std;
int main() { 
  int month;
  cout<<"Enter the number of a month:";
  cin>>month;
  if (month <1 || month >12)
     cout<<month<<" is NOT a valid month.\n";
  else
     cout<<month<<" is a valid month.\n";
  system("pause");
  return 0;
} // main
CODE

NEXT: Who gets a discount?