3. In programming,
a switch, case, select or inspect statement is a type
of selection control mechanism that exists in
most imperative programming languages such
as Pascal, Ada, C/C++, C#, Java, 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 multi way branch (or "go
to", 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.
NEXT
http://eglobiotraining.com
4. Switch case statements are a substitute for long if
statements that compare a variable to several "integral"
values ("integral" values are simply values that can be
expressed as an integer, such as the value of a char). The
basic format for using the switch case in the programming
is outlined below. The value of the variable given into
switch is compared to the value following each of the
cases, and when one value matches the value of the
variable, the computer continues executing the program
from that point.
The switch-case statement is a multi-way decision
statement. Unlike the multiple decision statement that can
be created using if-else, the switch statement evaluates
the conditional expression and tests it against numerous
constant values. The branch corresponding to the value
T
that the expression matches is taken during execution.
O
P
I BACK NEXT
C
http://eglobiotraining.com
5. Switch is used to choose a fragment of template
depending on the value of an expression
This has a similar function as the If condition - but it is
more useful in situations when there is many possible
values for the variable. Switch will evaluate one of
several statements, depending on the value of a
given variable. If no given value matches the
variable, the default statement is executed.
The value of the expressions in a switch-case
statement must be an ordinal type i.e. integer, char,
short, long, etc. Float and double are not allowed.
T
O
P
I BACK NEXT
C
http://eglobiotraining.com
6. Switch case 1
It is a sample program, 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 statements. Default simply skips out of the switch
case 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://www.cprogramming.com/tutorial/lesson5.html
T
O
P
I BACK NEXT
C
http://eglobiotraining.com
7. T http://www.cprogramming.com/tutorial/lesson5.html
O
P
I BACK NEXT
C
http://eglobiotraining.com
8. This switch statement performs the same
statements for more than one case label.
This switch statement contains
several case clauses and one default clause.
Each clause contains a function call and
a break statement. The break statements
prevent control from passing down through
each statement in the switch body.
http://publib.boulder.ibm.com/infocenter/comp
help/v8v101/index.jsp?topic=%2Fcom.ibm.xlcp
p8a.doc%2Flanguage%2Fref%2Fssits.htm
T
O
P
I
C BACK
http://eglobiotraining.com
10. Firstly we declare a switch statement followed by Circular
Brackets „(‟ and „)‟.
The switch-case body starts with „{‟ and ends with „}‟ all the
conditions should be placed inside the Curly Brackets only.
Then we declare a „case‟ statement which is followed by an
integral value and a colon „:‟.After the colon we start the
case body under which the specified code is executed if the
case condition evaluates to true. The Integral value is
compared with the variable (which we added in the switch()
statement). Then at the end of our code we declare a
„default‟ case/statement followed by a colon , this case is
executed if all above conditions evaluate to false. This
statement can be considered same as else statement in if-
else structure. The default statement is optional.
http://www.cfanatic.com/topic4267/
http://eglobiotraining.com
12. A switch statement allows a variable to be tested for equality
against a list of values. Each value is called a case, and the
variable being switched on is checked for each case. The switch
statement
The switch statement is almost the same as an “if statement”. The
switch statement can have many conditions. You start the switch
statement with a condition. If one of the variables equals the
condition, the instructions are executed. It is also possible to add
a default. If none of the variables equals the condition the
default will be executed. The if statement can be used to test
conditions so that we can alter the flow of a program. In other
words: if a specific statement is true, execute some instructions. If
not true, execute these instructions.
http://www.codingunit.com/c-tutorial-the-if-and-switch-statement
http://eglobiotraining.com
14. The switch case statement is a better way of writing a program when
a series of if else occurs. The general format for this is,
switch ( expression ) {
case value1:
program statement;
program statement;
......
break;
case valuen:
program statement;
.......
break;
default:
.......
.......
break;
}
http://eglobiotraining.com
15. The keyword break must be included at the end of each case
statement. The default clause is optional, and is executed if the cases
are not met. The right brace at the end signifies the end of the case
selections.
Rules for switch statements
values for 'case' must be integer or character constants the
order of the 'case' statements is unimportant the default clause
may occur first (convention places it last) you cannot use expressions or
ranges
http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_028.htm
http://eglobiotraining.com
17. There may be a situation when you need to
execute a block of code several number of times.
In general statements are executed sequentially:
The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control
structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement
or group of statements multiple times and following
is the general from of a loop statement in most of
T
O the programming languages.
P
I
C LOOP NEXT
http://eglobiotraining.com
18. C++ programming language
provides following types of loop to
handle looping requirements:
T
O
P
I
C
BACK
http://eglobiotraining.com
19. T
O
P
I
C
A for loop is a repetition control structure that
allows you to efficiently write a loop that needs
to execute a specific number of times.
The statements in the for loop repeat
continuously for a specific number of
times. The while and do-while loops repeat until
a certain condition is met. The for loop repeats
until a specific count is met. Use a for loop
when the number of repetition is know, or can
be supplied by the user.
LOOP BACK NEXT
http://eglobiotraining.com
20. T
O
P
I
C
#include <iostream>
#include <cmath>
}
using namespace std;
cout <<"nSeconds
//prototype falling distancen";
int fallingdistance(); cout <<"---------------------------------------
n";
//main function
for ( count = 1; count <= time;
int main() count++)
{ {
int count = 1 ; distance = .5 * 9.8 *
int time; pow(time, 2.0);
double distance ; cout << count << "
" << distance <<" meters"<< endl;
cout << "Please enter time in 1
through 10 seconds.nn"; }
system ("pause");
time = fallingdistance(); return 0;
}
while ( time < 1 || time > 10) // falling distance function for a return value in
seconds transfer to time
{ cout << "Must enter between 1
int fallingdistance () NEXT
and 10 seconds, please re-enter.n"; {
time = fallingdistance();
LOOP int seconds; BACK
http://eglobiotraining.com cin >> seconds;
return seconds;
22. T
O
P
I
C
The while loop allows programs to repeat
a statement or series of statements, over
and over, as long as a certain test
condition is true.
The while loop can be used if you don‟t
know how many times a loop must run.
A while loop statement repeatedly
executes a target statement as long as a
given condition is true.
LOOP BACK NEXT
http://eglobiotraining.com
23. T
O
P
I
C
#include <iostream.h>
int main(void) {
int x = 0;
int y = 0;
bool validNumber = false;
while (validNumber == false) {
cout << "Please enter an integer between 1 and 10: ";
cin >> x;
cout << "You entered: " << x << endl << endl;
if ((x < 1) || (x > 10)) {
cout << "Your value for x is not between 1 and 10!"
<< endl;
cout << "Please re-enter the number!" << endl << endl;
}
else
validNumber = true;
}
cout << "Thank you for entering a valid number!" << endl;
return 0;
}
LOOP BACK NEXT
http://eglobiotraining.com
25. T
O
P
I
C
In most computer programming languages, a do while
loop, sometimes just called a while loop, is a control
flow statement that allows code to be executed once
based on a given Boolean condition.
The do while construct consists of a process symbol and a
condition. First, the code within the block is executed, and
then the condition is evaluated. If the condition is true the
code within the block is executed again. This repeats until
the condition becomes false. Because do while loops
check the condition after the block is executed, the
control structure is often also known as a post-test loop.
Contrast with the while loop, which tests the condition
before the code within the block is executed.
LOOP BACK NEXT
http://eglobiotraining.com
26. T
O
P
I
C
Unlike for and while loops, which test the loop
condition at the top of the loop, the do...while
loop checks its condition at the bottom of the
loop.
A do...while loop is similar to a while loop,
except that a do...while loop is guaranteed to
execute at least one time.
The do-while loop is similar to the while loop,
except that the test condition occurs at
the end of the loop. Having the test condition
at the end, guarantees that the body of the
loop always executes at least one time.
LOOP
BACK NEXT
http://eglobiotraining.com
27. T
O
P
I
C
#include <iostream>
using namespace std;
main()
{ int num1, num2;
char again = 'y';
while (again == 'y' || again == 'Y') {
cout << "Enter a number: ";
cin >> num1;
cout << "Enter another number: ";
cin >> num2;
cout << "Their sum is " << (num1 + num2) << endl;
cout << "Do you want to do this again? ";
cin >> again; }
return 0;
}
LOOP BACK
NEXT
http://eglobiotraining.com
29. Loops are used to loop back and execute the same block
of code over and over again until a certain condition is
met.
This code takes a value from the user and runs a while loop
that many times. The conditions used for the while loop are
the same as the if-then-else statements, same goes for
every loop. Here since I only put "a" the program will read
"While a is true execute this block" and as long as a is a
positive integer it is considered to be 'true'.
http://www.cppgameprogramming.com/cgi/nav.cgi?pag
e=loops
http://eglobiotraining.com
31. Accidentally putting a ; at the end of a for loop or if statement so that the
statement has no effect - For example:
for (x=1; x<10; x++);
print f("%dn",x);
only prints out one value because the semicolon after the for statement
acts as the one line the for loop executes.
You can see that the declaration for a has been changed to a float, and
the %f symbol replaces the %d symbol in the print f statement. In addition,
the %f symbol has some formatting applied to it: The value will be printed
with six digits preceding the decimal point and two digits following the
decimal point.
Now let's say that we wanted to modify the program so that the
temperature 98.6 is inserted in the table at the proper position. That is, we
want the table to increment every 10 degrees, but we also want the table
to include an extra line for 98.6 degrees F because that is the normal body
temperature for a human being. The following program accomplishes the
goal:
http://eglobiotraining.com
32. #include <stdio.h>
int main()
{
float a;
a = 0;
while (a <= 100)
{
if (a > 98.6)
{
printf("%6.2f degrees F = %6.2f degrees Cn",
98.6, (98.6 - 32.0) * 5.0 / 9.0);
}
printf("%6.2f degrees F = %6.2f degrees Cn",
a, (a - 32.0) * 5.0 / 9.0);
a = a + 10;
}
return 0;
}
This program works if the ending value is 100, but if you change the ending
value to 200 you will find that the program has a bug. It prints the line for
98.6 degrees too many times. We can fix that problem in several different
ways.
http://computer.howstuffworks.com/c9.htm
http://eglobiotraining.com
34. As these cases demonstrate, often the structure of what your program is
doing can usually be expressed without using gotos. Undisciplined use of
gotos can create unreadable, un maintainable code when more idiomatic
alternatives (such as if-elses, or for loops) can better express your structure.
Theoretically, the goto construct does not ever have to be used, but there
are cases when it can increase readability, avoid code duplication, or make
control variables unnecessary. You should consider first mastering the
idiomatic solutions, and use goto only when necessary. Keep in mind that
many, if not most, C style guidelines strictly forbid use of goto, with the only
common exceptions being the following examples.
One use of goto is to break out of a deeply nested loop. Since break will not
work (it can only escape one loop), goto can be used to jump completely
outside the loop. Breaking outside of deeply nested loops without the use of
the goto is always possible, but often involves the creation and testing of
extra variables that may make the resulting code far less readable than it
would be with goto. The use of goto makes it easy to undo actions in an
orderly fashion, typically to avoid failing to free memory that had been
allocated.
Another accepted use is the creation of a state machine. This is a fairly
advanced topic though, and not commonly needed.
http://en.wikibooks.org/wiki/C_Programming/Control
http://eglobiotraining.com
36. The break command allows you to terminate and exit a loop (that is, do, for,
and while). You can place a break command only in the body of a looping
command or in the body of a switch command. The break keyword must be
lowercase and cannot be abbreviated.
In a looping statement, the break command ends the loop and moves
control to the next command outside the loop. Within nested statements,
the break command ends only the smallest enclosing do, for, switch, or while
commands.
In a switch body, the break command ends the execution of
the switch body and transfers control to the next command outside
the switch body.
Output will be displayed as:
0
1
2
3
4
5
6
7
8
http://eglobiotraining.com 9
38. Try changing the Fahrenheit-to-Celsius program so that it
uses scan f to accept the starting, ending and increment
value for the table from the user. Add a heading line to the
table that is produced. Try to find a different solution to the
bug fixed by the previous example. Create a table that
converts pounds to kilograms or miles to kilometres.
If you run this program, it will produce a table of values
starting at 0 degrees F and ending at 100 degrees F.
http://eglobiotraining.com
39. The output will look like this:
0 degrees F = -17 degrees C
10 degrees F = -12 degrees C
20 degrees F = -6 degrees C
30 degrees F = -1 degrees C
40 degrees F = 4 degrees C
50 degrees F = 10 degrees C
60 degrees F = 15 degrees C
70 degrees F = 21 degrees C
80 degrees F = 26 degrees C
90 degrees F = 32 degrees C
100 degrees F = 37 degrees C
The table's values are in increments of 10 degrees. You can see that
you can easily change the starting, ending or increment values of
the table that the program produces.
http://computer.howstuffworks.com/c9.htm
http://eglobiotraining.com