The Switch Statement:
Unlike the If statement which allows a selection of two alternatives the switch statement allows a program to select one statement for execution out of a set of alternatives. During the execution of the switch statement only one of the possible statements will be executed the remaining statements will be skipped. The usage of multiple If else statement increases the complexity of the program since when the number of If else statements increase it affects the readability of the program and makes it difficult to follow the program. The switch statement removes these disadvantages by using a simple and straight forward approach.The general format of the Switch Statement is :
Switch (expression)
{
Case case-label-1;
Case case-label-2;
Case case-label-n;
………………
Case default
}
When the switch statement is executed the control expression is evaluated first and the value is compared with the case label values in the given order. If the label matches with the value of the expression then the control is transferred directly to the group of statements which follow the label. If none of the statements matches then the statement against the default is executed. The default statement is optional in switch statement in case if any default statement is not given and if none of the condition matches then no action takes place in this case the control transfers to the next statement of the if else statement.
Example
include <stdio.h>
void main ()
{
int num1, num2, result
char operator
printf ("Enter two numbers")
scanf ("%d %d", &num1, &num2)
printf ("Enter an operator")
scanf ("%c", &operator)
switch (operator)
{
case '+':
result = num1 + num2
break
case '-':
result = num1 - num2
break
case '*':
result = num1 * num2
break
case '/':
if (num2 != 0)
result = num1 / num2
else
{
printf ("warning : division by zero \n")
result = 0
}
break
default:
printf ("\n unknown operator")
result = 0
break
}
printf ("%d", result)
}
In the above program the break statement is need after the case statement to break out of the loop and prevent the program from executing other cases.


0 comments:
Post a Comment