if and if/else statements can become quite confusing when
nested too deeply, and C++ offers an alternative. Unlike if, which
evaluates one value, switch statements allow you to branch on any of a
number of different values. The general form of the switch statement
case valueOne: statement;
case valueTwo: statement;
case valueN: statement;
expression is any legal C++ expression, and the statements are any legal C++
statements or block of statements. switch evaluates expression
and compares the result to each of the case values. Note, however, that
the evaluation is only for equality; relational operators may not be used here,
nor can Boolean operations.
If one of the case values matches the expression, execution jumps to
those statements and continues to the end of the switch block, unless a
break statement is encountered. If nothing matches, execution branches
to the optional default statement. If there is no default and there is
no matching value, execution falls through the switch statement and the
NOTE: It is almost always a good
idea to have a default case in switch statements.
If you have no other need for the default, use it to test for the
supposedly impossible case, and print out an error message; this can be a
tremendous aid in debugging.
It is important to note that if there is no break statement at the
end of a case statement, execution will fall through to the next case
statement. This is sometimes necessary, but usually is an error. If you decide
to let execution fall through, be sure to put a comment, indicating that you
didn't just forget the break.
This C++ program illustrates use of the switch statement.
2: // Demonstrates switch statement
4: #include <iostream.h>
6: int main()
8: unsigned short int number;
9: cout << "Enter a number between 1 and 5: ";
10: cin >> number;
11: switch (number)
13: case 0: cout << "Too small, sorry!";
15: case 5: cout << "Good job!\n"; // fall through
16: case 4: cout << "Nice Pick!\n"; // fall through
17: case 3: cout << "Excellent!\n"; // fall through
18: case 2: cout << "Masterful!\n"; // fall through
19: case 1: cout << "Incredible!\n";
21: default: cout << "Too large!\n";
24: cout << "\n\n";
25: return 0;
Output: Enter a number between 1 and 5: 3
Enter a number between 1 and 5: 8
Analysis: The user is prompted for
a number. That number is given to the switch statement. If the number
is 0, the case statement on line 13 matches, the message Too small,
sorry! is printed, and the break statement ends the switch. If the
value is 5, execution switches to line 15 where a message is printed,
and then falls through to line 16, another message is printed, and so forth
until hitting the break on line 20.
The net effect of these statements is that for a number between 1 and 5, that
many messages are printed. If the value of number is not 0-5, it is assumed to
be too large, and the default statement is invoked on line 21.
The syntax for the switch statement is as follows:
case valueOne: statement;
case valueTwo: statement;
case valueN: statement
The switch statement allows for branching on multiple values of
expression. The expression is evaluated, and if it matches any of the case
values, execution jumps to that line. Execution continues until either the end
of the switch statement or a break statement is encountered.
If expression does not match any of the case statements, and if there
is a default statement, execution switches to the default
statement, otherwise the switch statement ends.
cout << "Zero!" << endl;
cout << "One!" << endl;
cout << "Two!" << endl;
cout << "Default!" << endl;
cout << "Less than 3!";
cout << "Equals 3!";
cout << "greater than 3!";
|1. ||View Comment|
I've been satisfied with your tutorial site. Since I started to learn java and C++, I find it difficult to seek solutions when I encountered problems regarding to syntax and sourcecodes. When I discovered your site, I take my time exploring all links and tutorial stuffs. It was wonderful. Everything is there. Java-samples.com totally catered my voracious appetite in java and C++. Thanks for building this tutorial site. More power to java-samples.com Godspeed!!!
View Tutorial By: Mark Harold F. Manguino at 2008-08-06 05:00:54
|2. ||View Comment|
thanks or the infromation about switch statement
View Tutorial By: mikko at 2008-09-01 23:48:44
|3. ||View Comment|
can you give the program about the fast food by using the switch statement.... pls.....
View Tutorial By: grace at 2008-09-22 00:48:37
|4. ||View Comment|
thank you so much i learn from your tutorial i wish ill be expert in programming like you.can you give some example on how to convert and compute at the same time in one program.god bless:
View Tutorial By: Anonymous at 2009-01-03 20:08:41
|5. ||View Comment|
thankx a lot...i've been trying so hard to learn the switch statement ..... this tutorial shined my brain just in 5 mins...thankx again!!!!!
View Tutorial By: bhuwan at 2009-04-08 23:30:45
|6. ||View Comment|
all of codes of t-C++ ide, it is applicable to use to the other C++..?like java?,devc++,and others?
View Tutorial By: jonard at 2009-06-05 20:41:39
|7. ||View Comment|
i like your explanation it is understandable
View Tutorial By: gerasmia yen-yen d. at 2009-07-15 21:12:39
|8. ||View Comment|
ITS GOOD TO UNDERSTAND AS A BEGINNER,
View Tutorial By: Anonymous at 2009-07-24 06:31:50
|9. ||View Comment|
your tutorial is very helpful...
i was hoping that you give more example of that within 30-50 lines..
View Tutorial By: Zero17 at 2009-08-15 09:17:16
|10. ||View Comment|
i always encounter a problem every time we discuss new things in my C++ subject.. i don't know if i'm the problem or just my teacher who doesn't explain it clearly and fully.. i have a project now that is needed to include looping, switch and functions in 1code.. sound's easy to some but for me it's hard.. it's making my brain bleed. searching your site, gave me easy problems to solve and also made me understand C++ more...
THANK YOU! even if i don't know you personally.. i owe you my grade.
View Tutorial By: sukira 18 at 2009-08-29 03:25:23
|11. ||View Comment|
Thanks for the syntax, this has really helped me understand how to use 'switch'.
View Tutorial By: Ketobbey at 2010-04-30 19:01:29
|12. ||View Comment|
C++ is more than nyc & fun, de most interesting part abt C++ is knowing de algorithim of Ur codes , & u'll b de man. Thax for de explanation of switch statement i don't tink i'l ever have any problem abt switch statement. GOD BLESS U Guys. Dis is de next powerful programmer.
View Tutorial By: Themba at 2010-09-12 09:11:04
|13. ||View Comment|
thank you so much i satisfied for the tutorial in c++..i don't have a problem when you are always give the answer..now i know..
View Tutorial By: flick at 2010-09-24 21:10:59
|14. ||View Comment|
I want to ask, can a formula be inserted in this switch statement like the one I provided below?? Really need your help and comment.. Thank you..
using namespace std;
int price_before_discount, RM, dozen, total_price;
cout<< "How much is the price before discount for 1 dozen boxes of tissue?\n";
cout<< "How many dozen boxes of tissue you buy?\n";
total_price = ((price_before_discount*dozen) * (95/100));
case '1': cout<< "Total price is RM ";
total_price = ((price_before_discount*dozen) * (88/100));
case '2': cout<< "Total price is RM ";
total_price = ((price_before_discount*dozen) * (75/100));
case '3': cout<< "Total price is RM ";
total_price = ((price_before_discount*dozen) * (60/100));
case '4' : cout<< "Total price is RM ";
total_price = ((price_before_discount*dozen) * (40/100));
default : cout<< "Total price is RM ";
View Tutorial By: chika at 2011-02-02 17:18:59
|15. ||View Comment|
I want inserted switch statement in my program,
Really need your help and comment.. Thank you..
Main () /*calculate maximun stress */
float P, L, w, t;
printf("\t\t\n\n\n <<<This program is to calculate maximum stress>>>\t\n\n\n");
printf("Please input force value, P [KN]: ");
scanf("%f" , &P);
printf("Please input length, L [m]: ");
scanf("%f" , &L);
printf("Please input width, w [cm]: ");
scanf("%f" , &w);
printf("Please input thickness, t [cm]: ");
scanf("%f" , &t);
/* calculate M, y, I */
float M, y, I, max ;
/* convertion */
float w_m, t_m, P_N;
t_m = t /100;
w_m = w /100;
P_N = P * 1000;
/* calculation */
M = P_N * L;
y = t_m /2;
I = (w_m * pow(t_m,3 )) /12 ;
max = (M * y)/ I ;
/* Result */
printf("\n The maximun stress is = %8.3e[pa] or %8.2f[Mpa] \n ", max , max/10000000 );
View Tutorial By: shah at 2011-02-07 01:11:12
|16. ||View Comment|
What should be done to correct the error, just in case instead of a number, the user entered a letter (i.e. letter "a")?
View Tutorial By: Raymond at 2011-03-07 08:51:54
|17. ||View Comment|
i memorized it easly .
View Tutorial By: kibrom at 2011-04-27 11:46:24
|18. ||View Comment|
thanks for our help. god bless u and again thanks.
View Tutorial By: mehryab at 2011-05-08 14:44:21
|19. ||View Comment|
can we use if statment with swich,,,!!!
View Tutorial By: dena at 2011-07-09 13:52:27
|20. ||View Comment|
please give me a program of the 12 horoscope using the switch statement in functions.
View Tutorial By: auvx at 2011-08-03 02:02:56
|21. ||View Comment|
Thanks a lot for your tutorial.
(: It was very helpful and well-conceived.
And I just loved the last example for it showed how important the breaks are.
View Tutorial By: Nevermore at 2011-08-03 10:39:32
|22. ||View Comment|
3. Write a program that will continuously ask for an integer input from the user until a negative
value is entered. Display the sum and the average of the numbers entered (not including the
negative sentinel value). (Filename: Filename: Exer6.cpp)
Please enter number 1? 10
Please enter number 2? 8
Please enter number 3? 3
Please enter number 3? -1
Average is 7.
Computer for sum and average again [Y/N]? N
View Tutorial By: basil at 2011-08-04 13:00:30
|23. ||View Comment|
CAN I ASK A FORMULA OF FOR MAKING A CALCULATOR USING A SWITCH STATEMENT?u
View Tutorial By: JUNER at 2011-08-17 03:33:02
|24. ||View Comment|
can i ask a program that will compute a order from costumer using switch and do while statement in C++ program
View Tutorial By: mjae at 2011-09-12 08:02:46
|25. ||View Comment|
the tutorial is good and i am satisfied to it i want to learn how to use calender although i made it but i want to have some changes the programe is given below
cout<< "enter oyur date ?";
cout<< "the day is monday";
cout<< "the day is tuesday";
cout<< "the day is wednesday";
cout<< "the day is thursday";
cout<< "the day is friday";
cout<< "the day is saturday";
cout<< "you enter invalid date"
while (c !='e')
View Tutorial By: sheraz at 2011-11-07 02:08:55
|26. ||View Comment|
thank's for the info.. i've learned a lot.. now, i better understand the essence of switch statement..
View Tutorial By: farah talabo at 2012-01-08 23:55:14
|27. ||View Comment|
what if i use multiple switch statement, is it works?
what is the code? can u help! please!
View Tutorial By: earl at 2012-01-29 04:10:25
|28. ||View Comment|
you can use multiple switch statements depending on your program, and when there is more than one switch statement, then there is a nested switch am not so sure if am right but that what i think, i also want to know about nested switch pls!!!!!!!!!!
View Tutorial By: moshood at 2012-04-01 13:24:41
|29. ||View Comment|
can I ask question? how to make a complete program to simulate the game jackNpoy? thank you
View Tutorial By: manuel at 2012-08-13 10:06:24
|30. ||View Comment|
can i ask question? on how to make a statement by using a if else statement and switch statement
View Tutorial By: alas at 2012-09-27 00:42:08