C switch…case
What is a switch case in C?
In our earlier tutorials, we have studied about the If else statements, while, and do while loops. We have already learned how to use them in our programs to make it more efficient. In this tutorial, you will get to learn about the switch statement in C programming along with examples. Switch case can works in the same fashion as the Else If Ladder statement. In Else If Ladder, the program will run the block which is true and thus in this way the program ends. Likewise, the switch statement is also a control statement which will select one of the many given choices. We will have values of expressions and a list which is built in reference to those values. The list thus created is known as a case. The program will execute that block of code which matches the case value. Generally, The Switch case is fast and have clear codes as compared to the Nested If Else statements. To demonstrate the concept more detailly, let’s go through the syntax of switch case:
Syntax:
{
case value 1:
block 1;
break;
case value 2:
block 2;
break;
//You can use any number of case statements
default:
default statement;
break;
}
Flowchart:
Example:
#include<stdio.h> int main(){ int a,b; int n; printf("1. Addition\n"); printf("2. Subtraction\n"); printf("3. Multiplication\n"); printf("4. DIvision\n"); printf("Enter your choice (1 to 4): "); scanf("%d",&n); switch(n) { case 1: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Sum=%d",a+b); break; case 2: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Difference=%d",a-b); break; case 3: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Multiplication=%d",(a*b)); break; case 4: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Division=%d",a/b); break; default: printf("Enter the number from 1 to 4."); } }
The above code will provide the user with an option to jump into different blocks. When the user enters 1 then case 1 executes along with its block inside. Similarly, the program executes other cases on the basis of the number that user inputs to select the case number. And Finally, If the user enters a number that is not defined i.e. the number which is not in between 1 and 4 goes to the default block. Where default statements are executed. Below is an output of the code above.
Output:
- Addition
- Subtraction
- Multiplication
- Division
Enter your choice (1 to 4): 3
Enter the value of a and b: 3 4
Multiplication =12