Rules for Switch Case:
switch .. case is similar to nested if else statement, but the problem is , when we use multiple nested if else, it will increase the complexity of program.
1. Switch case default compare equal value.
2. The switch statement is not support to compare string & real no. (Decimal no.)
3. The switch statement cannot be nested.
4. You can use ‘n’ number of case statement in switch.
5. Default statement is optional statement in a switch case.
6. Break statement is compulsory used to break the statement.
syntax:
switch (expression)
{
case constant1:
statements to be executed if expression equals to constant1;
break;
case constant2:
statements to be executed if expression equals to constant3;
break;
. . .
default:
statements to be executed if expression doesn't match to any cases;
}
program:
# include <stdio.h>
int main()
{
char operator;
int num1 = 10,num2 = 10;
operator='+';
switch(operator)
{
case '+':
printf("num1+num2=%d",num1+num2);
break;
case '-':
printf("num1-num2=%d",num1-num2);
break;
case '*':
printf("num1*num2=%d",num1*num2);
break;
case '/':
printf("num2/num1=%d",num1/num2);
break;
default:
/* if operator is other than +, -, * or /, error message is shown */
printf(Error! operator is not correct");
break;
}
return 0;
}
output:
num1+num2=20;
0 comments:
Post a Comment