Practicing if and switch
May 22, 2024 (01:30:58 PM)
This lab serves multiple goals:
- To reinforce your understanding of
ifstatements, - To help you practice
switchstatements, - To help you understand the instances in which
switchorifshould be used, - (Optional) to help you understand the conditional operator, and
- (Optional) to introduce you to the
ToUppermethod.
Mastering the switch
statement
Consider the following code:
// We ask the user to enter the day of the week:
Console.WriteLine("Please enter the day of the week.");
// Note that anything that is not spelled exactly as
// in the switch statement will be treated as the
// default case.
// We read from the user:
string string_day = Console.ReadLine();
// Variable where the result of our computation will be stored:
int num_day;
// Switch statement to map textual description of the day
// (e.g., "Monday", "Tuesday", etc.) to a number
// relative to chronological order (e.g., 1, 2, etc.)
switch (string_day)
{
case ("Monday"):
num_day = 1;
break;
case ("Tuesday"):
num_day = 2;
break;
case ("Wednesday"):
num_day = 3;
break;
case ("Thursday"):
num_day = 4;
break;
case ("Friday"):
num_day = 5;
break;
case ("Saturday"):
num_day = 6;
break;
case ("Sunday"):
num_day = 7;
break;
default:
num_day = -1; // This is an error code.
break;
}
// We display the number corresponding to the day entered:
Console.WriteLine("The number corresponding to " + string_day + " is " + num_day + ".");You can download it as a solution
(that also contains the solution to the problems asked below. Make sure
you open day_of_the_week and not
day_of_the_week_solution first).
Now, do the following:
- Test the program with various values and make sure it behaves as expected.
- Comment out the
default:case along with the two lines below it and compile your program. Why is the compiler complaining? - Restore the code to its original state.
- Change the code so that “monday” would make the value 1 get assigned
to
num_day. - Change the code so that the
days of the week start on Sunday (i.e., “Sunday” causes the value 1
to get assigned to
num_day, “Monday” causes the value 2 to be assigned tonum_day, etc.) - Finally, change the last message to tell the user if the code
encountered an error; use an
ifstatement to display a different message if the user input did not match one of the literals in yourswitchstatement.
Here is an example of execution, where the user input is u͟n͟d͟e͟r͟l͟i͟n͟e͟d͟, and hitting “enter” is represented by ↵:
Please enter the day of the week.
t͟u͟e͟s͟d͟a͟y͟↵
The number corresponding to tuesday is 3.
Here is a second example:
Please enter the day of the week.
M͟O͟N͟D͟A͟Y͟↵
I am sorry, but MONDAY does not seem to be a valid day.
You can find an example solution in this solution or in the archive that you downloaded previously.
Practicing if and switch
This exercise will ask you to write a rather abstract program that
performs simple manipulations on a few variables. The main goal is to
have you practice “transforming” if statements into
switch
statements and switch statements
into if
statements. This will help you memorize their syntax and help you choose
the more convenient one to perform certain tasks.
Create a new project and do the following in Main.
- Declare and initialize the following variables:
- a
stringvariable namedday - an
intvariable namedmyVar - a
charvariable namedinitial, and - a
boolvariable namedflag
- a
- Set and change the value of these variables to make good tests as you progress through this problem.
- You can also display them on the screen to make sure that your statements behave as expected.
From switch to if-else
- Write a
switchstatement that setsflagtotrueif the value ofdayis"Mon","Tue","Wed","Thu"or"Fri", and tofalseotherwise. - Rewrite the previous statement as an
if-elsestatement.
From if-else
to switch
- Write an
if-elsestatement that doubles the value ofmyVarifmyVaris:3,5, or7. - Can you rewrite the previous statement as a
switchstatement? If so, do it. If not, explain why not.
Deciding Between Condition Types
- Write a statement that doubles the value of
myVarand setsinitialto'M'ifdayis equal to"Sat". What is the appropriate kind of statement to do this? - Write a statement that displays “Hello” on the screen if the value
of
initialis'E'or'e', “Bonjour” if the value ofinitialis'F'or'f', and “Guten Tag” if the value ofinitialis'D'or'd'. What is the appropriate kind of statement to do this?
Note that you can solve those problems with either an if statement or a
switch
statement.
Complex Conditions
- Write a statement that doubles the value of
myVarifdayis"Sun", triples the value ofmyVarifdayis not"Sun"butinitialis'a', or setsmyVarto0if neither of the other conditions is satisfied. - Write a statement that sets
myVarto0ifinitialis an upper-case letter or to1otherwise. You will need to understand how to use theIsUppermethod, and the documentation can help you with that.
Note that you can only solve those problems with if statements.
Pushing Further (Optional)
Conditional Operator
A conditional operator can be used to replace if-else
statements in particular cases (i.e., assignment, call, increment,
decrement, and new object expressions). Its structure is:
condition ? first_expression : second_expression;
You can read more about it in the documentation.
Practice using the conditional operator by adding these statements to the program you developed previously:
- Write a statement that sets
myVarto0ifinitialis an upper-case letter, and to1otherwise. You already wrote anifstatement that accomplishes this in the previous exercise, so you just need to rewrite it using the conditional operator. - Write a statement that sets
initialto'B'ifmyVaris greater than 500 and to'S'ifmyVaris less than or equal to 500. - Write a statement that doubles the value of
myVarifdayis"Sat"or"Sun"and adds 1 to the value ofmyVarotherwise.
ToUpper()
Method
C# contains a method called ToUpper()
in the string
class. You can read its
documentation, but the simplest way to understand is probably to see
an example first. The statement
Console.WriteLine("Hello, world!".ToUpper());will display
HELLO, WORLD!
Can you use this method to make your switch statement from the first part
accommodate any combination of uppercase and lowercase letters for the
days of the week? If done properly, your program should then correctly
identify that “MoNdAy”, “MONDAY”, “monday” and “Monday” all match the
same value.