Switch Statement: Case based Instructions

Understanding the Concept

  • A Switch case statement is a control statement that allows us to make a decision from a number of  given choices called Switch.
  • There are certain rules that need to be kept in mind while working with a switch statements.
    • Case values can never be conditional.
    • Every case must be a constant value or an expression.
    • Every case label must be unique
    • Float values can not be used.
    • The case label is terminated by colon(:) and statement in every case must be terminated by semi colon(;).
    • Break keyword is used at the end of each case statement.
Switch

Examples of Switch Statement

The Most basic example of a Switch case statement is to design a calculator which can perform basic operations ,i.e, addition,subtraction, multiplication and division.

Let us first understand how the Calculator works.

  • In a calculator we are given certain choices of operations.
  • Out of the given choices, the user is to select on and that operation is then executed.

Now we shall look at the program to implement calculator operations.

#include

int main()
{
int a,b;
float res;
char c;
printf("Enter first number: ");
scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);

printf("Choose operation to perform (+,-,*,/,%): ");
scanf(" %c",&c);

res=0;
switch(c)
{
case '+':
res=a+b;
break;

case '-':
res=a-b;
break;

case '*':
res=a*b;
break;

case '/':
res=(float)a/(float)b;
break;

case '%':
res=a%b;
break;
default:
printf("Invalid operation.\n");
}

printf("res: %d %c %d = %f\n",a,c,b,res);
return 0;
}
calci

Output: