switch… case statement in c

switch….case Statement

Decision making are needed when, the program encounters the situation to choose a particular statement among many statements. If a programmar has to choose one among many alternatives if…else can be used but, this makes programming logic complex. This type of problem can be handled in C programming using switch…case statement.

Syntax of switch…case

switch (expression)
{
case constant1:
   codes to be executed if expression equals to constant1;
   break;
case constant2:
   codes to be executed if expression equals to constant3;
   break;
   .
   .
   . 
default:
   codes to be executed if expression doesn't match to any cases;
}

In switch…case, expression is either an integer or a character. If the value of switch expression matches any of the constant in case, the relevant codes are executed and control moves out of the switch…case statement. If the expression doesn’t matches any of the constant in case, then the default statement is executed.

Example of switch…case statement

Write a program that asks user an arithmetic operator(‘+’,’-‘,’*’ or ‘/’) and two operands and perform the corresponding calculation on the operands.


/* C program to demonstrate the working of switch...case statement */
/* Program to create a simple calculator for addition, subtraction, multiplication and division */
# include <stdio.h>
int main(){
     char operator;
     float num1,num2;
     printf("Enter operator +, - , * or / :\n");
     operator=getche();
     printf("\nEnter two operands:\n");
     scanf("%f%f",&num1,&num2);
     switch(operator)                              
     {
     case '+':
              printf("num1+num2=%.2f",num1+num2);
              break;
     case '-':
              printf("num1-num2=%.2f",num1-num2);
              break;
     case '*':
              printf("num1*num2=%.2f",num1*num2);
              break;
     case '/':
              printf("num2/num1=%.2f",num1/num2);
              break;
     default:                                 
/* if operator is other than +, -, * or /, error message is shown */
              printf(Error! operator is not correct");
              break;
     }
     return 0;
}

Output

Enter operator +, -, * or / :
/
Enter two operators:
34
3
num2/num1=11.33

Notice break statement at the end of each case, which cause switch…case statement to exit. If break statement are not used, all statements below that case statement are also executed.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s