decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++...

31
Visual C++ Programming Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most programming languages provide “control structures” consisting of keywords that form a set of specialized statements to analyze one or more conditions and choose an option to move on the next step of flow. Although a control structure can be as simple as one single line of statement, not a code block, this lecture focuses on the discussion of “decision structure(also known as “selection statements”). A decision structure allows the programmer to write codes with logics to make a decision and change its behavior based on the decision. The decision is made based on the outcome of a logical test. A logical test is typically the evaluation of a Boolean condition with expression that can only yield either true or false as outcome. Visual C++ provide two type of decision structure: if and switch..case structures. The if statement is the simplest structure of a decision structure that tests a Boolean condition while the switch..case provides a structure to conditionally execute a chosen section of code. A decision structure makes decisions based on predefined condition(s); therefore, they are also known as “conditional statements.” Visual C++ inherits the convention from standard C++ to support jump statementsto unconditionally transfer program control within a function. There are four jump statements: goto, break, continue, and return. These jump statementscause the control of the program to jump from statement to other statement. In this lecture, students will explore how gotoand breakkeywords work in a program to jump off the program control. Basically, every switch..case structure must contain sufficient amount of breakkeywords, while the gotokeyword can appear in anywhere of the program. A later lecture will discuss continueand return” keywords. The generic if statement In Visual C++, a generic if statement begins with the keyword if, followed by a condition (a Boolean expression) enclosed by a pair of parentheses. The statement(s) of execution are grouped together inside a pair of curly brackets { }, although the curly brackets can be optional. Such a grouping is called a compound statement or simply a block. The following illustrates the syntax, where condition is a Boolean expression that yields either true or false as outcome while statements are whatever to be executed when the condition is tested to be true. if (condition) { statements; } In the following code, the randomly number generator will randomly create an integer (e.g. 17, 458, etc.), the number will be stored in a variable named n. Inside the if statement, there is a Boolean expression: (n % 2 == 0). The Boolean expression tests whether n is an even number because n must be a multiple of 2 if the remainder of n divided by 2 is 0. When n is an even number, the message box displays a string similar to 458924 It is an even number. By the way, the dashed-line encloses the if structure. #using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; int main()

Transcript of decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++...

Page 1: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 130

Lecture #5 Decision Structure

Control

Statements

Most programming languages provide “control structures” consisting of keywords that form a

set of specialized statements to analyze one or more conditions and choose an option to move

on the next step of flow. Although a control structure can be as simple as one single line of

statement, not a code block, this lecture focuses on the discussion of “decision structure”

(also known as “selection statements”).

A decision structure allows the programmer to write codes with logics to make a decision and

change its behavior based on the decision. The decision is made based on the outcome of a

logical test. A logical test is typically the evaluation of a Boolean condition with expression

that can only yield either true or false as outcome.

Visual C++ provide two type of decision structure: if and switch..case structures. The if

statement is the simplest structure of a decision structure that tests a Boolean condition while

the switch..case provides a structure to conditionally execute a chosen section of code. A

decision structure makes decisions based on predefined condition(s); therefore, they are also

known as “conditional statements.”

Visual C++ inherits the convention from standard C++ to support “jump statements” to

unconditionally transfer program control within a function. There are four “jump statements”:

goto, break, continue, and return. These “jump statements” cause the control of the program to

“jump from statement to other statement”. In this lecture, students will explore how “goto” and

“break” keywords work in a program to jump off the program control. Basically, every

switch..case structure must contain sufficient amount of “break” keywords, while the “goto”

keyword can appear in anywhere of the program. A later lecture will discuss “continue” and

“return” keywords.

The generic if

statement

In Visual C++, a generic if statement begins with the keyword if, followed by a condition (a

Boolean expression) enclosed by a pair of parentheses. The statement(s) of execution are

grouped together inside a pair of curly brackets { }, although the curly brackets can be

optional. Such a grouping is called a compound statement or simply a block. The following

illustrates the syntax, where condition is a Boolean expression that yields either true or false as

outcome while statements are whatever to be executed when the condition is tested to be true.

if (condition)

{

statements;

}

In the following code, the randomly number generator will randomly create an integer (e.g. 17,

458, etc.), the number will be stored in a variable named n. Inside the if statement, there is a

Boolean expression: (n % 2 == 0). The Boolean expression tests whether n is an even number

because n must be a multiple of 2 if the remainder of “n divided by 2 is 0”. When n is an even

number, the message box displays a string similar to “458924 It is an even number”. By the

way, the dashed-line encloses the if structure.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

Page 2: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 131

{

Random^ rn = gcnew Random(); // randomly number generator

int n = rn->Next(); // get a random number

if (n % 2 == 0)

{

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

}

}

The above example has a problem of logic. Its if statement performs an action (or sequence of

actions) only when the condition is tested to be true; otherwise the execution is skipped.

Therefore, it specifies what to execute when n is an even number, yet it does not specify what

to do when n is an odd number. The next section will discuss how a programmer can use the

if .. else statement to make up the missing logic.

The .NET framework provides the Random class which is a pseudo-random number

generator, a device that produces a sequence of numbers that meet certain statistical

requirements for randomness. The following demonstrates how to declare an object (e.g. “rn”)

as an instance of the Random class.

Random rn = gcnew Random;

The Next(min, max-1) method can return a positive integer randomly that is picked within a

specified range (from min to max-1). For example, the following will return a number in the

range of {1, 2, 3, and 4}.

rn->Next(1, 5)

The following is another example. It obtains the current hour value from the computer, and

then displays “Morning” when the hour value is less than 12. However, it does not describe

what to do when the hour value is greater than or equal to 12.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

DateTime dt = DateTime::Now;

int h = dt.Hour; // get the hour value

if (h < 12)

{

MessageBox::Show(h + " is morning.");

}

}

The DateTime structure of the .NET Framework represents an instance in time, typically

expressed as text of a date with a time of the day. The following illustrates how to create an

instance of DateTime in Visual C++, where dt is the identifier of the instance that holds of the

date and time value retrieved from the local computer.

DateTime dt = DateTime::Now;

Page 3: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 132

The Now property of the DateTime object returns the date and time of the current moment

from the computer called the “local time”. The “Now” property can further work with

following useful properties to obtain more specific date and time values.

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

adopts the 24-hour format by default.

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

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

• Day: Gets the day of the month represented by this instance.

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

• Year: Gets the year component of the date represented by this instance.

• DayOfYear: Gets the day of the year represented by this instance.

As a matter of fact, the declaration of DateTime struct can be omitted. The following

illustrates how to obtain the hour value without declaring an DateTime object (dt).

With Without DateTime dt = DateTime::Now;

int h = dt.Hour;

int h = DateTime::Now.Hour;

The following is the complete code. However, it does not specify what to do when the

expression, (h<12), is false.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

int h = DateTime::Now.Hour;

if (h < 12)

{

MessageBox::Show("Morning.");

}

}

By the way, another way to ensure that the hour value is always within the range from 0 to 11

is to use the modulus operator (%) to find the integer remainder of h divides by 12.

int h = DateTime::Now.Hour;

h = h % 12;

The following table explains the logic. Basically, the reminder of h%12 is a number from the

set {0, 1, 2, …., 11}.

when h <=12 h % 12 when h >=12 h % 12 12 12 % 12 = 0 12 12 % 12 = 0

1 1 % 12 = 1 13 13 % 12 = 1

2 2 % 12 = 2 14 14 % 12 = 2

3 3 % 12 = 3 15 15 % 12 = 3

4 4 % 12 = 4 16 16 % 12 = 4

5 5 % 12 = 5 17 17 % 12 = 5

6 6 % 12 = 6 18 18 % 12 = 6

7 7 % 12 = 7 19 19 % 12 = 7

Page 4: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 133

8 8 % 12 = 8 20 20 % 12 = 8

9 9 % 12 = 9 21 21 % 12 = 9

10 10 % 12 = 10 22 22 % 12 = 10

11 11 % 12 = 11 23 23 % 12 = 11

12 12 % 12 = 0 24 24 % 12 = 0

The following is a sample code that can determine “AM” and “PM” before evalue the h%12

expression. The original value of the variable “ap” is “AM”. If the value h is greater than 12, it

is “PM”. If the expression (h/24 ==1) is true, then a new cycle of 24 hour starts, so it returns to

“AM”.

int main()

{

String^ ap = "AM";

int h = DateTime::Now.Hour;

if (h/12 > 1) { ap = "PM"; }

if (h/24 == 1) { ap = "AM"; }

h = h % 12;

MessageBox::Show(ap);

}

if..else The if .. else statement performs an action when the condition is true and performs a different

action when the condition is false. The following illustrates the syntax, in which execution1 is

a set of statement(s) to be executed when condition is true while execution2 is a set of

statement(s) to be executed when condition is false.

if (condition)

{

execution1; // condition is TRUE

}

else

{

execution2; // condition is FALSE

}

The following is a sample code that asks the user to enter two integers and then assigns them

to n1 and n2. If the value of n1 is greater than n2, the message is similar to “135 is larger.” If

n1 and n2 are equal, the message is similar to “135 equals to 135”; otherwise, the message it

will say the value of n2 is larger.

#include "InputBox.cpp"

int main()

{

int n1 = Convert::ToInt32(InputBox::Show("Enter an

integer:"));

int n2 = Convert::ToInt32(InputBox::Show("Enter another

integer:"));

String^ str = nullptr;

if (n1 > n2) { str = n1 + " is larger."; }

else if (n1 == n2) { str = n1 + " equals to " + n2; }

else { str = n2 + " is larger."; }

MessageBox::Show(str);

Page 5: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 134

}

In the following sample code, the instructor adds the “else” part to make the logic more

complete: n is an even number when n can be divided by 2; otherwise, n is an odd number.

Consequently, a string will be display when n is an odd or an even number. The “else” part

provide the “otherwise” side of logic.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

Random^ rn = gcnew Random();

int n = rn->Next();

if (n % 2 == 0)

{

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

}

else

{

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

}

}

The following example checks whether the given score is greater than or equal to 60. It can

handle both “true” and “false” results of the condition. It also displays different message

accordingly.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

#include "InputBox.cpp"

int main()

{

String^ str = InputBox::Show("Enter your score: ");

float grade = Convert::ToSingle(str); //type casting

if (grade >=60)

{

MessageBox::Show("Pass!");

}

else

{

MessageBox::Show("Fail!");

}

}

Page 6: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 135

The following adds the “else” part to one of the previous example. Since the (h < 12) condition

can produce either true or false as result, the “else” part provides the statements to be executed

when the condition is false.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

int h = DateTime::Now.Hour;

if (h < 12)

{

MessageBox::Show(h + " is morning.");

}

else

{

MessageBox::Show(h + " is afternoon.");

}

}

if..else if..else Sometimes a programmer needs to make a decision based on several conditions. For example,

the letter grade a student can get from this course is determined using the following criteria,

which consists of 5 conditions.

Condition Percentage Letter grade

1 90 and above A

2 80 ~ 89.99 B

3 70 ~ 79.99 C

4 60 ~ 69.99 D

5 59.99 and below F

The use of the else if variant of the if statement can functionally solve this problem. The else if

statement(s) work by cascading the given conditions. When the first condition yields a true

result, the associated statement(s) or block will be executed, and no further testing are

performed. When the first condition is false, the second condition will be immediately tested.

When the second condition is tested to be true, its associated statement(s) will be executed,

and no further testing are performed. Otherwise, the third condition is tested. The same

process repeats till all conditions are tested if necessary.

The following example illustrates how the programming logic determines a student’s letter

grade depending on the given percentage. The Convert::ToString() method converts the user

input to the float type.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

#include "InputBox.cpp"

int main()

{

String^ str = InputBox::Show("Enter the percentage: ");

Page 7: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 136

float grade = Convert::ToSingle(str); //type casting

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 the above example, there is a variable of float type named “grade” which is used to hold a

percentage given by the user. The if..else..if..else statement contains four conditions for

testing: grade >= 90, grade >= 80, grade >= 70, and grade >= 60. The instructor manages to let

the “59.99 and below” condition be the “else” part of the if statement. In other words, when

none of the four specified conditions are true, the “59.99 and below” condition is assumed.

The if..else..if..else statement is used to choose from one of several conditions. The following

is another example. By the way, the instructor purposely not to enclose statements with a pair

curly brackets.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

DateTime dt = DateTime::Now;

int h = dt.Hour;

String^ ap = "AM";

if (h>12)

{

h = h - 12; // turn 24-hour value to 12-hour

ap = "PM"; // set to PM

}

String^ str = "";

if (h==1) str += "It is One ";

else if (h==2) str += "It is Two ";

else if (h==3) str += "It is Three ";

else if (h==4) str += "It is Four ";

else if (h==5) str += "It is Five ";

else if (h==6) str += "It is Six ";

else if (h==7) str += "It is Seven ";

else if (h==8) str += "It is Eight ";

else if (h==9) str += "It is Nine ";

else if (h==10) str += "It is Ten ";

else if (h==11) str += "It is Eleven ";

else str += "It is Twelve ";

str += ap + " now.\n";

MessageBox::Show(str);

}

Page 8: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 137

In the above code, the Hour property returns value in the 24-hour format. The following is one

way to turn it to 12-hour format. When the value is greater than 12, it will subtract 12 from the

value of h.

if (h>12)

{

h = h - 12;

ap = "PM";

}

The string variable “ap” (whose initial value is “AM”) is used to indicate AM/PM. When h is

greater than 12, its value will be changed to “PM”.

When h = 12 or h=24, none of the 11 expressions, (h==1), (h==2), (h==3), ..., (h==11), is

true. Therefore, the flow falls to the following else part of if statement. The output is “It is

Twelve AM now.” or “It is Twelve PM now.” according to the above code.

if (h==1) str += "It is One ";

..........

..........

else str += "It is Twelve ";

Nested if

statement

The if statement in Visual C++ can be nested, which could be an efficient solution when there

are multiple conditions to test. A “nested” if statement is an if statement that is the target of

another if statement. In other words, a nested if statement means an “if statement inside

another if statement”.

The following code has two layers of if statements: outer and inner. The outer evaluates the

condition (h > 12). When the (h > 12) condition is true, the inner evaluates another condition

(h > 18). The bold-faced lines are the nested if statements. It is necessary to note that both

inner and outer if statements are completed if statement, each of them contains the “if” part and

“else” part and can handle two possible execution paths: true or false. The dash-line border

denotes the inner if..else statement.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

int h = DateTime::Now.Hour;

if (h > 12)

{

if (h > 18)

{

MessageBox::Show(h + " is evening.");

}

else

{

MessageBox::Show(h + " is afternoon.");

}

}

else {

MessageBox::Show(h + " is morning.");

}

}

Page 9: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 138

The following is another example. It asks user to enter a number, and then determines the

letter grade.

#include "InputBox.cpp"

int main()

{

String^ str = InputBox::Show("Enter your score: ");

float score = Convert::ToSingle(str); //type casting

String^ gd = "";

if (score < 90) {

if (score < 80) {

if (score < 70) {

if (score < 60) { gd = "F"; }

else { gd = "D"; }

}

else { gd = "C"; }

}

else { gd = "B"; }

}

else { gd = "A"; }

MessageBox::Show("The semester grade is " + gd);

}

Nested if statement can be placed inside the “else” part. In the following example, there is an

if..else statement inside the “else” part of the first-layer if statement. The dashed border

encloses the second layer of the if statement.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

int h = DateTime::Now.Hour;

if (h < 12)

{

MessageBox::Show(h + " is morning.");

}

else {

if (h < 18)

{

MessageBox::Show(h + " is afternoon.");

}

else

{

MessageBox::Show(h + " is evening.");

}

}

}

Page 10: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 139

The following is the “nested if” version of one of the previous code.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

int h = DateTime::Now.Hour;

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

String^ str = "";

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

else {

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

else {

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

else {

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

else {

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

else {

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

else {

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

else {

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

else {

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

else {

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

else {

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

else { str += "It is Twelve "; }

}

}

}

}

}

}

}

} // else of layer 3

} // else of layer 2

} // else of layer 1

MessageBox::Show(str + "O\'clock.");

}

Conditional

operator

Visual C++ supports the conditional operator with the following syntax as a short-hand way of

an if..else statement. The expression must be a Boolean expression that can only yield either

true or false. A condition operator consists of a question mark (?) and a colon (:).

expression ? execution1 : execution2

When the expression evaluates to true (or 1), execution1 is executed. When the expression

evaluates to false (or 0), execution2 is executed. In a nutshell, execution2 is the “else” part of

the structure while execution1 is the “true” part of the structure.

Page 11: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 140

In the following example, when the expression (n%2==0) is true, the message box display

“even”; otherwise, it displays “odd”.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

Random^ rn = gcnew Random();

int n = rn->Next();

String^ str="";

(n%2==0) ? str="even" : str="odd";

MessageBox::Show(str);

return 0;

}

The above bold-faced line is functionally identical to the following if..else statement.

if (n%2==0) {

str="even"; //true part

}

else {

str="odd"; //else part

}

Interestingly, conditional operator can be nested. In the following example, the dashed line

border encloses the inner layer of conditional operator that was placed in the “else” part of the

code.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

double gd = 86.3;

String^ str="";

(gd >= 90) ? str="A" : (gd >= 80) ? str = "B" : str = "C";

MessageBox::Show(str);

return 0;

}

The above bold-faced line is functionally identical to the following code.

if (gd >= 90)

{

str="A";

}

Page 12: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 141

else

{

if (gd >= 80)

{

str="B";

}

else

{

str="C";

}

}

The

switch..case

Statement

The condition in an if statement must be a Boolean condition that can only produce two

possible outcomes: true or false. However, there are many expressions that produce more than

two possible outcomes, such as (x%5) which can yield 5 possible outcomes: { 0, 1, 2, 3, 4 }.

The following table illustrates why the expression (x%5) is not a Boolean expression. Any

expression that can yield more than 2 possible outcomes is not a Boolean expression.

Value of x Result of x%5

14 14%5 = 4

15 15%5 = 0

16 16%5 = 1 17 17%5 = 2 18 18%5 = 3 19 19%5 = 4 20 20%5 = 0

A switch..case structure is designed to handle the decision-making based on an expression that

has more than 2 possible outcomes. Unlike the if structure that only allow one if..else

statement to have two possible execution paths (one for true; the other for false), every

switch..case statement can have a number of possible execution paths. Every of the execution

path is an individual “case”.

The following illustrates the syntax, where expression is an expression or a variable while

constant1, constant2, .., and constantn are “case contstants” to be matched. The switch..case

statement evaluates the expression and then searches for the matching case among the “case

constants”. If a case is matched, the program will attempt to execute only the statements

associated to the matched case. Statements in case end with a “break” statement.

switch (expression)

{

case constant1: statements1; break;

case constant2: statements2; break;

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

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

case constantn: statementsn; break;

default: statementsn+1; // optional

}

The body of a switch statement is known as a switch block. Inside the switch block, every

section of statements is labeled with one “case constant” or the keyword “default”. The switch

statement match a value with a defined case, then executes all statements of the matched case.

In the following example, ‘A’, ‘B’, ‘C’, and ‘D’ are the case constant.

Char c = 'M';

switch(c)

{

Page 13: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 142

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

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

case 'C': str = "Chicago"; break;

case 'D': str = "Denver"; break;

default: str = "Undefined.";

}

In the syntax, there is a special case known as the “default” case. It is an optional case

designed for handling the “unexpected” cases. An “unexpected” case happens when the

program cannot find any matching case. The above example only defines four expected cases:

‘A’, ‘B’, ‘C’, and ‘D’. The value of the “c” variable; however, is ‘M’ and cannot match any of

the four expected cases. When there is no matching case, and the “default” case is present,

then statement(s) of the “default” case will be executed. By the way, the “default” case should

be the last case of the switch block.

Interestingly, the “default” case is only used for the unexpected. In the following example, the

expression, x%5, can only produce 5 possible outcomes: 0, 1, 2, 3, and 4. Since all the possible

cases are presented in the switch block, there is no need for the “default” case, so the “default”

case is omitted.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

Random^ rn = gcnew Random();

int x = rn->Next();

String^ str = "Reminder of " + x + "%5 is ";

switch (x%5)

{

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

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

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

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

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

}

MessageBox::Show(str);

}

The following code asks user to enter a number. The switch..case structure defines five

expected cases: ‘A’, ‘B’, ‘C’, ‘D’, and ‘F’. Any entry other than these five letters will be

considered unexpected and will thus become the “default” case. By the way, the ToUpper()

method converts a string to uppercase.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

#include "InputBox.cpp"

int main()

{

Page 14: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 143

String^ ans = InputBox::Show("Enter a grade:");

ans = ans->ToUpper(); // change to upper case

Char g = ans[0]; // get first character

String^ str="";

switch (g) // expression is a variable

{

case 'A': str="90 and above."; break;

case 'B': str="80 to 89.99."; break;

case 'C': str="70 to 79.99."; break;

case 'D': str="60 to 69.99."; break;

case 'F': str="below 60."; break;

default: str = "No such grade.";

}

MessageBox::Show(str);

}

The above switch block evaluates the value of a variable named “g” which is declared as Char

type. On the other hand, the user input is assigned to a String variable named “ans” which

accepts two or more characters. possible values. Since a String is an array of Char, the

following retrieve the first element of the “ans” and assigns it to “g”. In the above code, “g” is

a variable and is the expression evaluated by the switch statement.

Char g = ans[0];

A switch block can also evaluate an expression and match the result with a defined case. The

following compares two sample codes. One lets the switch statement evaluate an expression

that can produce 12 possible values; the other reads the value of a variable that can be assigned

one of 12 different values.

Expression Variable int h = DateTime::Now.Hour;

String^ str = nullptr;

switch (h%12) //expression

{

case 0: str = "Twelve";

case 1: str = "One";

case 2: str = "Two";

case 3: str = "Three";

case 4: str = "Four";

case 5: str = "Five";

case 6: str = "Six";

case 7: str = "Seven";

case 8: str = "Eight";

case 9: str = "Nine";

case 10: str = "Ten";

case 11: str = "Eleven";

}

int h = DateTime::Now.Hour;

h = h%12;

String^ str = nullptr;

switch (h) //variable

{

case 0: str = "Twelve";

case 1: str = "One";

case 2: str = "Two";

case 3: str = "Three";

case 4: str = "Four";

case 5: str = "Five";

case 6: str = "Six";

case 7: str = "Seven";

case 8: str = "Eight";

case 9: str = "Nine";

case 10: str = "Ten";

case 11: str = "Eleven";

}

The “break” statement placed at the end of a case forces the program to terminate the

switch..case structure and hand over the control to the statement following the switch block. In

other words, the “break” statement is used to ensure that only the code of the matched case

Page 15: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 144

will be executed. In the following, case ‘A’ and ‘B’ do not have the “break” statement. When

‘A’ is matched which does not have the “break” statement, the program will automatically

move on to read the code of case ‘a’, and then break off. Similarly, when ‘A’ is matched, the

program will automatically move on to read the statements of case ‘b’, and then break off. In

other words, when the answer is “A”, statements in case “a” will execute. When the answer is

“B”, statements in case “b” will execute.

#include "InputBox.cpp"

int main() {

String^ ans = InputBox::Show(

"Which is not a city?\na. California\nb.Boston.");

Char c = ans[0]; // get first character

String^ str;

switch (c)

{

case 'A':

case 'a': str="Correct. California is a state."; break;

case 'B':

case 'b': str="Incorrect. Boston is a city"; break;

default: str="You entered an unexpected answer";

}

MessageBox::Show(str);

}

The following is a bad code created by the instructor to demonstrates the role played by the

“break” statement in a switch..case structure. The “break” statement will force the switch..case

structure to terminate. However, all cases in the following code does not have the “break”

statement. Even though a case is matched, the program will continue to execute statements in

the next case and then repeatedly execute the next case until the last case of the switch block,

or the first time it sees a break statement. The output of the following code will always be

“Saturday” no matter what day of the week it is supposed to be.

// bad code

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

int w = Convert::ToInt32(DateTime::Now.DayOfWeek);

String^ str = "Today is ";

switch (w)

{

case 0: str += "Sunday";

case 1: str += "Monday";

case 2: str += "Tuesday";

case 3: str += "Wednesday";

case 4: str += "Thursday";

case 5: str += "Friday";

Page 16: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 145

case 6: str += "Saturday";

}

MessageBox::Show(str);

}

By the way, the “default” case is not necessary in this example because the DayOfWeek

property can only return 7 possible values with 0 being Sunday, 1 being Monday, and so on.

When the value of the variable w is 0, str is assigned “Sunday”. When w is 1, it is Monday,

and so on. Saturday, as the last in the weekday, is 6. Interestingly, values of the DayOfWeek

property are defined as enumerated constant by the DateTime structure. Therefore it is

necessary to convert it to int type (which as an alias of Int32), as shown below.

int w = Convert::ToInt32(DateTime::Now.DayOfWeek);

The following is a “good” version of code in which each case has a break statement to

terminate the execution.

// good code

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

int w = Convert::ToInt32(DateTime::Now.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;

}

MessageBox::Show(str);

return 0;

}

The switch..case statement is useful for creating a program to display randomly picked

messages. The following example uses random number generator to determine which tip to

display.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

Random^ rn = gcnew Random();

String^ tip;

switch (rn->Next(1,5))

{

Page 17: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 146

case 1: tip = "Bad news travels fast!"; break;

case 2: tip = "An apple a day keeps doctors away!"; break;

case 3: tip = "Every picture tells a story!"; break;

case 4: tip = "There are two sides to every question"; break;

}

MessageBox::Show(tip);

return 0;

}

In the above code, the randomly generated value is organized as an expression used in the

switch block to pick a tip.

switch (rn->Next(1,5)) { ..... }

It is important to note that not every case in a switch..case structure needs to have statements

for execution. In the following example, only when the weekday is Tuesday will a user see an

output.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

DateTime dt = DateTime::Now;

int w = Convert::ToInt16(dt.DayOfWeek);

String^ str;

switch (w)

{

case 0:

case 1:

case 2: str= "You just won the prize!"; break;

case 3:

case 4:

case 5:

case 6:

}

MessageBox::Show(str);

return 0;

}

It is also necessary to note that the entire switch..case structure only has one expression. The

evaluation result is used to find a match from the pre-defined cases including the “default”

case. In an if..else..if statement or a nested if structure, there are multiple conditions to

evaluate, and every condition must be evaluated in order to understand the logic to make the

correct decision. The following table compares two codes that produce the same results. There

is only one expression (w) at the switch..case side, yet, there are seven expressions to evaluate

at the if..else..if..else side.

switch..case DateTime dt = DateTime::Now;

int w = Convert::ToInt32(dt.DayOfWeek);

String^ wd;

Page 18: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 147

switch (w)

{

case 0: wd = "Sun"; break;

case 1: wd = "Mon"; break;

case 2: wd = "Tue"; break;

case 3: wd = "Wed"; break;

case 4: wd = "Thu"; break;

case 5: wd = "Fri"; break;

case 6: wd = "Sat"; break;

}

MessageBox::Show(wd);

if..else..if..else DateTime dt = DateTime::Now;

int w = Convert::ToInt32(dt.DayOfWeek);

String^ wd;

if (w==0) { wd = "Sun"; }

else if (w==1) { wd = "Mon"; }

else if (w==2) { wd = "Tue"; }

else if (w==3) { wd = "Wed"; }

else if (w==4) { wd = "Thu"; }

else if (w==5) { wd = "Fri"; }

else { wd = "Sat"; }

MessageBox::Show(wd);

In a nutshell, when a program needs to decide what to execute based on an expression that can

yield three or more possible results, a switch..case structure may be a better choice over the if

statement. From this point of view, the advantage of using switch..case structure is to simplify

the complexity of if..else’s. However, there is also a limitation of switch..case structure that

must be addressed. Visual C++, as well as the standard C++, does not allow the use of strings,

floating-point numbers, elements of array, or objects as value of a case.

The following is a sample code that demonstrates the incorrect data type of value for cases.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

String^ name = "jane";

switch (name)

{

case "jane": break; // syntax error

case "jack": break;

}

double d = 3.14;

switch (d)

{

case 3.14: break; // syntax error

case 4.27: break;

}

return 0;

}

Page 19: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 148

The following is the if version of the above code. Interestingly, if statement supports most

primitive data type.

goto keyword Visual C++, possibly inherited from standard C++, supports the “goto” keyword. The “goto”

statement transfers control to the location specified by a “label”. It provides an unconditional

jump from the “goto” statement to a labeled statement in the same program. The following is

the syntax of the “goto” statement, in which label is a given name that represents a block of

statements.

goto label;

.....

.....

label: statements;

The following is an example. There are four labels: “addIt”, “subIt”, “mulIt”, and “divIt”.

Each label represents a set of statement(s). The switch..case structure uses the random number

generator to randomly determine which of the four labels to “jump to”. When the case 0 is

matched, the “goto” keyword will force the control to jump to the “addIt” label. When the case

1 is matched, the “goto” keyword will force the control to jump to the “subIt” label.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

int x = 5; int y = 7;

Random^ rn = gcnew Random;

switch (rn->Next() % 4)

{

case 0: goto addIt; break;

case 1: goto subIt; break;

case 2: goto mulIt; break;

case 3: goto divIt; break;

}

addIt:

x = x + y;

subIt:

x = x - y;

mulIt:

x = x * y;

divIt:

x = x / y;

MessageBox::Show(x + "");

return 0;

}

Page 20: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 149

A real-world

example

Many retail stores offer discount(s) based on the unit price of products. The following table

lists the discounts.

Unit Price Disount Rate

0 ~ 24.99 0%

25 ~ 49.99 5%

50 ~ 74.99 10%

75 ~ 99.99 15%

100 ~ 249.99 20%

250 ~ 25%

The formula for performance the calculation is:

Discounted Unit Price = Unit Price × (1 – Discounted Rate)

A product with unit price 37.45 is eligible for a 5% discount. Therefore, the discounted price is

$37.5775. However, the smallest unit of the US$ currency is a cent. The calculated result need

to be rounded to $37.58.

37.45 × (1 - 5%) = 37.45 × 0.95 = 37.5775

The following is a sample code.

#include "InputBox.cpp"

int main() {

double discountRate, discountedPrice;

double unitPrice = Convert::ToDouble(InputBox::Show(

"Enter the unit price"));

if (unitPrice < 25) { discountRate = 0; }

else if (unitPrice < 50) { discountRate = 0.05; }

else if (unitPrice < 75) { discountRate = 0.1; }

else if (unitPrice < 100) { discountRate = 0.15; }

else if (unitPrice < 250) { discountRate = 0.2; }

else { discountRate = 0.05; }

discountedPrice = unitPrice * (1 - discountRate);

discountedPrice = Math::Round(discountedPrice, 2);

MessageBox::Show("Discounted Unit Price: $" +

discountedPrice);

}

The following is a sample output.

and

Review

Questions

1. The outcome of the following code is __.

String ^ str;

int i=4;

Page 21: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 150

if (i<5) { i++; }

else { i--; }

MessageBox::Show(i + "");

A. 3

B. 4

C. 5

D. 6

2. The outcome of the following code is __.

int i = 4;

switch (i)

{

case 3: i++; break;

case 4: i--;

case 5: i+=4; break;

case 6: i-=3; break;

default: i=0;

}

MessageBox::Show(i + "");

A. 4

B. 3

C. 7

D. 5

3. Given the following code segment, the value of a is __.

int a = (7==5) ? 4 : 3;

MessageBox::Show(a + "");

A. 4

B. 3

C. 7

D. 5

4. The outcome of the following code is __.

char c='K';

switch (c)

{

case 'A': c='A';

case 'H': c='H';

case 'K': c='K';

case 'M': c='M';; break;

}

MessageBox::Show(Convert::ToChar(c) + "");

A. A

B. H

C. K

D. M

5. The outcome of the following code is __.

Page 22: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 151

int i=5;

if (i>3) { if (i<6) { i=10; } else { i=8; } }

else { if (i==3) {i = 9; } else { i=7; } }

MessageBox::Show(i + "");

A. 7

B. 8

C. 9

D. 10

6. The outcome of the following code is __.

String ^ str;

int i=6;

if (i>=4) {

if (i==5) {str = i + "";}

else {str = --i + "";}

}

else {str = i++ + ""; }

MessageBox::Show(str);

A. 4

B. 5

C. 6

D. 3

7. The outcome of the following code is __.

String ^ str;

int i=3;

if (i>=4) {

if (i==5) {str = i + "";}

else {str = i-- + "";}

}

else {str = ++i + ""; }

MessageBox::Show(str);

A. 4

B. 5

C. 6

D. 3

8. The outcome of the following code is __.

int i=5;

if (i>1) { i=5; }

if (i>3) { i=6; }

if (i>6) { i=9; }

if (i>8) { i=12; }

MessageBox::Show(i + "");

A. 5

B. 6

C. 9

D. 12

Page 23: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 152

9. The outcome of the following code is __.

int i=5;

switch (i%2)

{

case 3: i=2;

case 4: i=3;

case 5: i=4; break;

default: i=5;

}

MessageBox::Show(i + "");

A. 2

B. 3

C. 4

D. 5

10. The outcome of the following code is __.

int i=5;

switch(i)

{

case 3: goto Case3; break;

case 4: goto Case4; break;

case 5: goto Case3; break;

default: goto Others;

}

Others: i=6;

Case5: i=5;

Case4: i=4;

Case3: i=3;

MessageBox::Show(i + "");

A. 3

B. 4

C. 5

D. 6

Page 24: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 153

Lab #5 C++ Flow Controls

Learning Activity #1: if .. else if

1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

2. Type notepad lab5_1.cpp and press [Enter] to use Notepad to create a new source file called lab5_1.cpp

with the following contents. The objective is to get the current hour value and display it in a sentence.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main()

{

//code

String^ ap = "AM";

DateTime dt = DateTime::Now;

int h = dt.Hour;

if (h > 12) { ap = "PM"; }

h = h % 12;

String^ str = "Method 1:"+ "\n";

str +="It 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 ";

if (h==12) str += "Twelve ";

str += "o\'clock " + ap + " now.";

str += "\nMethod 2:"+ "\n";

str +="It 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 ";

Page 25: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 154

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

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

else str += "Twelve ";

str += "o\'clock " + ap + " now.";

// display the content

MessageBox::Show( str );

}

3. Type cl /clr lab5_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the source file to create the executable object file.

4. Type lab5_1.exe and press [Enter] to test the executable file. A sample output looks:

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

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

Learning Activity #2: switch .. case

1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

2. Type notepad lab5_2.cpp and press [Enter] to use Notepad to create a new source file called lab5_2.cpp

with the following contents. The objective is to get the current hour value and display it in a sentence.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

String^ ap = "AM";

DateTime dt = DateTime::Now;

int h = dt.Hour;

if (h>12) {h = h - 12; ap="PM"; }

String^ str = "Correct:\nIt is ";

//good - with break

switch (h) {

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

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

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

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

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

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

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

case 7: str += "Seven"; break;

case 8: str += "Eight"; break;

Page 26: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 155

case 9: str += "Nine"; break;

case 10: str += "Ten"; break;

case 11: str += "Eleven"; break;

}

str += " o\'clock " + ap + " now!"+ "\n";

str += "\nIncorrect:\nIt is ";

//wrong - without break

switch (h) {

case 0: str += "Twelve";

case 1: str += "One";

case 2: str += "Two";

case 3: str += "Three";

case 4: str += "Four";

case 5: str += "Five";

case 6: str += "Six";

case 7: str += "Seven";

case 8: str += "Eight";

case 9: str += "Nine";

case 10: str += "Ten";

case 11: str += "Eleven";

}

str += " o\'clock " + ap + " now!"+ "\n";

MessageBox::Show(str);

return 0;

}

3. Type cl /clr lab5_2.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the source file to create the executable object file.

4. Type lab5_1.exe and press [Enter] to test the executable file. A sample output looks:

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

Learning Activity #3: Conditional Operator

1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

2. Type notepad lab5_3.cpp and press [Enter] to use Notepad to create a new source file called lab5_3.cpp

with the following contents:

#include "InputBox.cpp"

int main() {

double gd = Convert::ToDouble(InputBox::Show("Enter a score:"));

String^ str="Conditional Operator:\nIt is ";

Page 27: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 156

(gd >= 90) ? str="A" : (gd >= 80) ? str += "B" : (gd >= 70) ? str += "C" : (gd >=

60) ? str += "D" : str += "F";

str += "\n\nif..else:\nIt is ";

if (gd >= 90)

{

str+="A";

}

else

{

if (gd >= 80)

{

str+="B";

}

else

{

if (gd >= 70)

{

str+="C";

}

else

{

if (gd >= 60)

{

str+="D";

}

else

{

str+="F";

}

}

}

}

MessageBox::Show(str);

return 0;

}

3. Type cl /clr lab5_3.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the source file to create the executable object file.

4. Type lab5_3.exe and press [Enter] to test the executable file. A sample output looks:

5. Capture a screen shot similar to the above two figures and paste it to the Word document named lab5.doc

(or .docx).

Learning Activity #4: switch..case vs if..else

1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

Page 28: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 157

2. Type notepad lab5_4.cpp and press [Enter] to use Notepad to create a new source file called lab5_4.cpp

with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

int main() {

DateTime dt = DateTime::Now;

int w = Convert::ToInt32(dt.DayOfWeek);

String^ str = "switch..case:\nIt is ";

switch (w)

{

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

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

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

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

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

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

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

}

str += " today.\n";

str += "\nif..else\nIt is ";

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

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

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

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

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

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

else { str += "Sat"; }

str += " today.\n";

MessageBox::Show(str);

return 0;

}

3. Type cl /clr lab5_4.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the source file to create the executable object file.

4. Type lab5_4.exe and press [Enter] to test the executable file. A sample output looks:

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

Page 29: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 158

Learning Activity #5: goto

1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

2. Type notepad lab5_5.cpp and press [Enter] to use Notepad to create a new source file called lab5_5.cpp

with the following contents:

#include "InputBox.cpp"

int main() {

String^ str = "";

String^ ans = InputBox::Show("Enter your blood type:");

ans = ans->ToUpper();

if (ans == "A") { goto showA; }

else if (ans == "B") { goto showB; }

else if (ans == "O") { goto showO; }

else if (ans == "AB") { goto showAB; }

else { goto ShowNone; }

showA:

str = "Eat more apple."; goto showMsg;

showB:

str = "Eat more banana."; goto showMsg;

showO:

str = "Eat more orange."; goto showMsg;

showAB:

str = "Eat more apple and banana."; goto showMsg;

ShowNone:

str = "Noe such blood type."; goto showMsg;

showMsg:

MessageBox::Show(str);

return 0;

}

3. Type cl /clr lab5_5.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the source file to create the executable object file.

4. Type lab5_5.exe and press [Enter] to test the executable file. Click OK. A sample output looks:

and

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

Submittal

1. Complete all the 5 learning activities and the programming exercise in this lab.

Page 30: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 159

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

• Lab5_1.exe

• Lab5_2.exe

• Lab5_3.exe

• Lab5_4.exe

• Lab5_5.exe

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

3. Log in to course web site (e.g. Canvas or Blackboard) and enter the course site.

4. Upload the zipped file to Question 11 of Assignment as response.

Programming Exercise 05:

1. Launch the Developer Command Prompt.

2. Use Notepad to create a new text file named ex05.cpp.

3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one).

//File Name: ex05.cpp

//Programmer: [YourFullNameHere]

4. Include the “InputBox.cpp” file to your source code and use the InputBox::Show() method (provided by the

“InputBox.cpp” file) to ask a message “Enter a number” as input.

5. Write codes using a “switch..case” statement to match the user input with one of the following case and display

the message in a GUI-based Windows application. You must use the “switch..case” statement, or you will be

given 0 points.

Value Message

2 Use red color!

3 Use blue color!

4 Use green color!

5 Use white color!

6 Use yellow color!

Others Invalid number!

6. Compile the source code to produce executable code.

7. Upload both the source file and executable code as file response of the Assignment.

and

8. Download the “programming exercise template” and rename it to ex05.doc if necessary. Copy your source

code to the file and then capture the screen shot(s) similar to the above one and paste it to the Word document

named “ex05.doc” (or .docx).

9. Compress the source file (ex05.cpp), executable code (ex05.exe), and Word document (ex05.doc) to a .zip file

named “ex05.zip”.

Grading criteria:

Page 31: decision structure - Cypress Collegestudents.cypresscollege.edu/cis223/lc05.pdf · Visual C++ Programming – Penn Wu, PhD 130 Lecture #5 Decision Structure Control Statements Most

Visual C++ Programming – Penn Wu, PhD 160

You will earn credit only when the following requirements are fulfilled. No partial credit is given.

• You successfully submit both source file and executable file.

• You must use the “switch..case” statement and the Random class to earn credit.

• Your source code must be fully functional and may not contain syntax errors in order to earn credit.

• Your executable file (program) must be executable to earn credit.

Threaded Discussion

Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at

least two messages as responses to the question every week. Each message must be posted on a

different date. Grading is based on quality of the message.

Question:

Class, is the "switch..case" structure more effective than a nested "if" structure? Why or why not? If

you can, provide an example to support your perspective. [There is never a right-or-wrong answer for

this question. Please free feel to express your opinion.]

Be sure to use proper college level of writing. Do not use texting language.