Sei sulla pagina 1di 36

Switch statement in C

When you want to solve multiple option type problems, for example: Menu like program,
where one value is associated with each option and you need to choose only one at a time,
then, switchstatement is used.
Switch statement is a control statement that allows us to choose only one choice among the
many given choices. The expression in switch evaluates to return an integral value, which is
then compared to the values present in different cases. It executes that block of code which
matches the case value. If there is no match, then default block is executed(if present). The
general form of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}

Rules for using switch statement

1. The expression (after switch keyword) must yield an integer value i.e the expression
should be an integer or a variable or an expression that evaluates to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be any valid C statement.

Points to Remember

1. We don't use those expressions to evaluate switch case, which may return floating point
values or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use break after
each block, but if you do not use it, then all the consecutive blocks of code will get
executed after the matching block.
3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
11. printf("C");
12. break;
}

A B C

The output was supposed to be only A because only the first case matches, but as
there is no break statement after that block, the next blocks are executed too, until it
a break statement in encountered or the execution reaches the end of the switch block.
13. default case is executed when none of the mentioned case matches
the switch expression. The default case can be placed anywhere in the switch case.
Even if we don't include the default case, switch statement works.
14. Nesting of switch statements are allowed, which means you can
have switch statements inside another switch block. However,
nested switch statements should be avoided as it makes the program more complex
and less readable.

Example of switch statement


#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
/* Taking users input */
scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}

Difference between switch and if

 if statements can evaluate float conditions. switch statements cannot

evaluate floatconditions.
 if statement can evaluate relational operators. switch statement cannot evaluate

relational operators i.e they are not allowed in switch statement.

Rules of Using Switch Case in C Programming

1. Case Label must be unique

2. Case Labels must ends with Colon

3. Case labels must have constants / constant expression

4. Case label must be of integral Type ( Integer,Character)

5. Case label should not be ‘floating point number ‘

6. Switch case should have at most one default label

7. Default label is Optional

8. Default can be placed anywhere in the switch

9. Break Statement takes control out of the switch

10. Two or more cases may share one break statement


11. Nesting ( switch within switch ) is allowed.

12. Relational Operators are not allowed in Switch Statement.

13. Macro Identifier are allowed as Switch Case Label.

14. Const Variable is allowed in switch Case Statement.

15. Empty Switch case is allowed.

Syntax of Switch Case :

switch ( expression )
{
case label1 :
body1
break;

case label2 :
body2
break;

case label3 :
body3
break;

default :
default-body
break;
}
next-statement;

Rule 1 : Case Label must be unique

int id = 3 ;
switch(id)
{
case 1:
printf("C Programming Language");
break;
case 2:
printf("C++ Programming Language");
break;
case 2:
printf("Web Technology");
break;
default :
printf("No student found");
break;
}

Rule 2 : Case Labels must ends with Colon

case 1 :
printf("C Programming Language");
break;

Rule 3 : Case labels must have constants / constant expression

case 1+1:
case 'A':
case 67:

these are allowed examples of switch case labels , however variables are not allowed in switch case
labels.

case var :
case num1 :
case n1+n2 :
Rule 4 : Case label must be of integral Type ( Integer,Character) whereas
Case label should not be ‘floating point number ‘

case 10:
case 20+20:
case 'A':
case 'a':

these are allowed examples and following are illegal examples –

case 10.12:
case 7.5:

Rule 5 : Switch case should have at most one default label

switch(roll)
{
case 1:
printf("C Programming Language");
break;
case 2:
printf("C++ Programming Language");
break;
case 2:
printf("Web Technology");
break;
default :
printf("Default Version 1");
break;
default :
printf("Default Version 2");
break;
}

It violets first rule.


Rule 6 : Default label is Optional

switch(roll)
{
case 1 :
printf("C Programming Language");
break;
case 2 :
printf("C++ Programming Language");
break;
case 2 :
printf("Web Technology");
break;
}

default statement is optional. It can be neglected.

Rule 7 : Default can be placed anywhere in the switch

switch(roll)
{
case 1 :
printf("C Programming Language");
break;
default:
printf("No Student Found");
break;
case 2 :
printf("C++ Programming Language");
break;
case 2 :
printf("Web Technology");
break;
}
Rule 8 : Break Statement takes control out of the switch
Rule 9 : Two or more cases may share one break statement

switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
printf("Alphabet B");
break;
}

Rule 10 : Nesting ( switch within switch ) is allowed

switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
switch(alpha)
{
}
break;
}

nesting of switch case is allowed in C.

Rule 11 : Relational Operators are not allowed in Switch Statement.


switch(num)
{
case >15:
printf("Number > 15");
break;
case =15:
printf("Number = 15");
break;
case <15:
printf("Number < 15");
break;
}

relational operators are not allowed as switch label.

Rule 12 : Macro Identifier are allowed as Switch Case Label.

#define MAX 2

switch(num)
{
case MAX:
printf("Number = 2");
break;
}

as preprocessor will replace occurrence of MAX by constant value i.e 2 therefor it is allowed.

Rule 13 : Const Variable is allowed in switch Case Statement.

int const var = 2;

switch(num)
{
case var:
printf("Number = 2");
break;
}

Illegal way of using Switch Statement in C Programming ?


We have collected all the scenarios of switch that results into compile error. We call them as illegal
use of switch case statement, following are the illegal ways of switch case statement in C Programming
language :

1. Floating point values are not allowed as Case Label.

2. Case Labels Should be Unique.

3. Variables are not allowed in switch case.

4. Comparison operators are not at all accepted.

5. All statements inside switch must be wrapped inside any of the case.

Case 1 : Floating Case Not Allowed !!!


switch case label allows only integer value inside case label. Floating points are not at all accepted
inside switch case.

i = 1.5
switch ( i )
{
case 1.3:
printf ("Case 1.3");
break;
case 1.4:
printf ("Case 1.4");
break;
case 1.5:
printf ("Case 1.5");
break;
default :
printf ("Default Case ");
}

Case 2 : Case Labels Should be Unique

i = 1;
switch ( i )
{
case 1:
printf ("Case 1");
break;
case 1:
printf ("Case 2");
break;
case 3:
printf ("Case 3");
break;
default :
printf ("Default Case ");
}

Case 3 : Case Labels Should not Contain any Variable


Case label must be constant value.

i = 1;
switch ( i )
{
case 1:
printf ("Case 1");
break;
case i + i :
printf ("Case 2");
break;
case 3:
printf ("Case 3");
break;
default :
printf ("Default Case ");
}

Case 4 : All Cases must wrapped in any of the case


( Generally Compiler won’t show Error Message but It will neglect statement which does not belongs
to any case)

i = 1;
switch(i)
{
printf ( "Hi") // It does not belongs to any case
case 1:
printf("Case 1");
break;
case 2:
printf("Case 2");
break;
case 3:
printf("Case 3");
break;
default :
printf("Default Case ");
}

Output :

Case 1

Case 5 : Comparison Not allowed


i = 1;
switch(i)
{
case i>1:
printf ("Case 3");
break;
default :
printf ("Default Case ");
}

There are 4 types of case control statements in C language. They are,

1. switch
2. break
3. continue
4. goto
1. SWITCH CASE STATEMENT IN C:
 Switch case statements are used to execute only specific case statements based on the switch expression.
 Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
case label3: statements;
break;
default: statements;
break;
}
EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C:
C

1 #include <stdio.h>

3 int main ()
4 {

5 int value = 3;

6 switch(value)

7 {

8 case 1:

9 printf(“Value is 1 \n” );

10 break;

11

12 case 2:

13 printf(“Value is 2 \n” );

14 break;

15

16 case 3:

17 printf(“Value is 3 \n” );

18 break;

19

20 case 4:

21 printf(“Value is 4 \n” );

22 break;

23

24 default :

25 printf(“Value is other than 1,2,3,4 \n” );

26 }

27 return 0;

28 }

COMPILE & RUN


OUTPUT:
Value is 3

2. BREAK STATEMENT IN C:
 Break statement is used to terminate the while loops, switch case loops and for loops from the subsequent
execution.
 Syntax: break;
EXAMPLE PROGRAM FOR BREAK STATEMENT IN C:
C
1 #include <stdio.h>

2 int main()

3 {

4 int i;

6 for(i=0;i<10;i++)

7 {

8 if(i==5)

9 {

10 printf("\nComing out of for loop when i = 5");

11 break;

12 }

13 printf("%d ",i);

14 }

15 }

COMPILE & RUN


OUTPUT:
01234
Coming out of for loop when i = 5

3. CONTINUE STATEMENT IN C:
 Continue statement is used to continue the next iteration of for loop, while loop and do-while loops. So, the
remaining statements are skipped within the loop for that particular iteration.
 Syntax : continue;
EXAMPLE PROGRAM FOR CONTINUE STATEMENT IN C:
C

1 #include <stdio.h>

2 int main()

3 {
4 int i;

5 for(i=0;i<10;i++)

6 {

7 if(i==5 || i==6)

8 {

9 printf("\nSkipping %d from display using " \

10 "continue statement \n",i);

11 continue;

12 }

13 printf("%d ",i);

14 }

15 }

COMPILE & RUN


OUTPUT:
01234

Skipping 5 from display using continue statement


Skipping 6 from display using continue statement
789

4. GOTO STATEMENT IN C:
 goto statements is used to transfer the normal flow of a program to the specified label in the program.
 Below is the syntax for goto statement in C.
{
…….
go to label;
…….
…….
LABEL:
statements;
}
EXAMPLE PROGRAM FOR GOTO STATEMENT IN C:
C

1 #include <stdio.h>

2 int main()
3 {

4 int i;

5 for(i=0;i<10;i++)

6 {

7 if(i==5)

8 {

9 printf("\nWe are using goto statement when i = 5");

10 goto HAI;

11 }

12 printf("%d ",i);

13 }

14

15 HAI : printf("\nNow, we are inside label name \"hai\" \n");

16 }

COMPILE & RUN


OUTPUT:
01234
We are using goto statement when i = 5
Now, we are inside label name “hai”

Decision making using switch-case-default


Many times in our daily lives, we face conditions where we are required to choose
between a number of alternatives rather than just two or three. For example,
which school to go to, which food to have in a restaurant, which game to play,
etc. Similarly, in programming languages, we sometimes face problems where we
have to make the program user-friendly by giving them more than two
alternatives to choose from rather than just one or two.

In such cases, it becomes a convoluted problem if we use a series of if-else


statements. Therefore, C provides us a discrete control statement which
is "switch" to handle such issues effectively. Let us learn how to use a switch,
case and default keywords?

The general form of the three keywords is:


switch (integral_expression)
{
case constant_1:
code;
[break;]
case constant_2:
code;
[break;]

.
.
.

case constant_n:
code;
[break;]

default:
code;
}

Points to be noted:

1. The integer expression after the switch keyword is any valid C statement
that yields an integer value. Example, integer constants like 1, 2, 100 etc.
2. The values of constant_1, constant_2 after the case keyword can be an
integer or character. But all these constants must be different from each
other.
3. The code mentioned above is the code that we want to execute. It can be
anything ranging from printf to another switch-case ladder.
4. Now, when we run our program, what happens first is the integer
expression gets evaluated.
5. The control then goes inside the switch and the value received from the
integer expression is compared with the case constants.
6. If the match is found with any case constant, that particular case will be
executed along with the following case and default statements.
7. If the match is not found, only the statements after the default get
executed.

Example:

#include <stdio.h>
int main( )
{
int i = 2 ;

switch ( i )
{
case 1:
printf ( "1 \n" ) ;

case 2:
printf ( "2 \n" ) ;

case 3:
printf ( "3 \n" ) ;

default:
printf ( "No match \n" ) ;
}

return 0;
}

Output

2
3
No match

In the program above, most of us expected the output to be only 2 since the
value of constant i is 2. But that does not happen since all the case statements
and the default gets executed after the match is found, as mentioned earlier.

To prevent this from happening, we use another statement called the break
statement to get the output from that particular case only. Note that break need
not be written after the default statement since the control comes out of the
switch loop anyway.

Example:
#include <stdio.h>

int main( )
{
int i = 2 ;

switch ( i )
{
case 1:
printf ( "1 \n" ) ;
break;

case 2:
printf ( "2 \n" ) ;
break;

case 3:
printf ( "3 \n" ) ;
break;

default:
printf ( "No match \n" ) ;
}

return 0;
}

Output

More about switch (some useful points and some


disadvantages)
1) The above program need not be made in an ascending order only. It can
be made in other order.

Example:
#include<stdio.h>

int main( )
{
int i = 2 ;

switch ( i )
{
case 34 :
printf ( "1 \n" ) ;
break;

case 2 :
printf ( "2 \n" ) ;
break;

case 121 :
printf ( "3 \n" ) ;
break;

default :
printf ( "No match \n" ) ;
}

return 0;
}

Output

2) We can also use "character values" in "case and switch".

Example:

#include<stdio.h>

int main()
{

char ch = 's';
switch (ch)
{
case 'a':
printf("The letter is 'a'");
break;

case 'b':
printf("The letter is 'b'");
break;

case 's':
printf("The letter is 's'");
break;

default:
printf("No match");
}

return 0;
}

Output

The letter is 's'

The characters are in reality replaced by their ASCII values by the compiler to
make them act like integer constants.

3) If we want to write multiple statements within a particular case, we need not


enclose them within a pair of braces.

4) If there is a statement inside the switch statement but it does not belong to
any of the cases then that particular statement will not be executed or in other
words will be skipped by the compiler.

5) It is not compulsory to add the default statement at the end of the switch.
Even if we don’t write it, the program would run just the same.
6) Nested switches exist in reality but rarely used. The switch statements are
mostly used for writing menu driven programs.

7) Many times, we want to execute the same set of statements under different
cases. This can be done as shown below.

Example:

#include <stdio.h>

int main()
{

char ch;

printf("Enter alphabets a, b or c:\n");


scanf("%c",&ch);

switch(ch)
{
case 'a':
case 'A':
printf("The letter is 'a'");
break;

case 'b':
case 'B':
printf("The letter is 'b'");
break;

case 'c':
case 'C':
printf("The letter is 's'");
break;

default:
printf("No match");
}

return 0;
}
Output

Enter alphabets a, b or c: b
The letter is 'b'

Here, what happens is that the cases keep executing until a break statement is
found. Therefore, if for example if alphabet a is entered the case 'a' is satisfied
and because there are no statements after that, the control goes to the
next case i.e. case 'A' and executes the statements underneath that.

8) The switch statement is often compared with the if statement. It is better to


use the switch in many cases due to the advantages listed above but also, the
disadvantage of the switch is that we can't have a case which contains
conditionals like: case i > 10:

switch : A compound statement


This statement is used when we have to select one choice from multiple choices
on the basis of the value of some variable.

Syntax for switch statement:

switch(expression/condition)
{
case 1:
statements;
[break;]
case 2:
statements;
[break;]
default:
statements;
}

Here, expression can be anything that returns integer value or character value
but not a floating value.

Example:

#include <stdio.h>
int main()
{
int a = 2 ;

switch(a)
{
case 1:
printf("abc");
break;

case 2:
printf("xyz");
break;

case 3:
printf("pqr");
break;

default:
printf("stu");
}

return 0;
}

Output

xyz

Here, a is an expression which returning an integer value since it's value is 2 case
2 will be executed. Note that as we have used break statement here only case
2 will be executed and after that control will come out of the closing brace of the
switch.

Note: Also keep in mind that switch, case, default are all keywords.

Features of switch
 To execute multiple statements, in any case, there is no requirement of
braces as in if else.
 The default may or may not use the break statement.
 We can use case number in ascending or descending order or in any
random order.
 In both switch and case, we use int or char constant.
 We can use default anywhere in the program because every
time default is executed only when there is no match of any case.
 We can execute a common set of statement for multiple cases.
 If there is any statement in switch then it must be in any case.

Executing a common set of statements for multiple cases

#include <stdio.h>

int main()
{
int a = 2 ;

switch(a)
{
case 1:
case 2:
printf("xyz");
break;

case 3:
printf("pqr");
break;

default:
printf("stu");
}
return 0;
}

Output

xyz

Here, if even case 1 is encountered xyz is printed.


Disadvantages of switch statements
1. float constant cannot be used in the switch as well as in the case.
2. You can not use the variable expression in case.
3. You cannot use the same constant in two different cases.
4. We cannot use the relational expression in case.

Difference between switch case and if-else


Sr The switch case The if - else
No

1 In case of a switch, we create jump table on In this case, we do not create a jum
compile time only selected case is executed on table and all cases are executed at
runtime. runtime.

2 If a program is large we use the switch If a program is large then program


statement. structure will be more complex.

3 If a program is large, then switch case gives the If a program is small we use if else
more structured program.

Using switch case to design calculator

#include<stdio.h>

int main()
{
int num1,num2,opt;

printf("Enter the first Integer: ");


scanf("%d",&num1);
printf("Enter the second Integer: ");
scanf("%d",&num2);
printf("1:addition \n2: subtraction \n3:
multiplication \n4: division\n");
printf("Enter an correct option...: ");
scanf("%d",&opt);

switch(opt)
{
case 1:
printf("\nAddition of %d and %d is:
%d",num1,num2,num1+num2);
break;

case 2:
printf("\nSubstraction of %d and %d is:
%d",num1,num2,num1-num2);
break;

case 3:
printf("\nMultiplication of %d and %d is:
%d",num1,num2,num1*num2);
break;

case 4:
if(num2==0)
{
printf("OOps Devide by zero\n");
}
else
{
printf("\n Division of %d and %d
is: %d",num1,num2,num1/num2);
}
break;

default:
printf("\n Enter correct option\n");
}

return 0;
}

Output
Enter the first Integer: 10
Enter the second Integer: 6
1:addition
2: subtraction
3: multiplication
4: division
Enter an correct option...: 3
Multiplication of 10 and 6 is: 60

Switch case statement in C language


In C Programming Language, ladder/multiple if can be replaced by the switch
case statement, if value to be tested is integral type.

Switch statement is used to check a conditional expression or variable with the


given multiple choices of integral types. These integral values are called case
values.

In switch statement these is one condition (variable), which is checked with its
multiple case values. This statement is very useful in programming language.

Remember following points:

 There may be multiple values to be checked.


 Program’s control moves to the matched case value, if there is no case
value found it moves to the default case.
 case value must be integral type literal, variable can not be use as a case
value.
 default case statement is an option, but it should be use.
 default case can be placed anywhere in the switch body, but should be
use at the end of the switch body.
 Multiple case value can have single body i.e. you can check more than one
case values for single set of statements.
 Do not forget to put break after the case body.
 switch statement has fall-down property, if break is not found,
program’s execution moves to the next case body whether it is matched or
not.
Syntax

switch(test-condition/variable)
{
case case-value:
block1;
[break];

case case-value:
block2;
[break];

case case-value:
block3;
[break];

case case-value:
block4;
[break];

default:
block-default;
}

Here, break is an optional may be ignored if you are checking multiple case
values for single block (set of statements).

Consider the examples:

/* program to print number from 0 to 5 using switch*/


#include <stdio.h>
int main()
{
int num;
printf("Enter an integer number: ");
scanf("%d",&num);
switch(num){
case 0:
printf("Zero");
break;
case 1:
printf("One");
break;
case 2:
printf("Two");
break;
case 3:
printf("Three");
break;
case 4:
printf("Four");
break;
case 5:
printf("Five");
break;
default:
printf("Invalid Number");
}
return 0;
}

Output
First run:
Enter an integer number: 0
Zero

Second run:
Enter an integer number: 4
Four

Third run:
Enter an integer number: 8
Invalid Number

Consider the example to check whether entered character is VOWEL or


CONSONANT using switch statement having multiple case values without
using break, because here we are checking multiple case values for single
block.

/*program to chech entered character is VOWEL or


CONSONANT*/

#include < stdio.h >


int main()
{

char ch;
printf("Enter a character: ");
scanf("%c",&ch);

if( (ch>='A' && ch<='Z') || (ch>='a' && ch<='z') )


{
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
printf("%c is a VOWEL.",ch);
break;
default:
printf("%c is a CONSONANT.",ch);
}
}
else
printf("Entered character is INVALID.");
return 0;
}

Output
First run:
Enter a character: I
I is a VOWEL.

Second run:
Enter a character: t
I is a CONSONANT.

Third run:
Enter a character: 9
Entered character is INVALID.
++++++++++++++++++++++++++++++++++++++++++

Using range with switch case statement in


C programming language
Learn: How we can use switch case with the case values in a range in C
programming language? In this article, we are going to explain the same with
an example.
Yes, we can use a range of values with switch case statement; in this article we
are going to discuss the same.

For example, if you want to execute same set of statements with a range of
numbers, you do not need to write separate case values, you can use range
like min_value ... max_value.

Example:

If you want to check range from 1 to 10, you will have to write case 1 ...
10: there are spaces beween min_value, three dots (...) and max_value.

Consider the program:

#include <stdio.h>

int main()
{
int number;

//read number
printf("Enter any number (1-100): ");
scanf("%d",&number);

//switch case statement


switch(number)
{
//case values within a range
case 1 ... 50:
printf("Number is in between 1 to
50\n");
break;
//case values within a range
case 51 ... 100:
printf("Number is in between 51 to
100\n");
break;
//default case
default:
printf("Number is out of range!!!\n");
break;
}

return 0;
}

Output
First run:
Enter any number (1-100): 10
Number is in between 1 to 50

Second run:
Enter any number (1-100): 70
Number is in between 51 to 100

Third run:
Enter any number (1-100): 120
Number is out of range!!!

In first input, we entered 10 and it matches with case 1 ... 50 and the output
is "Number is in between 1 to 50", same as in second input, we entered 70,
which matches with case 51 ... 100 and the output is "Number is in between 51
to 100". And in this third input, we entered 120 which does not match with any
case range, thus default case is executed and the output is "Number is out of
range!!!".

By this way, we do not need to use write values with separate cases, if the values
that you want to validate are in range and want to execute the same body (set of
statements), we can use switch statement with the case values in a range.

Potrebbero piacerti anche