Switch Statement in C++

Here is the code tutorial for the Switch Statement in C++

#include <iostream>
using namespace std;

int main() {

int monthNumber;

cout << ”Enter month number: “;

cin >> monthNumber;

// if-based solution would be:

//

// if (monthNumber == 1)

//          cout << “January”;

// else if (monthNumber == 2)

//          cout << “February”;

// else …

//

// it can be coded in more elegant way

// using switch statement

cout << ”Month #” << monthNumber << ” is “;

switch (monthNumber) {

case 1:

cout << ”January”;

break;

case 2:

cout << ”February”;

break;

case 3:

cout << ”March”;

break;

case 4:

cout << ”April”;

break;

case 5:

cout << ”May”;

break;

case 6:

cout << ”June”;

break;

case 7:

cout << ”July”;

break;

case 8:

cout << ”August”;

break;

case 9:

cout << ”September”;

break;

case 10:

cout << ”October”;

break;

case 11:

cout << ”November”;

break;

case 12:

cout << ”December”;

break;

default:

cout << ”unknown month”;

break;

}

return 0;

}

Output for Program

Enter month number:
Month #2 is February

Advertisement

About Ali Turab Gilani
BS Computer Sciences from G.C University Lahore. Served as Teaching Assistant for Programming Fundamentals... Vice President IEEE Society Student Chapter...

2 Responses to Switch Statement in C++

  1. N says:

    This is not efficient coding. There should be array defined for Months.

  2. Ali Turab Gilani says:

    The sample is meant to demonstrate the switch statement not benefit of arrays…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.