Switch statement in C Programming

  • Tech Area
  • May 11, 2024



In this tutorial, We will see how to use switch case in C programming language. By the using of switch statement execute one code block among many alternatives.

The syntax of the switch case is:

switch (expression)
​{
    case 1:
      // statements
      break;

    case 2:
      // statements
      break;
    .
    .
    default:
      // default statements
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label i.e. case 1, case 2 and so on.

If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to case 2, statements after case 2: are executed until break is encountered.

If there is no match, the default statements are executed.

Program to Add, Subtract, Multiply and Divide using Switch statement

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, n;
clrscr();
printf("Enter any number");
printf("\n 1 for add");
printf("\n 2 for subtract");
printf("\n 3 for multiply");
printf("\n 4 for divide");
scanf("%d", &n);
switch(n)
{
case 1:
printf("Enter two numbers");
scanf("%d%d", &a,&b);
c = a + b;
printf("sum is = %d", c);
break;

case 2:
printf("Enter two numbers");
scanf("%d%d", &a,&b);
c = a - b;
printf("subtract is = %d", c);
break;

case 3:
printf("Enter two numbers");
scanf("%d%d", &a,&b);
c = a * b;
printf("multiply is = %d", c);
break;

case 4:
printf("Enter two numbers");
scanf("%d%d", &a,&b);
c = a / b;
printf("divide is = %d", c);
break;

default:
printf("wrong number");
}
printf("\n end program");
getch();
}

Output

Enter any number
1 for add
2 for subtract
3 for multiply
4 for divide
1
Enter two numbers 12
23
sum is = 35
end program

The number 1 entered by the user is stored in the n variable. And, two operands 12 and 23 are stored in variables a and b respectively. Since the n is 1, the control of the program jumps to case 1.

case 1:
printf("Enter two numbers");
scanf("%d%d", &a,&b);
c = a + b;
printf("sum is = %d", c);
break;

Finally, the break statement terminates the switch statement.


Subscribe us via Email

Join 10,000+ subscriber

Subscribe on YouTube