Saturday, November 27, 2010

The switch statement in c++


The switch statement in c++


The program that we create should be readable. To increase the readability of the program we should use tools that is simple to read and understand. When possible use switch statement rather than if else statement, as it can be more readable than if else statement. But switch statement has limitation. It can't replace if else completely but can be helpful at certain situation. It can't do everything thing that if else statement can do. For example, switch statement can take only int or char datatype in c++. The following programs will help you to understand the switch statement.

/* A simple c++ program example that demonstrate the use of switch statement in c++ by taking character input.*/


// Program 1


#include <iostream>

using namespace std;

int main ()
{
    char permit;

    cout << "Are you sure you want to quit? (y/n) : ";
    cin >> permit;

    switch (permit)
    {
        case 'y' :
            cout << "Hope to see you again!" << endl;
            break;
        case 'n' :
            cout << "Welcome back!" < < endl;
            break;
        default:
            cout << "What? I don't get it!" << endl;
    }

    return 0;
}

/* A c++ program example that demonstrate the use of switch statement in c++ by taking integer input. */


// Program 2

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    const int CHEESE_PIZZA = 11;
    const int SPINACH_PIZZA = 13;
    const int CHICKEN_PIZZA = 14;

    cout << " *********** MENU ***********" << endl;
    cout << setw (9) << "ITEM" << setw (20) << "PRICE" << endl;
    cout << " (1) Cheese Pizza" << setw (8) << "$"
            << CHEESE_PIZZA << endl;
    cout << " (2) Spinach Pizza" << setw (7) << "$"
            << SPINACH_PIZZA << endl;
    cout << " (3) Chicken Pizza" << setw (7) << "$"
            << CHICKEN_PIZZA << endl;
    cout << endl;

    cout << "What do you want? ";
    int option;
    cin >> option;

    cout << "How many? ";
    int quantity;
    cin >> quantity;

    int price;

    switch (option)
    {
        case 1:
            price = CHEESE_PIZZA;
            break;
        case 2:
            price = SPINACH_PIZZA;
            break;
        case 3:
            price = CHICKEN_PIZZA;
            break;
        default:
            cout << "Please select valid item from menu. " << endl;
            return 1;
    }

    int amount = price * quantity;
    cout << "Your Bill: $ " << amount << endl;

    return 0;
}


Explanation for the above program:


In the above program we take an integer value from the user which is stored in 'option' variable. We pass this value to switch statement. The switch statement has 3 cases: case 1, case 2 and case 3. The case 1: is similar to if (option == 1). This is the advantage of switch statement over if else statement. You don't need to type the name of variable again and again if you are doing selection operation on same variable. You just put the variable name on switch statement and then just specify the value after 'case'. One more thing to be noted is that it requires 'break' statement at the end of each 'case'. If you remove the break statement then it will jump to the case that follows it. Try it and check by yourself. The 'default' is same as else in if else statement.

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Want to learn more? View List Of All Chapters

8 comments:

  1. grave nand2 lng pla nturo n mam@@!!!,....

    ReplyDelete
  2. what is "setw"?? And is this program works?

    ReplyDelete
  3. setw is for spaces

    ReplyDelete
  4. thanks for this sir, its awesome, our teacher is giving us a activity like your 1st program ^ :) its is so helpful to me ;)

    ReplyDelete
  5. Create a C++ Tropical Cyclone Classifier Program based from the table below. Note that there are two agencies and they provide different categorization for some tropical cyclones.


    Tropical Cyclone Classifications For NW Pacific (all winds are 10-minute averages)
    Beaufort scale
    10-minute sustained winds (knots)
    Japan Meteorological Agency (JMA)
    Joint Typhoon Warning Center (JTWC)
    0 - 6
    <28 knots (32 mph; 52 km/h)
    Tropical Depression
    Tropical Depression
    7
    28 - 29 knots (32 - 33 mph; 52 - 54 km/h)
    30 - 33 knots (35 - 38 mph; 56 - 61 km/h)
    Tropical Storm
    8 - 9
    34 - 47 knots (39 - 54 mph; 63 - 87 km/h)
    Tropical Storm
    10
    48 - 55 knots (55 - 63 mph; 89 - 102 km/h)
    Severe Tropical Storm
    11
    56 - 63 knots (64 - 72 mph; 104 - 117 km/h)
    Typhoon
    12
    64 - 72 knots (74 - 83 mph; 119 - 133 km/h)
    Typhoon
    73 - 85 knots (84 - 98 mph; 135 - 157 km/h)
    86 - 89 knots (99 - 102 mph; 159 - 165 km/h)
    90 - 106 knots (100 - 122 mph; 170 - 196 km/h)
    107 - 114 knots (123 - 131 mph; 198 - 211 km/h)
    115 - 119 knots (132 - 137 mph; 213 - 220 km/h)
    Super Typhoon
    120 - 135 knots (140 - 155 mph; 220 - 250 km/h)
    >136 knots (157 mph; 252 km/h)

    Input:

    Your program should accept two input data: (1) the integer agency number (assume JMA=1 and JWTC=2), and (2) the integer 10-minute sustained wind speed reading in knots.

    Output:

    Your program must print the correct tropical cyclone classification from the given input data based on the table above. Also, your program must be able to trap input error such as incorrect agency number. If incorrect parameter for agency was inputted, your program should display: "Error: Unknown agency!". Use C++ switch's defaultcase to handle this.

    Sample Input/Output 1:

    *****************************************
    * A Tropical Cyclone Classifier Program *
    *****************************************
    Agencies:
    [1] Japan Meteorological Agency (JMA)
    [2] Joint Typhoon Warning Center (JTWC)

    Enter agency (JMA = 1, JWTC = 2) : 1
    Enter sustained wind speed reading (in knots) : 86

    Tropical cyclone classification : Typhoon

    Sample Input/Output 2:

    *****************************************
    * A Tropical Cyclone Classifier Program *
    *****************************************
    Agencies:
    [1] Japan Meteorological Agency (JMA)
    [2] Joint Typhoon Warning Center (JTWC)

    Enter agency (JMA = 1, JWTC = 2) : 2
    Enter sustained wind speed reading (in knots) : 120

    Tropical cyclone classification : Super Typhoon

    Sample Input/Output 3:

    *****************************************
    * A Tropical Cyclone Classifier Program *
    *****************************************
    Agencies:
    [1] Japan Meteorological Agency (JMA)
    [2] Joint Typhoon Warning Center (JTWC)

    Enter agency (JMA = 1, JWTC = 2) : 3

    Error: Unknown agency!

    ReplyDelete
  6. In some compilers, you will find the black screen disappearing before showing the results. To solve that just include the following
    /* system("pause"); */
    before the /* return 0; */ statement.

    ReplyDelete
  7. Programming is very interesting and creative thing if you do it with love. Your blog code helps a lot to beginners to learn programming from basic to advance level. I really love this blog because I learn a lot from here and this process is still continuing.
    Love from Pro Programmer

    ReplyDelete