Switch Statement

Default Image

witch
statement is another structure used for selection decision making. In
this structure we have multiple blocks of statements and only the
selected block will be executed who’s case will be matched. We can use
cases of both numeric and character data types. It is also called
substitute of nested if-else structure. Sample of switch statement is
given below:

switch(variable)

{

case value1:

statements to be executed;

break;

case value2:

statements to be executed;

break;

default:

statements to be executed;

}


In switch statement we use colon after the value, colon indicates the
end of value that we are going to compare and start of the statements
that will be executed. Break keyword is used to stop the processing of
the block. If we don’t use break and value of variable is equal to
value1 then all of the statements of switch structure will be executed.
Default statement will be executed when none of the value is equal to
variable that is going to be compared. Let’s write a programme that
perform basic arithmetic functions with the help of switch statement.


#include

#include

void main()

{

clrscr();

double a,b;

char op;

cout<<"Enter First Number \n"; cin>>a;

cout<<"Enter an operator (+, -, *,/): \n"; cin>>op;

cout<<"Enter Second Number \n"; cin>>b;

switch(op)

{

case '+':

cout<<"Sum of "<

break;

case '-':

cout<<"Subtraction of "<

break;

case '*':

cout<<"Multiplication of "<

break;

case '/':

cout<<"Division of "<

break;

default:

cout<<"You entered an invalid operator \n";

}

getch();

}


A switch statement can have an optional
default case, which must appear at the end of the switch. The default
case can be used for performing a task when none of the cases is true.
No break is needed in the default case.


You can download source code for switch structure from here.

calculator output


Read Count: 3 times

Comments

No comments yet.

Leave a Comment