In: Computer Science
Write a switch statement that uses the colour of a swab sample of COVID testing vehicle to send a message to a local doctor. Use the messages given for each colour in the table below. Justify your answer.
Colour |
Message |
Blue |
“No virus” |
Yellow |
“Needs to be under observation” |
Red |
“Needs to be admitted in COVID ward” |
The question is asked to implement a switch statement that uses the colour of a swab sample of COVID testing vehicle to send a message to a local doctor. Now, switch statement is a special statement in C, which can be used to check different values and based on the checking, corresponding case will be executed. The algorithm to implement the switch statement is given below:
Step 1: Get the sample as input to the program. Also define
a function sendMessage() that takes a string as an argument to send
it to a local doctor.
Step 2: Write a switch case that will take the argument as the sample. Now implement different cases.
Step 3: If the argument is "Blue", call the function sendMessage( "No virus" ).
Step 4: If the argument is "Yellow", call the function sendMessage( "Needs to be under observation" ).
Step 5: If the argument is "Red", call the function sendMessage( "Needs to be admitted in COVID ward" ).
Step 6: In default case, send "Invalid swab sample or invalid test" to the local doctor or to the laboratory.
If the function sendMessage() is defined to send a message to the
doctor, then the switch case implementation in C++/C would be:
switch(sample)
{
case "Blue": //in case
the sample is blue
sendMessage("No virus\n");
break;
case "Yellow": //in
case the sample is yellow
sendMessage("Needs to be under
observation\n");
break;
case "Red":
//in case the sample is red
sendMessage("Needs to be admitted
to COVID ward\n");
break;
default:
sendMessage("Invalid swab sample or
invalid test\n");
}
Analysis: At first,
the program will get the swab sample from the user. Now this sample
variable is passed to the argument of the switch statement. When
the sample is Blue, corresponding message will be passed, when it
is yellow, corresponding message will be passed and so on. The
message is passed using a function sendMessage() that sends the
message to a local doctor. After each case, the
break statement must be there in order to avoid
the other cases. There is also a default case (does not come under
any other defined case), that sends a message about the invalid
sample or invalid test to the doctor.