<< Chapter < Page Chapter >> Page >
An introduction to the case control structure and how it is implemented using a switch within the C++ programming language.

Traditional case control structure

Multiway selection using the case structure

One of the drawbacks of two way selection is that we can only consider two choices. But what do you do if you have more than two choices. Consider the following which has four choices:

if age equal to 18 you can voteelse if age equal to 39you're middle aged elseif age equal to 65 consider retirementelse age is un-important

You get an appropriate message depending on the value of age. The last item is referred to as the default. If the age is not equal to 18, 39 or 65 you get the default message. In some situations there is no default action. Consider this flowchart example:

This flowchart is of the case control structure and is used for multiway selection. The decision box holds the variable age. The logic of the case is one of equality where in the value in the variable age is compared to the listed values in order from left to right. Thus, the value stored in age is compared to 18 or is "age equal to 18". If it is true, the logic flows down through the action and drops out at the bottom of the case structure. If the value of the test expression is false, it moves to the next listed value to the right and makes another comparison. It works exactly the same as our nested if then else structure.

C++ code to accomplish multiway selection

Using the same example as above, here is the C++ code to accomplish the case control structure.

C++ source code - case structure with integers

switch (age) {case 18: cout<<"\nYou can vote."; break;case 39: cout<<"\nYou're middle aged."; break;case 65: cout<<"\nConsider retirement."; break;default: cout<<"\nAge is un-important."; }

Got questions? Get instant answers now!

The first thing you should note is that the C++ programming language does not formally have a case control structure. It does have a switch control structure but it acts differently than the traditional case control structure. We use a break (which is a branching control structure) with the switch to make it act like the traditional case structure. This is one of the few allowable ways to use the switch with break within the C++ programming language to simulate the traditional case structure. All other uses of the switch or break are to be avoided if you are to stay within the bounds of good structured programming techniques.

The value in the variable age is compared to the first "case" (note: case is one of the C++ reserved words) which is the value 18 (also called the listed value) using an equality comparison or is "age equal to 18". If it is true, the cout is executed which displays “You can vote.” and the next line of code (the break) is done (which jumps us to the end of the control structure). If it is false, it moves on to the next case for comparison.

Most programming languages, including C++, require the listed values for the case control structure be of the integer family of data types. This basically means either an integer or character data type. Consider this example that uses character data type (choice is a character variable):

C++ source code - case structure with characters

switch (choice) {case 'A': cout<<"\nYou are an A student."; break;case 'B': cout<<"\nYou are a B student."; break;case 'C': cout<<"\nYou are a C student."; break;default: cout<<"\nMaybe you should study harder."; }

Got questions? Get instant answers now!

Limitations of the case control structure

Most programming languages, including C++, do not allow ranges of values for case like structures. Consider this flowcharting example that used ranges:

Consider also the following pseudocode for the same logic:

Case of age 0 to 17 Display "You can't vote."18 to 64 Display "You’re in your working years." 65 + Display "You should be retired."Endcase

Using the case control structure when using non integer family or ranges of values is allowed when designing a program and documenting that design with pseudocode or flowcharting. However, the implementation in most languages would follow a nested if then else approach with complex Boolean expressions. The logic of the above examples would look like this:

if age>0 and age<= to 17 display You can’t vote.else if age is>= 18 and age<= 64 display You’re in your working years.else display You should be retired.

Good structured programming methods

Most text book authors confirm that good structured programming techniques and habits are more important than concentrating on the technical possibilities and capabilities of the language that you are using to learn programming skills.  Remember, this module is concentrating on programming fundamentals and concepts and it uses the C++ programming language to build our initial programming skills.  It is not a created with the intent to cover the C++ programming language in detail, despite the fact that at times we have to cover C++ language mechanics.

Definitions

case
A control structure that does mulitway selection.
switch
A C++ control structure that can be made to act like a case control structure.

Questions & Answers

how does Neisseria cause meningitis
Nyibol Reply
what is microbiologist
Muhammad Reply
what is errata
Muhammad
is the branch of biology that deals with the study of microorganisms.
Ntefuni Reply
What is microbiology
Mercy Reply
studies of microbes
Louisiaste
when we takee the specimen which lumbar,spin,
Ziyad Reply
How bacteria create energy to survive?
Muhamad Reply
Bacteria doesn't produce energy they are dependent upon their substrate in case of lack of nutrients they are able to make spores which helps them to sustain in harsh environments
_Adnan
But not all bacteria make spores, l mean Eukaryotic cells have Mitochondria which acts as powerhouse for them, since bacteria don't have it, what is the substitution for it?
Muhamad
they make spores
Louisiaste
what is sporadic nd endemic, epidemic
Aminu Reply
the significance of food webs for disease transmission
Abreham
food webs brings about an infection as an individual depends on number of diseased foods or carriers dully.
Mark
explain assimilatory nitrate reduction
Esinniobiwa Reply
Assimilatory nitrate reduction is a process that occurs in some microorganisms, such as bacteria and archaea, in which nitrate (NO3-) is reduced to nitrite (NO2-), and then further reduced to ammonia (NH3).
Elkana
This process is called assimilatory nitrate reduction because the nitrogen that is produced is incorporated in the cells of microorganisms where it can be used in the synthesis of amino acids and other nitrogen products
Elkana
Examples of thermophilic organisms
Shu Reply
Give Examples of thermophilic organisms
Shu
advantages of normal Flora to the host
Micheal Reply
Prevent foreign microbes to the host
Abubakar
they provide healthier benefits to their hosts
ayesha
They are friends to host only when Host immune system is strong and become enemies when the host immune system is weakened . very bad relationship!
Mark
what is cell
faisal Reply
cell is the smallest unit of life
Fauziya
cell is the smallest unit of life
Akanni
ok
Innocent
cell is the structural and functional unit of life
Hasan
is the fundamental units of Life
Musa
what are emergency diseases
Micheal Reply
There are nothing like emergency disease but there are some common medical emergency which can occur simultaneously like Bleeding,heart attack,Breathing difficulties,severe pain heart stock.Hope you will get my point .Have a nice day ❣️
_Adnan
define infection ,prevention and control
Innocent
I think infection prevention and control is the avoidance of all things we do that gives out break of infections and promotion of health practices that promote life
Lubega
Heyy Lubega hussein where are u from?
_Adnan
en français
Adama
which site have a normal flora
ESTHER Reply
Many sites of the body have it Skin Nasal cavity Oral cavity Gastro intestinal tract
Safaa
skin
Asiina
skin,Oral,Nasal,GIt
Sadik
How can Commensal can Bacteria change into pathogen?
Sadik
How can Commensal Bacteria change into pathogen?
Sadik
all
Tesfaye
by fussion
Asiina
what are the advantages of normal Flora to the host
Micheal
what are the ways of control and prevention of nosocomial infection in the hospital
Micheal
what is inflammation
Shelly Reply
part of a tissue or an organ being wounded or bruised.
Wilfred
what term is used to name and classify microorganisms?
Micheal Reply
Binomial nomenclature
adeolu
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Programming fundamentals - a modular structured approach using c++. OpenStax CNX. Jan 10, 2013 Download for free at http://cnx.org/content/col10621/1.22
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Programming fundamentals - a modular structured approach using c++' conversation and receive update notifications?

Ask