SlideShare a Scribd company logo
1 of 5
Download to read offline
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072
© 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 540
Switch Case Statements in C
Naren Khatwani
Student, Department of Computer Engineering, Vivekanand Education Society’s Institute of Technology,
Maharashtra, India
--------------------------------------------------------------------------***----------------------------------------------------------------------------
Abstract: C programs are very versatile in nature. These
programs handle the dynamic operations through a number
of instructions and syntax. One such operation performed is
the use of switch cases with appropriate break statements.
However, it has been observed that the code repeats itself
majority of times during the switch case statement execution
which is a major drawback. This paper thus focusses on the
mechanism to avoid repetition of code through the concept
of fall through and expresses the methodology to achieve fall
through using appropriate break statements and required
syntax.
1. INTRODUCTION
Languages used in any computer system has a set of
instructions to execute. These languages though
interpreted by the systems are in binary, assembly and
higher level languages form the crux for any human being
to operate the system. These high level languages have a
group of instructions written to form the code that needs
executions
It has been observed that though switch case operation is
very versatile operation it has a number of drawbacks
namely: repetition of code, increased execution time,
reduced usability. Though it is widely accepted the
drawbacks tend to decease the effectiveness of the
language. One solution to resolve the conflicts created by
switch case is using the mechanism of Fall through. Fall
through in switch statement means jumping of statements
during absence of break statement after each case.
1.1 SWITCH STATEMENT
The basic syntax of the switch case is as follows
switch (variable to be used) {
case name1 : statements;
break;
case name2 : statements;
break;
case name2 : statements;
break;
default : statements;
}
Where case indicates,
Break is used to come out of the switch case condition. It
can be said that break is used after each switch case
condition
Thus it can be said that switch case is used when there
exist different conditions for one single expression. The
syntax of switch statement above clearly shows the usage
of break statement. We can see that break statement
causes an immediate exit from the switch.
However as explained below fall through has the syntax
switch (variable to be used)
{
case name1 :
case name2 :
case name3 : statements;
break;
case name4 :
case name5 : statements;
break;
default : statements;
}
This indicates that fall through can be used when there
exist some common conditions for a single expression
while break statement is used only in the common
statement condition for multiple switch cases and In fall
through it can be clearly seen that a common statement
can be written as a condition for multiple cases in order to
provide reusability to the code.
Thus the difference in operations of both is as expressed in
figure 1.Mode of Operation
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072
© 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 541
A break is observed in figure 1 b at the end of all the
statements. This break is necessary to be added after the
last switch case because this will not cause an extra case to
be executed by a mistake.
Figure 1(a):Switch Statement
Figure 1(b):Switch Statement (using Fallthrough)
#include<stdio.h>
int main()
{
int n,t;
printf("ENTER THE NUMBER OF MONTH WHOSE
NUMBER OF DAYS YOU WANT TO KNOW");
scanf("%d",&n);
switch(n)
{
case 1:printf("31 days");
break;
case 2:printf("ENTER YEAR");
scanf("%d",&t);
if(((t%4==0)||(t%400==0))&&(t%100!=0))
printf("29 DAYS");
else
printf("28 DAYS");
break;
No of days in a month without
fallthrough
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072
© 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 542
case 3:printf("31 days");
break;
case 4:printf("30 days");
break;
case 5:printf("31 days");
break
case 6:printf("30 days");…….contd
#include<stdi
o.h>
int main()
{
int n,t;
printf("ENTER THE NUMBER OF MONTH WHOSE
NUMBER OF DAYS YOU WANT TO KNOW");
scanf("%d",&n);
switch(n)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:printf("31 days");
break;
case 2:printf("ENTER YEAR");
scanf("%d",&t);
if(((t%4==0)||(t%400==0))&&(t%100!=0))
{
printf("29
DAYS");
}
else
{…….contd
1.2 Applications of Fallthrough
Duff’s Device:
In the C programming language, Duff's device is a way of
manually implementing loop unrolling by interleaving two
syntactic constructs of C: the do-while loop and a switch
statement.
Loop Unrolling:
Loop unrolling, also known as loop unwinding, is a loop
transformation technique that attempts to optimize a
program's execution speed at the expense of
its binary size, which is an approach known as space–time
tradeoff. The transformation can be undertaken manually
by the programmer or by an optimizing compiler.
The following example explains the usage of Loop
Unrolling:
Consider a normal for Loop that starts from the value
j=5000 and decrements until the value of j is not equal to 0
and the statement inside the for loop adds a value s to the
array element j with each iteration.
for(j=5000;j!=0;j--)
{
b[j]=b[j]+s;
}
Now in order for loop unrolling to occur we need to do
some changes in the for loop
for(j=5000;j!=0;j=j-2)
{
b[j]=b[j]+s;
b[j-1]=b[j-1]+s;
}
Here we have added one more statement in the for loop
which will do the same operation of adding a value ‘s’ with
each iteration to the (j)th element as well as for the (j-1)th
element
Also we need to change the decrement condition to
compensate the variable ‘s’ we added for loop unrolling to
occur.
FALL TRHOUGH OCCURS HERE WHEN THE USER
ENTERS THE VALUE 1,3,5,7,8,10
NO OF DAYS IN A MONTH WITH FALL THROUGH
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072
© 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 543
As we can see above loop unrolling will cause the
iterations to turn near to half the no of iterations that
happened .
Working of Duffs Device:
First pass:
int count ; // Set to 20
{
int m = (count + 7) / 8; // n is now 3. (The "while" is
going to be run three times.)
switch (count % 8) { // The remainder is 4 (20
modulo 8) so jump to the case 4
case 0: // [skipped]
do { // [skipped]
*to = *from++; // [skipped]
case 7:*to = *from++; // [skipped]
case 6:*to = *from++; // [skipped]
case 5:*to = *from++; // [skipped]
case 4:*to = *from++; // Start here. Copy 1 byte
(total 1)
case 3:*to = *from++; // Copy 1 byte (total 2)
case 2:*to = *from++; // Copy 1 byte (total 3)
case 1:*to = *from++; // Copy 1 byte (total 4)
} while (--m > 0); // M = 3 Reduce M by 1, then jump up
//to the "do" if it's still
} // greater than 0 (and it is)
}
Second Pass:
int count;
{
int m = (count + 7) / 8;
switch (count % 8) {
case 0:
do { // The while jumps to here.
*to = *from++; // Copy 1 byte (total 5)
case 7:*to = *from++; // Copy 1 byte (total 6)
case 6: *to = *from++; // Copy 1 byte (total 7)
case 5:*to = *from++; // Copy 1 byte (total 8)
case 4:*to = *from++; // Copy 1 byte (total 9)
case 3:*to = *from++; // Copy 1 byte (total 10)
case 2:*to = *from++; // Copy 1 byte (total 11)
case 1:*to = *from++; // Copy 1 byte (total 12)
} while (--m > 0); // M = 2 Reduce M by 1, then jump
up to the "do" if it's still
} // greater than 0 (and it is)
}
Third Pass:
int count;
{
int m = (count + 7) / 8;
switch (count % 8) {
case 0:
do { // The while jumps to here.
*to = *from++; // Copy 1 byte (total 13)
case 7:*to = *from++; // Copy 1 byte (total 14)
case 6:*to = *from++; // Copy 1 byte (total 15)
case 5:*to = *from++; // Copy 1 byte (total 16)
International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056
Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072
© 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 544
case 4:*to = *from++; // Copy 1 byte (total 17)
case 3:*to = *from++; // Copy 1 byte (total 18)
case 2:*to = *from++; // Copy 1 byte (total 19)
case 1:*to = *from++; // Copy 1 byte (total 20)
} while (--m > 0); // M = 1 Reduce M by 1, then jump up
to the "do" if it's still
} // greater than 0 (and it's not, so bail)
} // continue here...
Conclusions:
C programs are considered very versatile. However in
order to avoid repetition of code two mechanisms namely
switch statement and break can be employed. Fallthrough
as a concept can enable repetition of code through
expressions.
References:
[1]. Holly, Ralf. "A reusable Duff device." Dr. Dobb's
Journal 30.8 (2005): 73-74.
[2]. The C Programming Language-Book by Brian
Kernighan and Dennis Ritchie
[3]. The C programming Language By Brian W. Kernighan
and Dennis M. Ritchie. Published by Prentice-Hall in 1988
ISBN 0-13-110362-8 (paperback) ISBN 0-13-110370-9
[4]. Expert C Programming: Deep C Secrets Book by Peter
van der Linden
[5].https://en.wikipedia.org/wiki/Duff%27s_device
[6]. https://en.wikipedia.org/wiki/Loop_unrolling
[7]. LET US C SOLUTIONS -15TH EDITION Book by
Yashavant Kanetkar
[8].21st Century C: C Tips from the New School Book by
Ben Klemens
[9]. Head First C-Book by David Griffiths and Dawn
Griffiths

More Related Content

What's hot

What's hot (20)

[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)
 
evaluating recursive_applications
evaluating recursive_applicationsevaluating recursive_applications
evaluating recursive_applications
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
 
Introduction to C Programming
Introduction to C Programming Introduction to C Programming
Introduction to C Programming
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
C programming part4
C programming part4C programming part4
C programming part4
 
Branching
BranchingBranching
Branching
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
Pointers operation day2
Pointers operation day2Pointers operation day2
Pointers operation day2
 
Vs c# lecture7
Vs c# lecture7Vs c# lecture7
Vs c# lecture7
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Javascripts hidden treasures BY - https://geekyants.com/
Javascripts hidden treasures            BY  -  https://geekyants.com/Javascripts hidden treasures            BY  -  https://geekyants.com/
Javascripts hidden treasures BY - https://geekyants.com/
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 

Similar to IRJET- Switch Case Statements in C

C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
Control flow stataements
Control flow stataementsControl flow stataements
Control flow stataements
Mitali Chugh
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
ransayo
 

Similar to IRJET- Switch Case Statements in C (20)

C programming session 02
C programming session 02C programming session 02
C programming session 02
 
BIT211_2.pdf
BIT211_2.pdfBIT211_2.pdf
BIT211_2.pdf
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
CST2403 NOTES
CST2403 NOTESCST2403 NOTES
CST2403 NOTES
 
Control flow stataements
Control flow stataementsControl flow stataements
Control flow stataements
 
IRJET- Parallelization of Definite Integration
IRJET- Parallelization of Definite IntegrationIRJET- Parallelization of Definite Integration
IRJET- Parallelization of Definite Integration
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, Strings
 
C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 Slides
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
 
control statements
control statementscontrol statements
control statements
 
Control Structures: Part 2
Control Structures: Part 2Control Structures: Part 2
Control Structures: Part 2
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Area and power performance analysis of floating point ALU using pipelining
Area and power performance analysis of floating point  ALU using pipeliningArea and power performance analysis of floating point  ALU using pipelining
Area and power performance analysis of floating point ALU using pipelining
 
Unit3 cspc
Unit3 cspcUnit3 cspc
Unit3 cspc
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Arduino introduction
Arduino introductionArduino introduction
Arduino introduction
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
C fundamental
C fundamentalC fundamental
C fundamental
 

More from IRJET Journal

More from IRJET Journal (20)

TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
TUNNELING IN HIMALAYAS WITH NATM METHOD: A SPECIAL REFERENCES TO SUNGAL TUNNE...
 
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURESTUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
STUDY THE EFFECT OF RESPONSE REDUCTION FACTOR ON RC FRAMED STRUCTURE
 
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
A COMPARATIVE ANALYSIS OF RCC ELEMENT OF SLAB WITH STARK STEEL (HYSD STEEL) A...
 
Effect of Camber and Angles of Attack on Airfoil Characteristics
Effect of Camber and Angles of Attack on Airfoil CharacteristicsEffect of Camber and Angles of Attack on Airfoil Characteristics
Effect of Camber and Angles of Attack on Airfoil Characteristics
 
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
A Review on the Progress and Challenges of Aluminum-Based Metal Matrix Compos...
 
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
Dynamic Urban Transit Optimization: A Graph Neural Network Approach for Real-...
 
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
Structural Analysis and Design of Multi-Storey Symmetric and Asymmetric Shape...
 
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
A Review of “Seismic Response of RC Structures Having Plan and Vertical Irreg...
 
A REVIEW ON MACHINE LEARNING IN ADAS
A REVIEW ON MACHINE LEARNING IN ADASA REVIEW ON MACHINE LEARNING IN ADAS
A REVIEW ON MACHINE LEARNING IN ADAS
 
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
Long Term Trend Analysis of Precipitation and Temperature for Asosa district,...
 
P.E.B. Framed Structure Design and Analysis Using STAAD Pro
P.E.B. Framed Structure Design and Analysis Using STAAD ProP.E.B. Framed Structure Design and Analysis Using STAAD Pro
P.E.B. Framed Structure Design and Analysis Using STAAD Pro
 
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
A Review on Innovative Fiber Integration for Enhanced Reinforcement of Concre...
 
Survey Paper on Cloud-Based Secured Healthcare System
Survey Paper on Cloud-Based Secured Healthcare SystemSurvey Paper on Cloud-Based Secured Healthcare System
Survey Paper on Cloud-Based Secured Healthcare System
 
Review on studies and research on widening of existing concrete bridges
Review on studies and research on widening of existing concrete bridgesReview on studies and research on widening of existing concrete bridges
Review on studies and research on widening of existing concrete bridges
 
React based fullstack edtech web application
React based fullstack edtech web applicationReact based fullstack edtech web application
React based fullstack edtech web application
 
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
A Comprehensive Review of Integrating IoT and Blockchain Technologies in the ...
 
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
A REVIEW ON THE PERFORMANCE OF COCONUT FIBRE REINFORCED CONCRETE.
 
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
Optimizing Business Management Process Workflows: The Dynamic Influence of Mi...
 
Multistoried and Multi Bay Steel Building Frame by using Seismic Design
Multistoried and Multi Bay Steel Building Frame by using Seismic DesignMultistoried and Multi Bay Steel Building Frame by using Seismic Design
Multistoried and Multi Bay Steel Building Frame by using Seismic Design
 
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
Cost Optimization of Construction Using Plastic Waste as a Sustainable Constr...
 

Recently uploaded

Performance enhancement of machine learning algorithm for breast cancer diagn...
Performance enhancement of machine learning algorithm for breast cancer diagn...Performance enhancement of machine learning algorithm for breast cancer diagn...
Performance enhancement of machine learning algorithm for breast cancer diagn...
IJECEIAES
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
Madan Karki
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
BalamuruganV28
 
Online crime reporting system project.pdf
Online crime reporting system project.pdfOnline crime reporting system project.pdf
Online crime reporting system project.pdf
Kamal Acharya
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
rahulmanepalli02
 

Recently uploaded (20)

Performance enhancement of machine learning algorithm for breast cancer diagn...
Performance enhancement of machine learning algorithm for breast cancer diagn...Performance enhancement of machine learning algorithm for breast cancer diagn...
Performance enhancement of machine learning algorithm for breast cancer diagn...
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
 
Introduction to Artificial Intelligence and History of AI
Introduction to Artificial Intelligence and History of AIIntroduction to Artificial Intelligence and History of AI
Introduction to Artificial Intelligence and History of AI
 
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
 
Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailing
 
Online crime reporting system project.pdf
Online crime reporting system project.pdfOnline crime reporting system project.pdf
Online crime reporting system project.pdf
 
Geometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfGeometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdf
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
Piping and instrumentation diagram p.pdf
Piping and instrumentation diagram p.pdfPiping and instrumentation diagram p.pdf
Piping and instrumentation diagram p.pdf
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
 
AI in Healthcare Innovative use cases and applications.pdf
AI in Healthcare Innovative use cases and applications.pdfAI in Healthcare Innovative use cases and applications.pdf
AI in Healthcare Innovative use cases and applications.pdf
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
 

IRJET- Switch Case Statements in C

  • 1. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072 © 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 540 Switch Case Statements in C Naren Khatwani Student, Department of Computer Engineering, Vivekanand Education Society’s Institute of Technology, Maharashtra, India --------------------------------------------------------------------------***---------------------------------------------------------------------------- Abstract: C programs are very versatile in nature. These programs handle the dynamic operations through a number of instructions and syntax. One such operation performed is the use of switch cases with appropriate break statements. However, it has been observed that the code repeats itself majority of times during the switch case statement execution which is a major drawback. This paper thus focusses on the mechanism to avoid repetition of code through the concept of fall through and expresses the methodology to achieve fall through using appropriate break statements and required syntax. 1. INTRODUCTION Languages used in any computer system has a set of instructions to execute. These languages though interpreted by the systems are in binary, assembly and higher level languages form the crux for any human being to operate the system. These high level languages have a group of instructions written to form the code that needs executions It has been observed that though switch case operation is very versatile operation it has a number of drawbacks namely: repetition of code, increased execution time, reduced usability. Though it is widely accepted the drawbacks tend to decease the effectiveness of the language. One solution to resolve the conflicts created by switch case is using the mechanism of Fall through. Fall through in switch statement means jumping of statements during absence of break statement after each case. 1.1 SWITCH STATEMENT The basic syntax of the switch case is as follows switch (variable to be used) { case name1 : statements; break; case name2 : statements; break; case name2 : statements; break; default : statements; } Where case indicates, Break is used to come out of the switch case condition. It can be said that break is used after each switch case condition Thus it can be said that switch case is used when there exist different conditions for one single expression. The syntax of switch statement above clearly shows the usage of break statement. We can see that break statement causes an immediate exit from the switch. However as explained below fall through has the syntax switch (variable to be used) { case name1 : case name2 : case name3 : statements; break; case name4 : case name5 : statements; break; default : statements; } This indicates that fall through can be used when there exist some common conditions for a single expression while break statement is used only in the common statement condition for multiple switch cases and In fall through it can be clearly seen that a common statement can be written as a condition for multiple cases in order to provide reusability to the code. Thus the difference in operations of both is as expressed in figure 1.Mode of Operation
  • 2. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072 © 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 541 A break is observed in figure 1 b at the end of all the statements. This break is necessary to be added after the last switch case because this will not cause an extra case to be executed by a mistake. Figure 1(a):Switch Statement Figure 1(b):Switch Statement (using Fallthrough) #include<stdio.h> int main() { int n,t; printf("ENTER THE NUMBER OF MONTH WHOSE NUMBER OF DAYS YOU WANT TO KNOW"); scanf("%d",&n); switch(n) { case 1:printf("31 days"); break; case 2:printf("ENTER YEAR"); scanf("%d",&t); if(((t%4==0)||(t%400==0))&&(t%100!=0)) printf("29 DAYS"); else printf("28 DAYS"); break; No of days in a month without fallthrough
  • 3. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072 © 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 542 case 3:printf("31 days"); break; case 4:printf("30 days"); break; case 5:printf("31 days"); break case 6:printf("30 days");…….contd #include<stdi o.h> int main() { int n,t; printf("ENTER THE NUMBER OF MONTH WHOSE NUMBER OF DAYS YOU WANT TO KNOW"); scanf("%d",&n); switch(n) { case 1: case 3: case 5: case 7: case 8: case 10: case 12:printf("31 days"); break; case 2:printf("ENTER YEAR"); scanf("%d",&t); if(((t%4==0)||(t%400==0))&&(t%100!=0)) { printf("29 DAYS"); } else {…….contd 1.2 Applications of Fallthrough Duff’s Device: In the C programming language, Duff's device is a way of manually implementing loop unrolling by interleaving two syntactic constructs of C: the do-while loop and a switch statement. Loop Unrolling: Loop unrolling, also known as loop unwinding, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size, which is an approach known as space–time tradeoff. The transformation can be undertaken manually by the programmer or by an optimizing compiler. The following example explains the usage of Loop Unrolling: Consider a normal for Loop that starts from the value j=5000 and decrements until the value of j is not equal to 0 and the statement inside the for loop adds a value s to the array element j with each iteration. for(j=5000;j!=0;j--) { b[j]=b[j]+s; } Now in order for loop unrolling to occur we need to do some changes in the for loop for(j=5000;j!=0;j=j-2) { b[j]=b[j]+s; b[j-1]=b[j-1]+s; } Here we have added one more statement in the for loop which will do the same operation of adding a value ‘s’ with each iteration to the (j)th element as well as for the (j-1)th element Also we need to change the decrement condition to compensate the variable ‘s’ we added for loop unrolling to occur. FALL TRHOUGH OCCURS HERE WHEN THE USER ENTERS THE VALUE 1,3,5,7,8,10 NO OF DAYS IN A MONTH WITH FALL THROUGH
  • 4. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072 © 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 543 As we can see above loop unrolling will cause the iterations to turn near to half the no of iterations that happened . Working of Duffs Device: First pass: int count ; // Set to 20 { int m = (count + 7) / 8; // n is now 3. (The "while" is going to be run three times.) switch (count % 8) { // The remainder is 4 (20 modulo 8) so jump to the case 4 case 0: // [skipped] do { // [skipped] *to = *from++; // [skipped] case 7:*to = *from++; // [skipped] case 6:*to = *from++; // [skipped] case 5:*to = *from++; // [skipped] case 4:*to = *from++; // Start here. Copy 1 byte (total 1) case 3:*to = *from++; // Copy 1 byte (total 2) case 2:*to = *from++; // Copy 1 byte (total 3) case 1:*to = *from++; // Copy 1 byte (total 4) } while (--m > 0); // M = 3 Reduce M by 1, then jump up //to the "do" if it's still } // greater than 0 (and it is) } Second Pass: int count; { int m = (count + 7) / 8; switch (count % 8) { case 0: do { // The while jumps to here. *to = *from++; // Copy 1 byte (total 5) case 7:*to = *from++; // Copy 1 byte (total 6) case 6: *to = *from++; // Copy 1 byte (total 7) case 5:*to = *from++; // Copy 1 byte (total 8) case 4:*to = *from++; // Copy 1 byte (total 9) case 3:*to = *from++; // Copy 1 byte (total 10) case 2:*to = *from++; // Copy 1 byte (total 11) case 1:*to = *from++; // Copy 1 byte (total 12) } while (--m > 0); // M = 2 Reduce M by 1, then jump up to the "do" if it's still } // greater than 0 (and it is) } Third Pass: int count; { int m = (count + 7) / 8; switch (count % 8) { case 0: do { // The while jumps to here. *to = *from++; // Copy 1 byte (total 13) case 7:*to = *from++; // Copy 1 byte (total 14) case 6:*to = *from++; // Copy 1 byte (total 15) case 5:*to = *from++; // Copy 1 byte (total 16)
  • 5. International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 Volume: 06 Issue: 06 | June 2019 www.irjet.net p-ISSN: 2395-0072 © 2019, IRJET | Impact Factor value: 7.211 | ISO 9001:2008 Certified Journal | Page 544 case 4:*to = *from++; // Copy 1 byte (total 17) case 3:*to = *from++; // Copy 1 byte (total 18) case 2:*to = *from++; // Copy 1 byte (total 19) case 1:*to = *from++; // Copy 1 byte (total 20) } while (--m > 0); // M = 1 Reduce M by 1, then jump up to the "do" if it's still } // greater than 0 (and it's not, so bail) } // continue here... Conclusions: C programs are considered very versatile. However in order to avoid repetition of code two mechanisms namely switch statement and break can be employed. Fallthrough as a concept can enable repetition of code through expressions. References: [1]. Holly, Ralf. "A reusable Duff device." Dr. Dobb's Journal 30.8 (2005): 73-74. [2]. The C Programming Language-Book by Brian Kernighan and Dennis Ritchie [3]. The C programming Language By Brian W. Kernighan and Dennis M. Ritchie. Published by Prentice-Hall in 1988 ISBN 0-13-110362-8 (paperback) ISBN 0-13-110370-9 [4]. Expert C Programming: Deep C Secrets Book by Peter van der Linden [5].https://en.wikipedia.org/wiki/Duff%27s_device [6]. https://en.wikipedia.org/wiki/Loop_unrolling [7]. LET US C SOLUTIONS -15TH EDITION Book by Yashavant Kanetkar [8].21st Century C: C Tips from the New School Book by Ben Klemens [9]. Head First C-Book by David Griffiths and Dawn Griffiths