4. In programming, a switch, case, select or inspect state
ment is a type of selection control mechanism that
exists in most imperative programming languages such
as Pascal programming language, Ada programming
language, C/C++ programming language, C#
programming language, Java programming
language, and so on. It is also included in several other
types of programming languages. Its purpose is to
allow the value of a variable or expression to control
the flow of program execution via a multiway
branch (or "goto", one of several labels). The main
reasons for using a switch include improving clarity, by
reducing otherwise repetitive coding, and (if
the heuristics permit) also offering the potential for
faster execution through easier compiler optimization in
many cases.
http://eglobiotraining.com/
5. Like if statements, switch...case controls the flow of
programs by allowing programmers to specify different
code that should be executed in various conditions. In
particular, a switch statement compares the value of a
variable to the values specified in case statements. When
a case statement is found whose value matches that of
the variable, the code in that case statement is run.
The break keyword exits the switch statement, and is
typically used at the end of each case. Without a break
statement, the switch statement will continue executing
the following expressions ("falling-through") until a break, or
the end of the switch statement is reached.
http://eglobiotraining.com/
6. switch (expression)
{
case constant1:
codes to be executed if expression equals to constant1;
break;
case constant2:
codes to be executed if expression equals to constant3;
break;
.
.
.
default:
codes to be executed if expression doesn't match to any cases;
}
http://eglobiotraining.com/
7. #include <iostream>
using namespace std;
void playgame()
{
cout << "Play game called";
}
void loadgame()
{
cout << "Load game called";
}
void playmultiplayer()
{
cout << "Play multiplayer game called";
}
int main()
{
int input;
cout<<"1. Play gamen";
cout<<"2. Load gamen";
cout<<"3. Play multiplayern";
cout<<"4. Exitn";
cout<<"Selection: ";
cin>> input;
switch ( input ) {
case 1:
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
cout<<"Thank you for playing!n";
break;
default:
cout<<"Error, bad input, quittingn";
break;
}
cin.get();
}
http://eglobiotraining.com/
9. This is a sample programming, in which not all of the proper functions
are actually declared, but which shows how one would use switch in a
program. This program will compile, but cannot be run until the
undefined functions are given bodies, but it serves as a model (albeit
simple) for processing input. If you do not understand this then try
mentally putting in if statements for the case programming statements.
Default simply skips out of the switch case programming construction
and allows the program to terminate naturally. If you do not like
that, then you can make a loop around the whole thing to have it wait
for valid input. You could easily make a few small functions if you wish
to test the code.
http://eglobiotraining.com/
10. #include <iostream>
using namespace std;
int main(){
cout << "Enter a number between 1 and 5!" << endl;
int number;
cin >> number;
switch(number){
case 1: //if (number == 1)
cout << "one";
break;
case 2: //else if(number == 2) and so on...
cout << "two";
break;
case 3:
cout << "three";
break;
case 4:
cout << "four";
break;
case 5:
cout << "five";
break;
default: //if number is NOT 1,2,3,4 or 5
cout << number << " is not between 1 and 5!";
}
cout << endl;
system("pause");
}
http://eglobiotraining.com/
12. break;
The same result for multiple values
The break is used to break out from the switch/case programming
If you want to execute the same code in more
statement. Without break the program will execute all the code
cases, you don`t have to write that code
after the selected one. For example, if we don`t use breaks in the
multiple times, just write it like in the bellow
this code, and the user inputs 3, the program will show:
example:
threefourfive3 is not between 1 and 5!
switch (myvariable){
instead of
case 1:
three
case 2:
Write the above code in your compiler and try it out to see it with
case 3:
your own eyes.
cout << "myvariable is 1,2 or 3";
}
default:
The default case is optional, this is executed when none of the
previous cases are executed or when you forget the break;.
Note: The cases (including the default case) are followed by a
colon, not semicolon!
Note: This is very important! A variable can`t be used as possible
value of a case statement! Example of how NOT to do:
int myvariable = 1;
switch (x){
case myvariable: //this is NOT valid
//code to execute
}
http://eglobiotraining.com/
13. #include <iostream.h>
using namespace std;
int main(void)
{
int day;
cout << "Enter the day of the week between 1-7::";
cin >> day;
switch(day)
{
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
default:
cout << "Sunday";
break;
}
}
http://eglobiotraining.com/
15. Syntax:
Switch statement programming
switch(expression)
compares the value of an expression
{
against a list of integers or character
case constant1:
constants. The list of constants are listed
Statements
using the "case“ programming
break
statement along with a "break“
case constant2:
programming statement to end the
Statements
execution. If no conditions match then
break
the code under the default statement
.
is executed.
.
default
Statements
}
http://eglobiotraining.com/
16. #include <stdlib.h>
#include <stdio.h>
int main(void) {
int n;
printf("Please enter a number: ");
scam("%d", &n);
switch (n) {
case 1: {
printf("n is equal to 1!n");
break;
}
case 2: {
printf("n is equal to 2!n");
break;
}
case 3: {
printf("n is equal to 3!n");
break;
}
default: {
printf("n isn't equal to 1, 2, or 3.n");
break;
}
}
system("PAUSE");
return 0;
}
http://eglobiotraining.com/
18. The switch programming statement is
used in C++ for testing if a variable is
equal to one of a set of values. The
variable must be an integer, i.e.
integral or non-fractional. The
programmer can specify the actions
taken for each case of the possible
values the variable can have. The
same operation can be performed by
using a series of if, else if, and else
statements.
http://eglobiotraining.com/
19. This is the switch programming statement. It indicates that a series of
cases will follow in which we will test for equality with variable "n". If n is
switch (n) {
equal to any of the values in the following cases, then the first match
found will run its encapsulated code. The curly brace, {, encapsulates
the case statements. An end curly brace, }, will follow below.
case 1: { This is the first case programming statement. It has a set of code
printf("n is equal to 1!n"); encapsulated by curly braces, { and }, which are not manditory, but
break; serve to make the source code easier to follow. If n is equal to 1, then
} the printf() function here will display "n is equal to 1!" on the screen. A
break programming statement follows the printf() function. This is
required after each case to tell the program to exit out of the switch
programming statement. Otherwise, the rest of the code in each of the
cases would be run if the break programming statement were not
present.
case 2: { This is the second case programming statement. If n is equal to 2, then
printf("n is equal to 2!n"); the printf() function will be run to display "n is equal to 2!" on the screen.
break; The break statement will cause the program to exit out of the switch
} statement as desired since we have already found a match for n.
case 3: { This is the last case statement. If n is equal to 3, then the printf() function
printf("n is equal to 3!n"); will be run to display "n is equal to 3!" on the screen. The break
break; statement will cause the program to exit out of the switch statement as
} desired since we have already found a match for n.
This is the default statement. If a match for n has not been found, then
default: {
the code after the default statement will be run, and the printf()
printf("n isn't equal to 1, 2, or 3.n");
function will display "n isn't equal to 1, 2, or 3." on the screen. The break
break;
statement will cause the program to exit out of the switch statement;
}
although, since the default statement here comes after the case
statements, this break statement inside of the default statement is
technically not required.
This is the end curly brace that encapsulates the case statements and
}
the default statement within the switch statement.
http://eglobiotraining.com/
20. #include <iostream.h>
int main()
{
unsigned short int number;
cout << "Enter a number between 1 and 5: ";
cin >> number;
switch (number)
{
case 0: cout << "Too small, sorry!";
break;
case 5: cout << "Good job!n"; // fall through
case 4: cout << "Nice Pick!n"; // fall through
case 3: cout << "Excellent!n"; // fall through
case 2: cout << "Masterful!n"; // fall through
case 1: cout << "Incredible!n";
break;
default: cout << "Too large!n";
break;
}
cout << "nn";
return 0;
}
http://eglobiotraining.com/
22. It is important to note that if there is no break
programming statement at the end of a case
programming 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. The user is
prompted for a number. That number is given to the switch
programming 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.
http://eglobiotraining.com/
24. Looping programming statement are used to repeat a block
of code. Being able to have your program repeatedly
execute a block of code is one of the most basic but useful
tasks in programming -- many programs or websites that
produce extremely complex output (such as a message
board) are really only executing a single task many times.
(They may be executing a small number of tasks, but in
principle, to produce a list of messages only requires
repeating the operation of reading in some data and
displaying it.) Now, think about what this means: a loop lets
you write a very simple programming statement to produce a
significantly greater result simply by repetition.
http://eglobiotraining.com/
25. The following commands used in
C++ for achieving looping:
•for loop
•while loop
•do-while loop
http://eglobiotraining.com/
26. The variable initialization allows you to
either declare a variable and give it a
value or give a value to an already
existing variable. Second, the condition
tells the program that while the conditional
expression is true the loop should continue
to repeat itself. The variable update
section is the easiest way for a for loop to
handle changing of the variable. It is
#include <iostream>
possible to do things like x++, x = x + 10, or
using namespace std; // So the program can see cout and endl
even x = random ( 5 ), and if you really
int main()
{ wanted to, you could call other functions
for ( int x = 0; x < 10; x++ ) { that do nothing to the variable but still
cout<< x <<endl; have a useful effect on the code. Notice
}
cin.get(); that a semicolon separates each of these
}
sections, that is important. Also note that
every single one of the sections may be
empty, though the semicolons still have to
be there. If the condition is empty, it is
evaluated as true and the loop will repeat
until something else stops it.
http://eglobiotraining.com/
28. The basic structure is while ( condition
) { Code to execute while the
condition is true } The true represents
a boolean expression which could be
x == 1 or while ( x != 7 ) (x does not
equal 7). It can be any combination
of boolean programming statements
#include <iostream>
that are legal. Even, (while x ==5 || v
using namespace std; // So we can see cout and endl
== 7) which says execute the code
int main()
{ while x equals five or while v equals 7.
int x = 0; // Don't forget to declare variables
Notice that a while loop is the same
while ( x < 10 ) { // While x is less than 10
cout<< x <<endl; as a for loop without the initialization
x++; // Update x so the condition can be met eventually
} and update sections. However, an
cin.get();
} empty condition is not legal for a
while loop as it is with a for loop.
http://eglobiotraining.com/
30. Notice that the condition is tested at the
end of the block instead of the
beginning, so the block will be executed at
least once. If the condition is true, we jump
back to the beginning of the block and
execute it again. A do..while loop is
basically a reversed while loop. A while loop
says "Loop while the condition is true, and
execute this block of code", a do..while
loop says "Execute this block of code, and
loop while the condition is true". Keep in
#include <iostream>
mind that you must include a trailing semi-
using namespace std;
colon after the while in the above example.
int main()
{ A common error is to forget that a do..while
int x;
loop must be terminated with a semicolon
x = 0;
do { (the other loops should not be terminated
// "Hello, world!" is printed at least one time
// even though the condition is false with a semicolon, adding to the confusion).
cout<<"Hello, world!n";
} while ( x != 0 ); Notice that this loop will execute
cin.get();
} once, because it automatically executes
before checking the condition.
http://eglobiotraining.com/
32. The while loop executes a block of programming statements while
a condition is true. The basic syntax of a while loop is:
while( condition ){
//code to execute while condition is true
}
Here is an example about how to use it. The following program will
write out the numbers from 1 to 100:
#include <iostream>
using namespace std;
int main(){
int i = 0;
while(i < 100){
cout << ++i << endl;
}
system("pause");
}
Before the while loop starts i is declared with the value 0, but the
first number will be 1, because the ++ is in front of i.
http://eglobiotraining.com/
34. The for loop is useful when you know how
many times you need to repeat a block of
code, because the for loop repeats the
#include <iostream>
code for a specific number of times.
using namespace std;
int main(){
for(int i=1;i<=100;i++){
cout << i << endl;
}
system("pause");
}
http://eglobiotraining.com/
35. The basic syntax is:
for(integer = starting value; integer <= ending value; integer++){
//code to execute
}
We can use any variable name for the integer, but the default is i or y.
Here is an example of using the for loop:
Write out the numbers from 1 to 100:#include <iostream>
using namespace std;
int main(){
for(int i=1;i<=100;i++){
cout << i << endl;
}
system("pause");
}
For the starting and ending value we can use variables, too. For example look at the bellow program which shows all the numbers
between two numbers:#include <iostream>
using namespace std;
int main(){
cout << "Enter the starting number: ";
int startingnum;
cin >> startingnum;
cout << "Enter the ending number: ";
int endingnum;
cin >> endingnum;
for(startingnum;startingnum <= endingnum;startingnum++){
cout << startingnum << endl;
}
system("pause");
}
The counting expression can be anything, it can increment or decrement, or any mathematical expression, here are some
examples:for(int i=10;i>0;i--)
or
for(int i=1;i<=101;i+=10)
or
for(int i=1;i<=101;i*=2)
and so on....
http://eglobiotraining.com/