Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

switch statement in C-Programming

The document explains the switch statement in C, which evaluates an expression and executes associated statements based on its value, serving as a more efficient alternative to lengthy if-else-if ladders. It outlines the syntax, rules, and examples of using switch cases, including the optional break and default statements, as well as the ability to use ranges in GNU C. The document also discusses the advantages and disadvantages of switch statements, along with a comparison to if-else-if structures.

Uploaded by

kussupurne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

switch statement in C-Programming

The document explains the switch statement in C, which evaluates an expression and executes associated statements based on its value, serving as a more efficient alternative to lengthy if-else-if ladders. It outlines the syntax, rules, and examples of using switch cases, including the optional break and default statements, as well as the ability to use ranges in GNU C. The document also discusses the advantages and disadvantages of switch statements, along with a comparison to if-else-if structures.

Uploaded by

kussupurne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Switch Statement in C

Last Updated : 29 Aug, 2024

Switch case statement evaluates a given expression and based on the evaluated value(matching a
certain condition), it executes the statements associated with it. Basically, it is used to perform
different actions based on different conditions(cases).

• Switch case statements follow a selection-control mechanism and allow a value to change
control of execution.
• They are a substitute for long if statements that compare a variable to several integral values.
• The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.

In C, the switch case statement is used for executing one condition from multiple conditions. It is
similar to an if-else-if ladder.
The switch statement consists of conditional-based cases and a default case.

Syntax of switch Statement in C


switch(expression)

case valuel : statement 1;


break;
case value2: statement 2;
break;

case value n: statement n;


break;
default: default statement;

How to use switch case Statement in C?


Before using the switch case in our program, we need to know about some rules of the switch
statement.

Rules of the switch case statement

Following are some of the rules that we need to follow while using the switch statement:

1. In a switch statement, the "case value" must be of "char" and "int" type.
2. There can be one or N number of cases.
3. The values in the case must be unique.
4. Each statement of the case can have a break statement. It is optional.
5. The default Statement is also optional.
Example

// C programto Demonstratereturning of day based numeric


// value
#include <stdio.h>
int main()
// switchvariable
int var -
// switch statement
switch (var)
case 1
printf( "Case 1 is Matched.")
break;
case 2
printf( "Case 2 is Matched." •
break;
case 3
printf( "Case 3 is Matched." •
break;
default :
printf( "Default case is Matched.")
break;

return 0,

Output

Case I is Matched.
How switch Statement Work?
The working of the switch statement in C is as follows:

1. Step 1: The switch variable is evaluated.


2. Step 2: The evaluated value is matched against all the present cases.
3. Step 3A: If the matching case value is found, the associated code is executed.
4. Step 3B: If the matching code is not found, then the default case is executed if present.
5. Step 4A: If the break keyword is present in the case, then program control breaks out of the
switch statement.
6. Step 4B: If the break keyword is not present, then all the cases after the matching case are
executed.
7. Step 5: Statements after the switch statement are executed.

We can also understand the working of the switch statement in C using the flowchart.

Flowchart of Switch Statement

Flowchart Ofswitch statement in C

Break in switch case


This keyword is used to stop the execution inside a switch block. It helps to terminate the switch
block and break out of it. When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
The break statement is optional. If omitted, execution will continue on into the next case. The flow
of control will fall through to subsequent cases until a break is reached.

Example of switch case without break

// C Programto demonstrate
the behaviourof switchcase
// withoutbreak
#include <stdio.h>
int main()

int var
// switch case withoutbreak
switch (var)
case 1
printf( "Case 1 is executed.\n");
case 2
printf("Case 2 is executed.\n");
case 3
printf("Case 3 is executed.
case 4
printf( '"Case4 is executed.
return 0,

Output

Case 2 executed .
Case 3 executed. Case 4 is executed.
Default in switch case
The default keyword is used to specify the set of statements to execute if there is no case match.
It is optional to use the default keyword in a switch case. Even if the switch case statement does
not have a default statement, it would run without any problem.

Important Points About Switch Case Statements

1. Switch expression should result in a constant value

If the expression provided in the switch statement does not result in a constant value, it would not
be valid. Some valid expressions for switch case will be,

// Constant expressions allowed


switch(1+2+23)
switch(l *2+3%4)
// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)

2. Expression value should be only of int or char type.

The switch statement can only evaluate the integer or character value. So the switch expression
should return the values of type int or char only.

3. Case Values must be Unique

In the C switch statement, duplicate case values are not allowed.

3. Nesting of switch Statements

Nesting of switch statements is allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes the program
more complex and less readable.

4. The default block can be placed anywhere

Regardless of its placement, the default case only gets executed if none of the other case
conditions are met. So, putting it at the beginning, middle, or end doesn't change the core logic.
Examples of switch Statement in C

Example 1: C Program to print the day of the week using a switch case.

// C programto print the day using switch


#include <stdåo.h>
// Driver Code
int main()
int day
printf( "The day with number%d is day) ;
switch (day)
case 1
printf( "Monday" ) ;
break;
case 2
printf( "Tuesday") ;
break;
case 3
printf( "Wednesday");
break;
case 4
printf( "Thursday" ) ;
break;
case 5
printf( " Friday" );
break;
case 6
printf( "Saturday" ) ;
break;
case 7
printf( "Sunday" ) ;
break;
default :
printf( "Invalid Input");
break;
return 0,

Output

The day with number 2 is Tuesday


Example 2: Simple Calculator using switch case in C

// C Programto create a simple calculator using switch


// statement
#include <stdåo.h>
#include
// driver code
int main()
// switch variable
char choice;
// operands
int x, y;
while (1)
printf("Enter the Operator (+,-,*,/)\nEnter x to
"exit\n");
scanf(" %c", &choice);
// for exit
if (choice 'x')
exit(0) ;

printf( "Enter the two numbers:


scanf("%d , &x, &y);
// switch case with operation for each operator
switch (choice)
Case
printf(" %d y,
break;
case
printf(
break;
Case '
printf( * %d y,
break;
case '/'
printf( %d y,
break;
default :
printf("lnvalid Operator Input\n");

return 0,

Output

Enter the operator (+,


Enter x to exit

Enter the two numbers: 100 + 200


100 + 200 = 300
Advantages of C switch Statement
1. Easier to read than if else if.
2. Easier to debug and maintain for a large number of conditions.
3. Faster execution speed.

Disadvantages of C switch Statement


1. Switch case can only evaluate int or char type.
2. No support for logical expressions.
3. Have to keep in mind to add a break in every case.

Conclusion
In this article, we discussed the switch statement in C programming and how to use it. It is a
conditional statement like the if-else-if ladder having its own merits and demerits. It is mostly
preferred when the number of conditions to evaluate is large.

Switch Statement in C —FAQs

What is the switch case in C?

The switch case statement is a flow control statement in which we can define a switch
variableand then executedifferentcode based on the value of the switch variable.It is an
alternativeof if else if ladder.

What is the case in the switch statement in C?

The case keywordis used to define the differentcases and their associated code in the switch
statement.

What does the break in the switch case do?

The break keywordis used to exit the switch blockafter executingthe matching case.

What are the differences between switch and if else if ladder in C?

Followingare the main differencesbetween C switch and C if else if ladder:

switch

• It executes the differentcases on the basis of the value of the switch variable.
• It can only evaluate the int or char type expressions.
• Faster and easier to read for the large number of conditions.

if else if

It executes the differentblocks based on the conditionspecified.


• It can evaluate any type of expression.
• It can get messy when there are lots of conditions.
Using Range in switch Case in C
Last Updated : 26 Dec, 2023

You all are familiar with switch case in C, but did you know you can use a range of numbers
instead of a single number or character in the case statement? Range in switch case can be useful
when we want to run the same set of statements for a range of numbers so that we do not have to
write cases separately for each value.

• That is the case range extension of the GNU C compiler and not standard C.
• You can specify a range of consecutive values in a single case label.

Syntax

The syntax for using range case is:

case low . . high:

It can be used for a range of ASCII character codes like this:

case 'A'

You need to Write spaces around the ellipses ( ). For example, write this:

// Correct case 1 5:
// Wrong - case 1...5.

The below program illustrates the use of range in switch case.

c
C program to illustrate
// using range in switch case
*include < stdio.h>
int main ()

int arra 15, 20 1;

for (int 14
switch arr[i])
// range 1 to 6
case 1 6:
printf( "Ed in range arr 1
break;
// range 19 to 20
case 19
print f ( in range 19 to 20\n' arr 1
break;
default:
print f ( not in range\n• arr[i]);
break;

return O ;

Output

1 in range 1 to 6
5 in range 1 to 6
15 not in range
20 in range 19 to 20
Complexity Analysis

• Time Complexity: O(n), where n is the size of array arr.


• Auxiliary Space: 0(1)

Error conditions

1. low > high: The compiler gives an error message.


2. Overlapping case values: If the value of a case label is within a case range that has already
been used in the switch statement, the compiler gives an error message.

You might also like