Switch statement in c program
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:
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
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. Example :
#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;
}
}
First run:
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
Post a Comment
If you have any doubts, Please let me know
Thanks!