Tuesday, 20 December 2011

Episode 11 : switch statement


switch statement

We need to work a particular statement from others statement. For execute this particular statement, we use switch statement. When we write a long program then using of if-else statement is so much boring and difficult.

Structure of switch statement :

switch (expression)
{
case constant_1 :       // using colon ( : ) is compulsory.
Statement _1;
------------------
Statement _n;
break;

case constant_2 :
Statement _2;
------------------
Statement _n;
break;
  
case constant_n :
Statement _n;
break;
default :
default statement _X;
break;  
}

At switch statement, there are four basic keyword of switch.

·       switch
·       case
·       break
·       default

switch :
          switch keyword is tell the compiler that here is start the switch statement. This keyword also contain the conditional expression in parentheses ‘( )’ like if  statement. But the conditional expression is not any relational or logical expression, it contain a variable and switch statement is  dependent of this variable value which case will be executed.

case :
          If we compare the switch statement with ‘if’ statement then we compare the case with ‘else-if’ . We write the condition in a first bracket “()” in else-if statement and statement is depended to this condition but there are no conditional expression with case , it hold only a constant which is depended to the value of variable which we use in the switch keyword. Compiler compare the constant of case and using the variable value in switch keyword and which case is match with the variable value then compiler execute the statement of that case.

break :
          break keyword is defined that the case statement and that case is finished. When compiler find the break statement then the compiler stop the switch statement. Using break is not compulsory but it needed to switch statement.

default :
          We know the uses of else – if , the same work done by the default statement like else statement. When the value of switch keyword is not match to the case constant then the compiler execute the default and it statement.

Now we write a simple program using switch statement :

#include <stdio.h>
void main()
{
int number;
printf(“\n\n Enter your number (1 - 3) :”);
scanf(“%d”,&number);
switch(number)
{
case 1 :
printf(“Hello friends 1”);
break;

case 2 :
printf(“Hello friends 2”);
break;

case 3 :
printf(“Hello friends 3”);
break;
default :
printf(“Wrong Number : No friends\n”);
printf(“Enter the correct number”);
break;
}
}

Output :

Enter your number (1 - 3) : 2
Hello friends 2

I hope you are all now understand the switch statement. Run this and observe that.

Written by “Shojib”

No comments:

Post a Comment