C Switch Statement

Switch Statement

Switch statement is used to solve multiple option type problems for menu like program, where one value is associated with each option.
The expression in switch case evaluates to return an integral value, which is then compared to the values in different cases, where it matches that block of code is executed, if there is no match, then default block is executed.

The general form of switch statement is,

switch(expression)
{
    case value-1:
        block-1;
        break;
    case value-2:
        block-2;
        break;
    case value-3:
        block-3;
        break;
    case value-4:
        block-4;
        break;
    default:
        default-block;
        break;
}

Points to Remember

  • We don't use those expressions to evaluate switch case, which may return floating point values or strings.
  • It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of codes will get executed after the matching block.
  • Check Following Example, The output was supposed to be only A because only the first case matches, but as there is no break statement after the block, the next blocks are executed, until the cursor encounters a break.
  • default case can be placed anywhere in the switch case. Even if we don't include the default case switch statement works.

Example:

int i = 1;
switch(i)
{
    case 1:    
        printf("A");        // No break
    case 2:
        printf("B");        // No break
    case 3:
        printf("C");
    break;
}

Output:

Command Prompt
A B C

Program of Switch Statement:

//Write a C Program which demonstrate use switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
    int a,b,c,choice;
    clrscr();
    while(choice!=3)
    {
        printf("\n 1. Press 1 for Addition");
        printf("\n 2. Press 2 for Subtraction");
        printf("\n Enter your choice:");
        scanf("%d",&choice);
        switch(choice)
        {
        case 1:
              printf("Enter 2 numbers:");
              scanf("%d%d",&a,&b);
              c=a+b;
              printf("Addition is %d",c);
              break;
        case 2:
              printf("Enter 2 numbers:");
              scanf("%d%d",&a,&b);
              c=a-b;
              printf("Subtraction is %d",c);
              break;
        default:
              printf("you have passed a wrong key");
              printf("\n press any key to continue");
        }
    }
    getch();
}

Output:

Command Prompt
1. Press 1 for Addition
2. Press 2 for Subtraction
Enter your choice:
1
Enter 2 numbers: 
5
7
Addition is 12

Share This Page to Download:

Share to Download

Share This Page on:


Ask Question