When the actions to be taken depending on the value of control variable, are large in number, then the use of control structure Nested if…else makes the program complex. There switch statement can be used.
The Syntax of The Switch Statement in C Language
case expression 1:
block of instructions 1
case expression 2:
block of instructions 2
default block of instructions
It works in the following way:
switch evaluates expression and checks if it is equivalent to expression1. If it is, it executes block of instructions 1 until it finds the break keyword, the moment it finds the control will go to the end of the switch.
If the expression was not equal to expression 1 it will check whether the expression is equivalent to expression 2. If it is, it will execute the block of instructions 2 until it finds the break keyword.
Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case statements as values you want to check), the program will execute the instructions included in the default: section, if it exists, as it is an optional statement.
A program to illustrate The Switch Statement in C Language
Write a program that performs the following, depending upon the choice selected by the user.
- calculate the square of number if choice is 1
- calculate the cube of number if choice is 2 and 4
- calculate the cube of the given number if choice is 3
- otherwise print the number as it is
printf(“\n Enter any number:\n “);
printf(“Choice is as follows:\n\n”);
printf(“1. To find square of the number\n”);
printf(“2. To find square-root of the number\n”);
printf(“3. To find cube of a number\n”);
printf(“4. To find the square-root of the number\n\n”);
printf(“Enter your choice:\n”);
case 1 : printf(“The square of the number is %d\n”,n*n); break;
case 2 :
case 4 : printf(“The square-root of the given number is %f”,sqrt(n));
case 3: printf(“ The cube of the given number is %d”,n*n*n);
default : printf(“The number you had given is %d”,n);
Enter any number:
Choice is as follows:
1. To find square of the number
2. To find square-root of the number\n);
3. To find cube of a number
4. To find the square-root of the number
Enter your choice:
The square-root of the given number is 2