SWITCH
It is a multiway decision statement.The switch statement tests
the value of guven variable( or expression) against a list of
"case" values and when a match is found, a block of statements
associated with that case is executed.
General form of
switch is
switch(expression) { case value-1: block-1; break; case value-2: block-2; break; --------------------- --------------------- case value-n: block-n; break; default: default-block; break; } statement-x;
In the above general form,
Expression:It is an
integer expression (or) character.
Value-1,value-2….. :These
are constants (or) constant expressions (evaluable to integer
constant) and are known as "case labels". Each of these
values should be unique with switch statement.
block-1,block-2…:These
are the statement lists and may contain zero (or) more
statements.There is no need to put braces around these blocks.
Note: "case labels" must end with a colon (:).
When
the switch is executed, the value of the expression is
successively compared against the values value-1, value-2…….If a
case is found whose value matches with the value of the
expression then the block of statements of that particular case
will get executed.
Break:The break statement at the
end of each block signal the end of a particular case and causes
an exit from switch statement, transferring the control to the
statement-x, following the switch.
The default is an
optional case. When present it will be executed if the
value of expression does not match with any of the case values.
If not present, no action takes place if all matches fail and
the control goes to the statement-x.
Ex: program
to test all arithmetic operations using switch statement
main( ) { int a,b ,opt; clrscr( ); printf("enterany2values"); scanf("%d%d",&a,&b); printf("1.addition\n2.subraction\n3.multiplication\4.division\n6.modular\n"); printf("\nenteryouroption"); scanf("%d",&opt); switch(opt) { case 1: printf("aditionof%d&%dis%d",a,b,a+b); break; case 2: printf("subof%d&%dis%d",a,b,a-b"); break; case 3: printf("multipleof%d&%dis%d",a,b,a*b); break; case 4: printf("divof%d&%dis%d",a,b,a/b); break; case 5: printf("modularof%d&%dis%d",a,b,a/b); break; default: printf ("\n invalid option"); } getch(); }