SWITCH PROGRAMME
☆SWITCH PROGRAMME LIST☆
What is a switch Statement in C?
The switch case statement is used when we have multiple options and we need to perform a different task for each option.when the variable being switched on is equal to a case,the statements following that case will execute until a break statement is reached. When a break statement is reached the switch terminates,and the flow of control jumps to the next line after the switch statement.Not every case needs to contain a break .if no break appears , the flow of control will fall through to subsequent cases until a break is reached.
The if..else..if ladder allows you to execute a block code among many alternatives. If you are checking on the value of a single variable in if...else Ladder , it is better to use switch statement.
The switch statement is often faster than nested if...else (not always). Also, the syntax of switch statement is cleaner and easy to understand.
- The syntax of switch...case:
- When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.
Suppose, the value of n is equal to constant2. The compiler executes the statements after case constant2: until break is encountered. When break statement is encountered, switch statement terminates.
#include <stdio.h> void main() { int x ; printf("Enter Value of x"); scanf("%d", &x); switch (x) { case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; case 3: printf("Choice is 3"); break; default: printf("Choice other than 1, 2 and 3"); break; } }
•OUTPUT
Enter Value of x : 2
Choice is 2
Second run:
Enter Value of x : 1
Choice is 1
Third run:
Enter Value of x : 50
Choice other than 1, 2 and 3
Here are some switch programmes:
Comments