selection statement condition compound statement...

29
Visual C# - Penn P. Wu, PhD. 100 Lecture #4 C# Selection Statements Introduction A conditional statement (also known as selection statement) is used to decide whether to do something at a special point, or to decide between two courses of action. A conditional statement chooses among alternative actions in a C# program. In other words, a conditional statement causes the program control to be transferred to a specific flow based upon whether a certain condition is true or not. There are two types of conditional statement; the if statement and the switch statement. The if statement performs (selects) an action based on a tested condition. A condition is an expression with a Boolean value (TRUE or FALSE) that is used for decision making. The switch statement is a control statement that selects a switch section to execute from a list of candidates. The if statement An if statement typically evaluates a Boolean expression, such as (x > 3), and then determine which statement to run based on the value of a Boolean expression. In C#, an if conditional statement begins with the keyword if, followed by a condition in parentheses. The statement(s) of execution are grouped together between curly brackets { }. Such a grouping is called a compound statement or simply a block. The following is the syntax. if ( condition ) { //execution; } The following is a simple C# code contains an if statement that evaluates whether an expression (5 > 3) is true and displays the text “Correct!” when the result is true. using System; using System.Windows.Forms; public class Example { public static void Main() { if (5 > 3) { MessageBox.Show("Correct!"); } } } In the following example. The variable n is an int type and is assigned 14 as its value. The expression (n%2 ==0) will test whether the remainder of n “modulus” 2 equals to 0. When the expression is tested to be true, it displays “14 is an even number”. using System; using System.Windows.Forms; public class Example { public static void Main() { int n = 14; if (n%2 == 0) { MessageBox.Show(n + " is an even number."); } } }

Upload: others

Post on 22-Mar-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 100

Lecture #4 C# Selection Statements

Introduction

A conditional statement (also known as selection statement) is used to decide whether to do

something at a special point, or to decide between two courses of action. A conditional

statement chooses among alternative actions in a C# program. In other words, a conditional

statement causes the program control to be transferred to a specific flow based upon whether a

certain condition is true or not. There are two types of conditional statement; the if statement and the switch statement. The if statement performs (selects) an action based on a tested

condition. A condition is an expression with a Boolean value (TRUE or FALSE) that is used

for decision making. The switch statement is a control statement that selects a switch section to

execute from a list of candidates.

The if statement An if statement typically evaluates a Boolean expression, such as (x > 3), and then determine

which statement to run based on the value of a Boolean expression. In C#, an if conditional

statement begins with the keyword if, followed by a condition in parentheses. The statement(s)

of execution are grouped together between curly brackets { }. Such a grouping is called a

compound statement or simply a block. The following is the syntax.

if ( condition )

{

//execution;

}

The following is a simple C# code contains an if statement that evaluates whether an

expression (5 > 3) is true and displays the text “Correct!” when the result is true.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

if (5 > 3) { MessageBox.Show("Correct!"); }

}

}

In the following example. The variable n is an int type and is assigned 14 as its value. The

expression (n%2 ==0) will test whether the remainder of n “modulus” 2 equals to 0. When the

expression is tested to be true, it displays “14 is an even number”.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int n = 14;

if (n%2 == 0)

{

MessageBox.Show(n + " is an even number.");

}

}

}

Page 2: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 101

The following code decides whether a student has passed an exam with a pass score of 60.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

string str = InputBox.Show("Enter your score:");

double grade = Convert.ToDouble(str);

// test if the value of user entry >= 60

if (grade >=60)

{

MessageBox.Show("Pass!");

}

}

}

A C# code can have as many if statement as it is deemed necessary. The following example

has seven individual if statements.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DateTime t = DateTime.Now;

int w = (int) t.DayOfWeek;

if (w == 0) { MessageBox.Show("Sunday"); }

if (w == 1) { MessageBox.Show("Monday"); }

if (w == 2) { MessageBox.Show("Tuesday"); }

if (w == 3) { MessageBox.Show("Wednesday"); }

if (w == 4) { MessageBox.Show("Thursday"); }

if (w == 5) { MessageBox.Show("Friday"); }

if (w == 6) { MessageBox.Show("Saturday"); }

}

}

The following line creates an instance named t of the DateTime structure of the .NET

Framework. The Now property gets the current date and time values.

DateTime t = DateTime.Now;

In the following, the DayOfWeek property gets the day of the week represented by the

DateTime instance (t). The value is then assigned to an int type of variable named w. The

value of t.DayOfWeek is a constant in the range of 0 to 6 that indicates the day of the week.

int w = (int) t.DayOfWeek;

Other useful properties of the DateTime structure are:

• Month: Gets the month component of the date represented by this instance.

• Hour: Gets the hour component of the date represented by this instance.

• Minute: Gets the minute component of the date represented by this instance.

Page 3: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 102

• Second: Gets the seconds component of the date represented by this instance.

By the same token, the following example checks whether the current value of retrieved from

the hour property is less than 12. The hour property is an int type; therefore, the instructor

chooses to create another variable h of int type to keep the retrieved value. The expression of the first if statement is (h >= 12) which can eliminate the AM/PM issue. Finally, the

MessageBox.Show() method displays the string.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int h = DateTime.Now.Hour;

if (h >= 12) { h = h - 12; } // eliminate the AM/PM issue

string str = "";

if (h ==0) { str = "twelve"; }

if (h ==1) { str = "one"; }

if (h ==2) { str = "two"; }

if (h ==3) { str = "three"; }

if (h ==4) { str = "four"; }

if (h ==5) { str = "five"; }

if (h ==6) { str = "six"; }

if (h ==7) { str = "seven"; }

if (h ==8) { str = "eight"; }

if (h ==9) { str = "nine"; }

if (h ==10) { str = "ten"; }

if (h ==11) { str = "eleven"; }

MessageBox.Show("It is " + str + " O'clock now!");

}

}

The following code eliminates the AM/PM issue. When h is 13, h = h – 12 will change h

to 1.

if (h >= 12) { h = h - 12; }

Another way, which is simpler, is to use the modulus (%) operation:

h = h % 12;

The above examples all have a logical problem . They all specify what to execute when the

expression is tested to be true, but they do not specify what to do when the expression is tested

to be false. It will take an if..else statement to resolve such logical issues.

The if .. else

statement

The if statement performs an indicated action (or sequence of actions) only when the condition

is tested to be true; otherwise, the execution is skipped. The if .. else statement performs an

action when a condition is true and performs a different action when the condition is false. The

following illustrates the syntax.

if ( condition )

{

execution1; // do this when condition is TRUE

}

Page 4: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 103

else

{

execution2; // do this when condition is FALSE

}

The following uses an if..else structure to determine the correct value of AM/PM/

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int h = DateTime.Now.Hour;

if (h > 12) { MessageBox.Show("AM"); }

else { MessageBox.Show("PM"); }

}

}

The following creates an anonymous instance of the Random class and uses it to generate a

random number in a range from 0 to 99. The randomly selected integer is then assigned to a

variable n of the int type. The if..else structure will evaluate the expression (n%2 == 0). When

the evaluation is true, n is an even number; otherwise, n is an odd number.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int n = (new Random()).Next(0, 100);

if (n%2 == 0)

{

MessageBox.Show(n + " is an even number.");

}

else

{

MessageBox.Show(n + " is an odd number.");

}

}

}

The following demonstrates how to use an if..else structure to determine which of two given

integers, n1 and n2, is larger. By the way, the instructor purposely places a “seed” number in

the Random(seed) constructor to enhance the randomization effect. The “seed” is a number

used to initialize a pseudorandom number generator. It is defaulted to 0.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int n1 = (new Random(1)).Next(0, 100);

int n2 = (new Random(2)).Next(0, 100);

Page 5: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 104

if (n1 >= n2)

{

MessageBox.Show(n1 + " is larger than " + n2);

}

else

{

MessageBox.Show(n2 + " is larger than " + n1);

}

}

}

The following is the if..else version of one of the previous examples.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

string str = InputBox.Show("Enter your score:");

double grade = Convert.ToDouble(str);

// test if the value of user entry >= 60

if (grade >=60)

{

MessageBox.Show("Pass!");

}

else

{

MessageBox.Show("Fail!");

}

}

}

The following is another example. It retrieves the value of DayOfWeek property.

Interestingly, the values of DayOfWeek are defined as enumerated values; therefore, it is

necessary to cast their data type to int. By the way, 0 indicates Sunday and 1 indicates Monday

while 6 is Saturday. The instructor chooses to use the hybrid expression (w >= 5 || w ==

0) for weekends. Another way to write an expression for weekends is (w==5 || w==6 ||

w==0).

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DateTime t = DateTime.Now;

int w = (int) t.DayOfWeek; // type casting

if (w >= 5 || or w == 0)

{

MessageBox.Show("Weekend.");

}

else

{

Page 6: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 105

MessageBox.Show("Weekday.");

}

}

}

In previous lectures, students learned to use the Show() method of the MessageBox class to

display the specific text, as shown below.

MessageBox.Show("Hello world!");

The following is an overloaded form of the Show() method, which can display a message box

with specified text, caption, buttons, and icon.

MessageBox.Show(text, caption, button)

where,

• text is the text to display in the message box;

• caption is the text to display in the title bar of the message box; and

• button is one of the MessageBoxButtons values that specifies which buttons to display in

the message box.

The MessageBoxButtons enumeration provides the following constants to specify which

buttons to display on a message box.

Constant Numerical

Value

Meaning

MessageBoxButtons.OK 0

The message box contains an OK

button.

MessageBoxButtons.OKCancel 1

The message box contains OK

and Cancel buttons.

MessageBoxButtons.AbortRetryI

gnore 2

The message box contains Abort, Retry, and Ignore buttons.

MessageBoxButtons.YesNoCancel 3

The message box contains Yes,

No, and Cancel buttons.

MessageBoxButtons.YesNo 4

The message box contains Yes

and No buttons.

MessageBoxButtons.RetryCancel 5

The message box contains Retry

and Cancel buttons.

The following demonstrates how this overload form works.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

MessageBox.Show("Do you like C#?",

"Question 1",

MessageBoxButtons.YesNo);

}

Page 7: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 106

}

The following is the sample output of the above code.

As a matter of face, the Show() method can work with the DialogResult enumeration which

defines the following constants to indicate the returned value of a dialog box.

Constant Numerical

Value

Meaning

DialogResult.None 0 Nothing is returned from the dialog box. This

means that the modal dialog continues

running.

DialogResult.OK 1 The dialog box return value is OK.

DialogResult.Cancel 2 The dialog box return value is Cancel.

DialogResult.Abort 3 The dialog box return value is Abort.

DialogResult.Retry 4 The dialog box return value is Retry.

DialogResult.Ignore 5 The dialog box return value is Ignore.

DialogResult.Yes 6 The dialog box return value is Yes.

DialogResult.No 7 The dialog box return value is No.

The following demonstrates how to use an instance of the DialogResult enumeration (named

“result”) to temporarily store the returned value of the message box. Then, it uses an if..else

structure to determine what to display. When the “No” button is clicked, the returned value is

DialogResult.No. When the “Yes” button is clicked, the returned value is DialogResult.Yes.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DialogResult result = MessageBox.Show("Do you like C#?",

"Question 1",

MessageBoxButtons.YesNo);

if (result == DialogResult.No)

{

MessageBox.Show("Sorry to hear that.");

}

else

{

MessageBox.Show("Good to know that.");

}

Page 8: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 107

}

}

The following is the sample output after the “Yes” button is clicked.

The else if

statement

Sometimes a programmer needs to make a decision based on several conditions. Such demand

can be done by using the else if variant of the if statement. This works by cascading several comparisons. As soon as one of these gives a true result, the following statement or block is

executed, and no further comparisons are performed. In the following example, the if structure

awards grades depending on the exam result.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

string str = InputBox.Show("Enter your score:");

double grade = Convert.ToDouble(str);

if (grade >=90) { MessageBox.Show("A"); }

else if (grade >=80) { MessageBox.Show("B"); }

else if (grade >=70) { MessageBox.Show("C"); }

else if (grade >=60) { MessageBox.Show("D"); }

else { MessageBox.Show("F"); }

}

}

In this example, all comparisons test a single variable called “result.” In other cases, each test

may involve a different variable or some combination of tests. The same pattern can be used

with more or fewer else if's, and the final lone else may be left out. It is up to the programmer

to devise the correct structure for each programming problem.

The following is the if..else..if version of one of the previous examples.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DateTime t = DateTime.Now;

int w=(int) t.DayOfWeek;

if (w == 0) { MessageBox.Show("Sunday"); }

else if (w == 1) { MessageBox.Show("Monday"); }

else if (w == 2) { MessageBox.Show("Tuesday"); }

else if (w == 3) { MessageBox.Show("Wednesday"); }

else if (w == 4) { MessageBox.Show("Thursday"); }

else if (w == 5) { MessageBox.Show("Friday"); }

Page 9: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 108

else if (w == 6) { MessageBox.Show("Saturday"); }

else { MessageBox.Show("No such day"); }

}

}

The following is another example. It uses if and else if statements without the “else” parts.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DialogResult result = MessageBox.Show(

"Are you sure you want to delete it?",

"Confirmation",

MessageBoxButtons.OKCancel);

if (result == DialogResult.OK)

{

MessageBox.Show("You chose to delete the file.");

}

else if (result == DialogResult.Cancel)

{

MessageBox.Show("Deletion cancelled.");

}

}

}

The switch..case

Statement

Often time, the “switch” statement is used as an alternative to an if..else structure when a single expression can produce three or more outcomes. The following expression, for example,

can produce 5 possible outcomes: 0, 1, 2, 3, and 4. An if..else statement can only handle two

outcomes: true or false.

n % 5

The switch structure is a control statement that selects a switch section to execute from a list of

candidates. A switch structure includes one or more “sections”. Each switch section consists

of a case “label” followed by one or more statements. Each case in a switch statement has one label (e.g. label1 and label2 as shown below) and statements and must end with a break

statement. The following illustrates the syntax.

switch (expression)

{

case label1: statements; break;

case label1: statements; break;

.............

.............

case labeln: statements; break;

default: statements; break;

}

The following figure illustrates the flow.

Page 10: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 109

It is necessary to note that values of labels in a switch statement are treated as constants, these

values cannot be changed throughout the entire program life span. If a value passed to the

switch statement matches any case label constant, the specified switch section is executed;

otherwise, the default section is executed.

In the following example, the expression is defined by an int type of variable named “n”. The

value of “n” is assigned randomly from five possible values: 0, 1, 2, 3, and 4 (because of the

Next(min, max+1) method). Each time when the program runs, the value of n will be used to

match one of the six “candidate” cases (five cases are labeled with an integer and the default

case). In general, switch..case is a selection structure that chooses a single case to execute

from a list of “candidate” cases based on a pattern match with the match expression. When

n=3 or n=4, the default case is executed.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int n = (new Random()).Next(0, 5);

string str = "";

switch (n)

{

case 0: str = "Zero"; break;

case 1: str = "One"; break;

case 2: str = "Two"; break;

default: str = "Exception"; break;

}

MessageBox.Show(str);

}

}

switch

expression

case 1

case 2

case n

default

statement 1

break;

statement 2

break;

statement n

break;

statement

break;

yes

yes

yes

no

no

no

Page 11: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 110

It is necessary to note that the instructor placed a special case is the default case in the above

code because “case 3” and “case 4” are not defined inside the switch statement. When n=3 or

n=4, there will be no matching cases in the switch statement, so they are exceptions. In a

switch cases, exceptions are handled by the default case. Interestingly, occasionally, the

default case is not necessary. For example, in the following code, the Next() method can only

produce three possible outcomes: 0, 1, and 2.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int n = (new Random()).Next(0, 5);

string str = "";

switch (n)

{

case 0: str = "Zero"; break;

case 1: str = "One"; break;

case 2: str = "Two"; break;

}

MessageBox.Show(str);

}

}

Typically, when all the possible cases are defined in a switch statement, the default case

becomes an optional case. The following example does not have the “default” case, simply

because the DayOfWeek property can only return value in the range of 0 to 6; therefore, there

is no need to have the “default” case.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DateTime t = DateTime.Now;

int w = (int) t.DayOfWeek;

String str = "";

switch (w)

{

case 0: str = "Sunday"; break;

case 1: str = "Monday"; break;

case 2: str = "Tuesday"; break;

case 3: str = "Wednesday"; break;

case 4: str = "Thursday"; break;

case 5: str = "Friday"; break;

case 6: str = "Saturday"; break;

}

Page 12: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 111

MessageBox.Show(str);

}

}

The following is a sample output.

In C#, labels of a switch statement can be a value of integer, floating-point, character, and

string. However, arrays or objects cannot be used here unless they are dereferenced to a simple

type. The following example shows a simple switch structure that has six switch sections: case

‘A’, ‘B’, ‘C’, ‘D’, ‘F’, and default.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

Char grade = 'C';

string meaning = "";

switch (grade)

{

case 'A':

meaning = "outstanding distinction and excellence";

break;

case 'B':

meaning = "solid accomplishment and goodness";

break;

case 'C':

meaning = "adequate but ordinary";

break;

case 'D':

meaning = "below standard and just passabl";

break;

case 'F':

meaning = "clear failure";

break;

default:

meaning = "Not a defined grade level";

break;

}

MessageBox.Show(meaning);

}

}

The cases can be defined using the String type. In the following example, the variable n of int

type will be assigned a randomly selected integer (from the range 0 to 4). The expression,

Page 13: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 112

names[n], will then retrieve a string literal from the “names” array (e.g. “Nancy”) to match

with the defined case. When “John” is picked, the default case is executed.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

String[] names = new String[] { "Arcy",

"Nancy",

"Lucy",

"Darcy",

"John" };

int n = (new Random()).Next(0, 5);

String str = "";

switch (names[n])

{

case "Arcy": str = "Apple"; break;

case "Nancy": str = "Banana"; break;

case "Lucy": str = "Cherry"; break;

case "Darcy": str = "Date"; break;

default: str = "Blackberry"; break;

}

MessageBox.Show(names[n] + " likes " + str);

}

}

In the following example, the case is defined using DialogResult remuneration.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DialogResult result = MessageBox.Show("What do you want?",

"Sample",

MessageBoxButtons.YesNoCancel);

String str = "";

switch (result)

{

case DialogResult.Yes:

str = "You click Yes."; break;

case DialogResult.No:

str = "You click No."; break;

case DialogResult.Cancel:

str = "You click Cancel."; break;

Page 14: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 113

}

MessageBox.Show(str);

}

}

In C#, statements in a section can be empty, which simply passes control to the next case. In

the following example, only when the weekday is Tuesday will a user see an output.

using System;

using System.Windows.Forms;

public class Example

{

static void Main(string[] args)

{

DateTime t = DateTime.Now;

int w=(int) t.DayOfWeek;

switch (w)

{

case 0:

case 1:

case 2: MessageBox.Show("You just won the prize!"); break;

case 3:

case 4:

case 5:

case 6:

default: break;

}

}

}

In the following example, the instructor purposely makes two empty cases: ‘a’ and ‘b’;

therefore, the code becomes “case insensitive”. When either “a” or “A” is given, “Apple” is

the output.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

Char c = InputBox.Show("Enter a letter [A/B]:")

String str = "";

switch (c)

{

case 'a' :

case 'A' : str = "Apple"; break;

case 'b' :

case 'B' : str = "Banana"; break;

}

MessageBox.Show(str);

}

}

Page 15: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 114

The switch structure evaluates the expression and then looks for its values among the cases. If

a matching case is found, then the statements in that section will be executed. It is important to

understand how the switch structure is executed in order to avoid mistakes. Execution of the

statements in the selected switch section begins with the first statement and continue till a

break statement is reached. The break statement forces the switch statement to stop. Without a break statement, C# might continue to execute statements in the next case and the case after

until the first time it reaches a break statement, or simply returns a “CS0162: Unreachable

code detected” error message. In the following example, the instructor purposely not to write a

break statement at the end of each case section.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

String str = "";

int n = 1;

switch (n)

{

case 0: str = "Apple";

case 1: str = "Orange";

case 2: str = "Grape";

default: str = "Banana"; break;

}

MessageBox.Show(str);

}

}

The output is:

Microsoft (R) Visual C# Compiler version 4.0.30319.18408

for Microsoft (R) .NET Framework 4.5

Copyright (C) Microsoft Corporation. All rights reserved.

1.cs(13,4): error CS0163: Control cannot fall through from one

case label ('case 1:') to another

1.cs(12,12): warning CS0162: Unreachable code detected

1.cs(14,12): warning CS0162: Unreachable code detected

In a switch structure, the condition is evaluated only once, and the result is compared to each

case statement. In an else if statement, the condition is evaluated again. When the condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster. The

advantage of using switch statement is to simplify the complexity of if..else’s. Compare the

following with one of the above examples to see the difference.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

Page 16: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 115

DateTime t = DateTime.Now;

int w = (int) t.DayOfWeek;

String str = "";

if (w == 0) { str = "Sunday"; }

else if (w == 1) { str = "Monday"; }

else if (w == 2) { str = "Tuesday"; }

else if (w == 3) { str = "Wednesday"; }

else if (w == 4) { str = "Thursday"; }

else if (w == 5) { str = "Friday"; }

else { str = "Saturday"; }

MessageBox.Show(str);

}

}

A switch..case is used to test variable equality for a list of values, where each value is a case.

When the variable is equal to one of the cases, the statements following the case are executed. A break statement ends the switch case. The optional default case is for the situation when the

variable does not equal any of the cases.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

Char choice = 'M';

String str = "";

switch(choice)

{

case 'Y' :

str = "Yes";

break;

case 'M' :

str = "Maybe";

break;

case 'N' :

str = "No";

break;

default:

str = "Invalid response"; break;

}

MessageBox.Show(str);

}

}

Practical

Examples

According to the Astronomy textbook, an average year has 365.24219 days, which means

there is an extra 0.25 (actually 0.24219) day in an average year. Therefore, there is a need to

add one extra day every four year to offset the extra 0.25 day (0.25 × 4 = 1).

In the Gregorian Calendar, there is a leap year every four year whose number is perfectly

divisible by four - except for years which are both divisible by 100 and not divisible by 400. The second part of the rule effects century years. For example; the century years 1600 and

Page 17: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 116

2000 are leap years, but the century years 1700, 1800, and 1900 are not. This means that three

times out of every four hundred years there are eight years between leap years.

The following is a sample code that will determine if a given year is leap year. It is based on

the canonical definition of the term “leap year”, so the logic applies to all programming languages.

bool isLeap = false;

if (y%4 == 0 && (y%100 != 0 || y%400 == 0))

{

isLeap = true;

}

The above code takes a year value such as 1968 and performs the following modulus

operations.

y % 4

y % 100

y % 400

The following is a complete sample code that will display the number of days available in

February of the current year. The variable y obtains its value from the “now()” method of the

“datetime” class. The value is then passed to the “isLeapYear()” function to determine whether

the current year is a leap year. The “if” structure will decide the correct number of days

available for February.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int y = 2000;

bool isLeap = false;

int lastDay = 28;

if (y%4 == 0 && (y%100 != 0 || y%400 == 0))

{

isLeap = true;

lastDay = 29;

}

MessageBox.Show("Leap year: " + isLeap +

"\nLast day of Feb: " + lastDay);

}

}

The following is a sample output.

Page 18: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 117

Interesting, the annual calendar cycle of the Gregorian Calendar is pretty predictable, and the

days of the week repeat every few years. This means that all of the days of the week match up,

including possible leap days. Most holidays will match up, too.

According to the American Museum of Natural History in New York, the only simple pattern is that it repeats every 28 years. It repeats every 28 years as 28 is the lowest common multiple

of the 4-year cycle of leap years and the 7 weekdays. The 28-year calendar cycle works well as

long as the 4-year cycle of leap years is maintained. This phenomenon gives us many years

until 2100 to recycle yearly calendars.

By checking the calendar from year 2000 to 2027, the instructor was able to obtain the

weekday of January 1 for 28 years.

2000 2001 2002 2003 2004

The following table lists the weekdays. The values of weekday used in the following table are

0, 1, 2, 3, 4, 5, and 6 with 0 being Sunday, 1 being Monday, and 6 being Saturday.

Year Weekday Year Weekday Year Weekday Year Weekday

2000 6 2007 1 2014 3 2021 5

2001 1 2008 2 2015 4 2022 6

2002 2 2009 4 2016 5 2023 0

2003 3 2010 5 2017 0 2024 1

2004 4 2011 6 2018 1 2025 3

2005 6 2012 0 2019 2 2026 4

2006 0 2013 2 2020 3 2027 5

Since the circle takes 28 years to complete, the following table lists the results of y%28 (y

represents a given year and “%” is the “modulus” operator).

Year y%28 Year y%28 Year y%28 Year y%28

2000 12 2007 19 2014 26 2021 5

2001 13 2008 20 2015 27 2022 6

2002 14 2009 21 2016 0 2023 7

2003 15 2010 22 2017 1 2024 8

2004 16 2011 23 2018 2 2025 9

2005 17 2012 24 2019 3 2026 10

2006 18 2013 25 2020 4 2027 11

The following table lists the weekdays and their associated y%28 results.

Weekday y%28 Weekday y%28 Weekday y%28 Weekday y%28 6 12 1 19 3 26 5 5

1 13 2 20 4 27 6 6

2 14 4 21 5 0 0 7

3 15 5 22 0 1 1 8

4 16 6 23 1 2 3 9

6 17 0 24 2 3 4 10

0 18 2 25 3 4 5 11

Page 19: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 118

The following uses if statements to determine the weekday of January 1 of a given year. For

example, when the value of y is 2020, the value of y%28 is 4, the following if statements will

set the value of firstDay to 3, which means the January 1, 2020 is a Wednesday.

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

int y =2020;

//determine the weekday of Jan 1

int firstDay = 0; //0-Sun, 1-Mon, 6-Sat

if (y%28 == 12 || y%28 == 17 || y%28 == 23 || y%28 == 6)

{ firstDay = 6; }

if (y%28 == 22 || y%28 == 0 || y%28 == 5 || y%28 == 11)

{ firstDay = 5; }

if (y%28 == 10 || y%28 == 16 || y%28 == 21 || y%28 == 27)

{ firstDay = 4; }

if (y%28 == 15 || y%28 == 26 || y%28 == 4 || y%28 == 9)

{ firstDay = 3; }

if (y%28 == 14 || y%28 == 20 || y%28 == 25 || y%28 == 3)

{ firstDay = 2; }

if (y%28 == 13 || y%28 == 19 || y%28 == 2 || y%28 == 8)

{ firstDay = 1; }

if (y%28 == 18 || y%28 == 24 || y%28 == 1 || y%28 == 7)

{ firstDay = 0; }

MessageBox.Show(firstDay + "");

}

}

The above code will be used in a later lecture to create Julian calendars.

Review

Questions

1. Given the following statements, the output is __.

int x = 9;

if (x != 7) { MessageBox.Show("True"); }

else { MessageBox.Show("False"); }

A. 1

B. 0

C. True

D. False

2. Given the following statements, the output is __.

string ans = "1";

ans = "0";

if ((6<=4) || (6<=8)) { ans = "False"; }

Page 20: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 119

MessageBox.Show(ans);

A. 1

B. 0

C. True

D. False

3. The result of the following calculation is __.

int i=6;

if (i>=4) {

if (i==5) { MessageBox.Show(i+"");}

else { MessageBox.Show((i--) + "");}

}

else { MessageBox.Show((i++) +""); }

A. 4

B. 5 C. 6

D. 3

4. The result of the following calculation is __.

int i=3;

if (i>=4) {

if (i==5) { MessageBox.Show(i + "");}

else { MessageBox.Show((i--) + "");}

}

else { MessageBox.Show((++i) + ""); }

A. 4

B. 5

C. 6

D. 3

5. Given the following statements, the output is __.

String str = "";

int n = 9;

if (n > 11) { str = "Apple"; }

else if (n > 7) { str = "Banana"; }

else if (n > 5) { str = "Cherry"; }

else { str = "Dragon fruit"; }

MessageBox.Show(str);

A. Apple

B. Banana

C. Cherry D. Dragon fruit

6. Given the following statements, the output is __.

String str = "";

int i = 3;

switch (i%2)

{

case 0: str += "zero"; break;

case 1: str += "one"; break;

case 2: str += "two"; break;

case 3: str += "three"; break;

Page 21: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 120

}

MessageBox.Show(str);

A. zero

B. two

C. one

D. three

7. Given the following statements, the output is __.

String str = "";

int i = 3;

switch (i%2)

{

case 3: str = "three"; break;

case 1: str = "one"; break;

case 2: str = "two"; break;

case 0: str = "zero"; break;

}

MessageBox.Show(str);

A. zero

B. two C. one

D. three

8. Given the following statements, the output is __.

String str = "";

Char c = 'b';

switch (c)

{

case 'a':

case 'A': str ="Apple"; break;

case 'b':

case 'c': str = "Cherry"; break;

case 'B': str = "Banana"; break;

default: str = "Orange"; break;

}

MessageBox.Show(str);

A. Apple

B. Banana

C. Cherry

D. Orange

9. Given the following statements, the output is __.

double discount;

char code = 'C' ;

switch ( code )

{

case 'A': discount = 0.0; break;

case 'B': discount = 0.1; break;

case 'C': discount = 0.2; break;

default: discount = 0.3; break;

}

MessageBox.Show(discount + "");

Page 22: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 121

A. 0.0

B. 0.1

C. 0.2

D. 0.3

10. Given the following statements, the output is __.

double discount;

char code = 'b' ;

switch ( code )

{

case 'A': discount = 0.0; break;

case 'B': discount = 0.1; break;

case 'C': discount = 0.2; break;

default: discount = 0.3; break;

}

MessageBox.Show(discount + "");

A. 0.0

B. 0.1 C. 0.2

D. 0.3

Page 23: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 122

Lab #4 C# Selection Statements

Learning Activity #1:

1. Create a new directory called C:\CIS218 if it does not exist.

2. Launch the Development Command Prompt (not the Windows Command Prompt). (See Lab #1 for details)

3. In the prompt, type cd c:\cis218 and press [Enter] to change to the C:\CIS218 directory.

4. In the prompt, type notepad lab4_1.cs and press [Enter] to use Notepad to create a new source file called

lab4_1.cs with the following contents:

using System;

using System.Windows.Forms;

public class lab4_1

{

public static void Main()

{

int h = DateTime.Now.Hour;

h = h % 12; // turn 24 hour format to 12 hour format

String str = "Method 1:\nIt is ";

if (h==0) { str += "Twelve"; }

if (h==1) { str += "One"; }

if (h==2) { str += "Two"; }

if (h==3) { str += "Three"; }

if (h==4) { str += "Four"; }

if (h==5) { str += "Five"; }

if (h==6) { str += "Six"; }

if (h==7) { str += "Seven"; }

if (h==8) { str += "Eight"; }

if (h==9) { str += "Nine"; }

if (h==10) { str += "Ten"; }

if (h==11) { str += "Eleven"; }

str += " o'clock\n\n";

str += "Method 2:\nIt is ";

if (h==1) { str += "One"; }

else if (h==2) { str += "Two"; }

else if (h==3) { str += "Three"; }

else if (h==4) { str += "Four"; }

else if (h==5) { str += "Five"; }

else if (h==6) { str += "Six"; }

else if (h==7) { str += "Seven"; }

else if (h==8) { str += "Eight"; }

else if (h==9) { str += "Nine"; }

else if (h==10) { str += "Ten"; }

else if (h==11) { str += "Eleven"; }

else { str += "Twelve"; }

str += " o'clock\n";

Page 24: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 123

MessageBox.Show(str);

}

}

5. In the prompt, type csc /t:winexe lab4_1.cs and press [Enter] to compile the source code. The compiler

creates a new file called lab4_1.exe.

6. Type lab4_1.exe and press [Enter] to test the program. A sample output looks:

7. Download the “assignment template” and rename it to lab4.doc if necessary. Capture a screen shot similar to the

above and paste it to the Word document named lab4.doc (or .docx).

Learning Activity #2:

1. Under the C:\cis218 directory, use Notepad to create a new source file called lab4_2.cs with the following contents:

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

DateTime t = DateTime.Now;

int w = (int) t.DayOfWeek;

String str = "switch..case:\n";

switch(w)

{

case 0: str += "Sunday"; break;

case 1: str += "Monday"; break;

case 2: str += "Tuesday"; break;

case 3: str += "Wednesday"; break;

case 4: str += "Thursday"; break;

case 5: str += "Friday"; break;

case 6: str += "Saturday"; break;

}

str += "\n\nif..else..if..else:\n";

if (w == 0) { str += "Sunday"; }

else if (w == 1) { str += "Monday"; }

else if (w == 2) { str += "Tuesday"; }

else if (w == 3) { str += "Wednesday"; }

else if (w == 4) { str += "Thursday"; }

else if (w == 5) { str += "Friday"; }

else { str += "Saturday"; }

str += "\n\nIs it correct?";

Page 25: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 124

DialogResult result = MessageBox.Show(str,

"Day of week",

MessageBoxButtons.YesNo);

if (result == DialogResult.No)

{

MessageBox.Show("Sorry to hear that.");

}

else

{

MessageBox.Show("Good to know that.");

}

}

}

2. Compile and test the program. The output looks:

and

3. Capture a screen shot similar to the above and paste it to the Word document named lab4.doc (or .docx).

Learning Activity #3:

1. Make sure the InputBox.cs file is the C:\cis218 directory.

2. Under the C:\cis218 directory, use Notepad to create a new source file called lab4_3.cs with the following

contents:

using System;

using System.Windows.Forms;

public class lab4_3

{

public static void Main()

{

String input = InputBox.Show("What year were you born [e.g. 1992]:");

int year = Convert.ToInt32(input);

year = year % 12;

//if..else if..else

String str = input + " is a(n) ";

if (year == 0) { str += "monkey"; }

else if (year == 1) { str += "rooster"; }

else if (year == 2) { str += "dog"; }

else if (year == 3) { str += "pig"; }

else if (year == 4) { str += "rat"; }

else if (year == 5) { str += "ox"; }

else if (year == 6) { str += "tiger"; }

else if (year == 7) { str += "rabbit"; }

else if (year == 8) { str += "dragon"; }

else if (year == 9) { str += "snake"; }

Page 26: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 125

else if (year == 10) { str += "horse"; }

else { str += "goat"; }

str += " year in Chinese zodiac.\n\n";

// switch..case

String zodiac = "It is a(n) ";

switch (year)

{

case 0: zodiac += "monkey"; break;

case 1: zodiac += "rooster"; break;

case 2: zodiac += "dog"; break;

case 3: zodiac += "pig"; break;

case 4: zodiac += "rat"; break;

case 5: zodiac += "ox"; break;

case 6: zodiac += "tiger"; break;

case 7: zodiac += "rabbit"; break;

case 8: zodiac += "dragon"; break;

case 9: zodiac += "snake"; break;

case 10: zodiac += "horse"; break;

case 11: zodiac += "goat"; break;

}

zodiac += " year!";

MessageBox.Show(str + zodiac);

}

}

3. Type csc /t:winexe lab4_3.cs InputBox.cs and press [Enter] to compile.

4. Test the program. A sample output looks:

and

5. Capture a screen shot similar to the above and paste it to the Word document named lab4.doc (or .docx).

Learning Activity #4:

1. Under the C:\cis218 directory, use Notepad to create a new source file called lab4_4.cs with the following

contents:

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

String bd = InputBox.Show("Enter your blood type [A/B/O/AB]:");

bd = bd.ToUpper();

string traits = "Positive: ";

Page 27: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 126

switch (bd)

{

case "A":

traits += "Earnest, Neat";

break;

case "B":

traits += "Passionate, Creative";

break;

case "O":

traits += "Easygoing, Leadership Ability";

break;

case "AB":

traits += "Talented, Composed";

break;

default:

traits = "Error: No such blood type....";

break;

}

traits += "\nNegative: ";

if (bd == "A") { traits += "Stubborn, Anxious"; }

else if (bd == "B") { traits += "Selfish, Uncooperative"; }

else if (bd == "O") { traits += "Insensitive, Unpunctual"; }

else if (bd == "AB") { traits += "Eccentric, Two-faced"; }

else { traits += "A, B, O, or AB only..."; }

traits += "\nDo you Agree?";

DialogResult result = MessageBox.Show(traits,

"Traits",

MessageBoxButtons.YesNo);

switch (result)

{

case DialogResult.No:

MessageBox.Show("You do not agree."); break;

case DialogResult.Yes:

MessageBox.Show("Great! You agree."); break;

}

}

}

2. Compile and test the program. A sample output looks:

and

3. Capture a screen shot similar to the above and paste it to the Word document named lab4.doc (or .docx).

Learning Activity #5:

Page 28: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 127

1. Under the C:\cis218 directory, use Notepad to create a new source file called lab4_5.cs with the following

contents:

using System;

using System.Windows.Forms;

public class Example

{

public static void Main()

{

String input = InputBox.Show("Enter the year:");

int y = Convert.ToInt32(input);

bool isLeap = false;

int lastDay = 0;

int totalNumberOfDay = 0;

if (y%4 == 0 && (y%100 != 0 || y%400 == 0))

{

isLeap = true;

}

switch (isLeap)

{

case true:

lastDay = 29;

totalNumberOfDay = 366;

break;

case false:

lastDay = 28;

totalNumberOfDay = 365;

break;

}

String result = "Year: " + input + "\n";

result += "Leap year: " + isLeap + "\n";

result += "Last day of Feb: " + lastDay + "\n";

result += "Total number of days: " + totalNumberOfDay + "\n";

MessageBox.Show(result);

}

}

2. Type csc /t:winexe lab4_5.cs InputBox.cs and press [Enter] to compile.

3. Test the program. A sample output looks:

and

4. Capture a screen shot similar to the above and paste it to the Word document named lab4.doc (or .docx).

Submittal

1. Complete all the 5 learning activities.

Page 29: selection statement condition compound statement blockstudents.cypresscollege.edu/cis218/lc04.pdfVisual C# - Penn P. Wu, PhD. 102 • Second: Gets the seconds component of the date

Visual C# - Penn P. Wu, PhD. 128

2. Create a .zip file named lab4.zip containing ONLY the following self-executable files.

• Lab4_1.exe

• Lab4_2.exe

• Lab4_3.exe

• Lab4_4.exe

• Lab4_5.exe

• Lab4.doc (or .docx) [You may be given zero point if this Word document is missing]

3. Log in to course site and enter the course site.

4. Upload the zipped file as response to question 11.

Programming Exercise:

1. Use Notepad to create a new file named ex04.cs with the following heading lines (be sure to replace

YourFullNameHere with the correct one):

//File Name: ex04.cs

//Programmer: YourFullNameHere

2. Under the above two heading lines, write C# codes to ask the user to enter her/his GPA using the “InputBox.cs”

file. Then, use an if..else if..else structure to decide the academic excellence level using the following criteria

(known as Latin Honor). Finally, display the output in a message box. If the GPA is lower than 3.4, display “No

honor”.

Level GPA Gum Laude > 3.4

Magna Cum Laude > 3.6

Summa Cum Laud > 3.8

3. The following are sample outputs.

4. Download the “programming exercise template”, and rename it to ex04.doc. Capture a screen shot similar to the

above figure and then paste it to the Word document named “ex04.doc” (or .docx).

5. Compress the source code (ex04.cs), the executable (ex04.exe), and the Word document (ex04.doc or .docx) to

a .zip file named “ex04.zip”. You may be given zero point if any of the required file is missing.

Grading Criteria:

• You must be the sole author of the codes.

• You must meet all the requirements in order to earn credits.

• No partial credit is given.