Switch Case

Switch case statement is alternate to if else-if ladder statement which can allow us to execute multiple operations for the different values of a single variable is called a switch variable.Switch case statement is a control statement that allow to choose only one case among the many given cases.

Rules for switch case statement

  • Switch expression must be an integer type or character type.
  • Case label must end with a colon(:).
  • If there is no cases are match, then default statements are executed.
  • Case label values must be unique.

Syntax of switch statement:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

Let’s see the example of switch case statement.

#include<stdio.h>
void main( )
{
    int a, b, c, choice;
    clrscr(); 
    printf("enter the value of a & b");
    scanf("%d%d",& a,& b);
    printf("press 1 for addition");
    printf("press 2 for subtraction");
    printf("press 3 for multiplication");
    printf("press 4 for division");
    scanf("%d ", & choice);
    switch(choice)
    {
    Case 1:
    c=a+b;
    printf("sum=%d ", c);
    break;
    case 2:
    c=a-b;
    printf("sub =%d ",c);
    break;
    case 3:
    c=a*b;
    printf("mul = %d ", c);
    break;
    case 4:
    if(b!=0)
    {
    c=a/b;
    printf("div = %d" ,c);
    }
    else
    {
    printf("can't divide by 0");
    break;
    default:
    printf("wrong decision");
    }
    getch();
    }

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews