Switch Statement in C Programming | C Programming


Switch Statement in C Programming     

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:    
statement;   
break;                       
case case-label-2:   
statement;    
break;  …   …   …                       
case case-label-n:    
statement;    
break;                       
default:   
statement;                     
}    
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>
int main()
{char choice;
double a,b,sum,diff,prod,quo;
printf("Enter first and second number respectively:\n");
scanf("%lf%lf",&a,&b);
printf("Press\n+ for Addition\n- for Subtraction\n* for Multiplication\n/ for Division\n");
scanf("%c",&choice);
switch(choice=getchar())
{
case '+':
sum=a+b;
printf("Sum of %.1lf and %.1lf is %.1lf",a,b,sum);
break;
case '-':
diff=a-b;
printf("Difference of %.1lf and %.1lf is %.1lf",a,b,diff);
break;
case '*':
prod=a*b;
printf("Product of %.1lf and %.1lf is %.1lf",a,b,prod);
break;
case '/':
quo=(double)a/b;
if (b==0)
printf("Undefined Value!!");
else
printf("Quoitent of %.1lf and %.1lf is %.1lf",a,b,quo);
break;
default:
printf("Error! Invalid Selection");
}
return 0;
}

Popular posts from this blog

C Program for SCAN Disk Scheduling Algorithm | C Programming

C program to Find Cartesian Product of Two Sets | C programming

C Program To Check The String Is Valid Identifier Or Not | C Programming