switch: looking at one variable

In this example, we calculate the tip as 20% if the service is 'Y' or 'y'. Otherwise, the tip is 15%. Compare this to the example using if/else.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Tip based on service
#include <iostream>
using namespace std;
int main(void) {
  double cost, tip;
  char service;
  cout<<"Enter cost of meal:$";
  cin>>cost;
  cout<<"Was the service good (Y/N)?";
  cin>>service;
  switch (service)
  { case 'Y': case 'y': tip=cost*0.20; break; //20% for good service
    default: tip=cost*0.15; break;  //15% if not
  } //switch
  cout<<"The tip is $"<<tip<<"\n";
  system("pause");
} //main
CODE

NEXT: Print season from month