C# Tutorial MSM_Murach chapter-05-slides

36
Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 1 C hapter5 How to code controlstructures

Transcript of C# Tutorial MSM_Murach chapter-05-slides

Page 1: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 1

Chapter 5

How to code control structures

Page 2: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 2

The syntax of the if-else statement if (booleanExpression) { statements } [else if (booleanExpression) { statements }] ... [else { statements }]

If statements without else if or else clauses With a single statement if (subtotal >= 100) discountPercent = .2m;

With a block of statements if (subtotal >= 100) { discountPercent = .2m; status = "Bulk rate"; }

Page 3: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 3

An if statement with an else clause if (subtotal >= 100) discountPercent = .2m; else discountPercent = .1m;

An if statement with else if and else clauses if (subtotal >= 100 && subtotal < 200) discountPercent = .2m; else if (subtotal >= 200 && subtotal < 300) discountPercent = .3m; else if (subtotal >= 300) discountPercent = .4m; else discountPercent = .1m;

Page 4: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 4

Nested if statements if (customerType == "R") { // begin nested if if (subtotal >= 100) discountPercent = .2m; else discountPercent = .1m; } // end nested if else // customerType isn't "R" discountPercent = .4m;

Page 5: C# Tutorial MSM_Murach chapter-05-slides

Slide 5

How to use the relational operators

You can use the relational operators to create a Boolean expression that compares two operands and returns a Boolean value.

To compare two operands for equality, use two equals

signs. If you use a single equals sign, the compiler will interpret it as an assignment statement, and your code won’t compile.

Page 6: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 6

Relational operators Operator Name == Equality != Inequality > Greater than < Less than >= Greater than or equal <= Less than or equal

Page 7: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 7

Examples that use relational operators firstName == "Frank" // equal to a string literal txtYears.Text == "" // equal to an empty string message == null // equal to a null value discountPercent == 2.3 // equal to a numeric literal isValid == false // equal to the false value code == productCode // equal to another variable lastName != "Jones" // not equal to a string literal years > 0 // greater than a numeric literal i < months // less than a variable subtotal >= 500 // greater than or equal to // a literal value quantity <= reorderPoint // less than or equal to // a variable

Page 8: C# Tutorial MSM_Murach chapter-05-slides

Slide 8

How to use logical operators You can use the logical operators to create a Boolean expression

that combines two or more Boolean expressions. Since the && and || operators only evaluate the second

expression if necessary, they’re sometimes referred to as short-circuit operators. These operators are slightly more efficient than the & and | operators.

Page 9: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 9

Logical operators Operator Name Description && Conditional-And Returns a true value if both expressions are

true. This operator only evaluates the second expression if necessary.

|| Conditional-Or Returns a true value if either expression is true. This operator only evaluates the second expression if necessary.

& And Returns a true value if both expressions are true. This operator always evaluates both expressions.

| Or Returns a true value if either expression is true. This operator always evaluates both expressions.

! Not Reverses the value of the expression.

Page 10: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 10

Examples of logical operators subtotal >= 250 && subtotal < 500 timeInService <= 4 || timeInService >= 12 isValid == true & counter++ < years isValid == true | counter++ < years date > startDate && date < expirationDate || isValid == true ((thisYTD > lastYTD) || empType=="Part time") && startYear < currentYear !(counter++ >= years)

Page 11: C# Tutorial MSM_Murach chapter-05-slides

In-Class Activity

• Can you– Code the “Calculate..” to

• Access txtNumericGrade.Text• Convert it to a decimal and store it in a variable• Use If-else construct to determine the letter grade

and display it in lblLetterGrade.txt Numeric Grade Letter Grade

90-100 A

80-89 B

70-79 C

60-69 D

< 60 F

Page 12: C# Tutorial MSM_Murach chapter-05-slides

Slide 12

In-Class Activity

• Can you– Code the “Exit” button– Code the “Calculate..” button to

• If the customer is “Preferred”, they always get free shipping• Shipping cost for non-Preferred is a function of the Order Total

– $0.00-$25.00 = $5.00– $25.01-$500.00 = $8.00– $500.01-$1,000.00 = $10.00– $1,000.01-$5,000.00 = $15.00– $5,000.01 and up = $20.00

• Sales tax is 7% of Order Total + Shipping (if any)• Display the shipping cost, sales tax, and grand total all formatted

as currency

Page 13: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 13

The enhanced Invoice Total form

Refer to page 144 to see what is going on with this enhanced form…

Page 14: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 14

The event handler for the Click event of the Calculate button private void btnCalculate_Click(object sender, System.EventArgs e) { string customerType = txtCustomerType.Text; decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); decimal discountPercent = .0m; if (customerType == "R") { if (subtotal < 100) discountPercent = .0m; else if (subtotal >= 100 && subtotal < 250) discountPercent = .1m; else if (subtotal >= 250) discountPercent =.25; }

Page 15: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 15

The event handler (continued) else if (customerType == "C") { if (subtotal < 250) discountPercent = .2m; else discountPercent = .3m; } else { discountPercent = .4m; } decimal discountAmount = subtotal * discountPercent; decimal invoiceTotal = subtotal - discountAmount; txtDiscountPercent.Text = discountPercent.ToString("p1"); txtDiscountAmount.Text = discountAmount.ToString("c"); txtTotal.Text = invoiceTotal.ToString("c"); txtCustomerType.Focus(); }

Page 16: C# Tutorial MSM_Murach chapter-05-slides

Slide 16

Tinker with if-else statements 1. Open the application that’s in the Z:\Murach Files\Book

Applications\Chapter 05\InvoiceTotal directory. 2. Change the if-else statement so customers of type “R” with a subtotal that

is greater than or equal to $250 but less than $500 get a 25% discount and those with a subtotal of $500 or more get a 30% discount. Next, change the if-else statement so customers of type “C” always get a 20% discount. Then, test the application to make sure this works.

3. Add another customer type to the if-else statement so customers of type

“T” get a 40% discount for subtotals of less than $500, and a 50% discount for subtotals of $500 or more. Also, make sure that customer types that aren’t “R”, “C”, or “T” get a 10% discount. Then, test the application.

4. Test the application again, but use lowercase letters for the customer types.

Note that these letters aren’t evaluated as capital letters. Now, stop the debugging and modify the code so the users can enter either capital or lowercase letters for the customer types. Then, test the application to make sure it works correctly.

Page 17: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 17

The syntax of the while statement while (booleanExpression) { statements }

A while loop that adds the numbers 1 through 4 int i = 1, sum = 0; while (i < 5) { sum += i; i++; }

A while loop that calculates a future value int i = 1; while (i <= months) { futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate); i++; }

Page 18: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 18

The syntax of the do-while statement do { statements } while (booleanExpression);

A do-while loop that calculates a future value int i = 1; do { futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate); i++; } while (i <= months);

Page 19: C# Tutorial MSM_Murach chapter-05-slides

Slide 19

Concepts When you set a breakpoint at a specific statement, the program

stops before executing that statement and enters break mode. Then, you can step through the execution of the program one statement at a time.

In break mode, the Autos window displays the current values of the variables in the current statement and the previous statement.

Page 20: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 20

How to set and clear breakpoints To set a breakpoint, click in the margin indicator bar to the left of

a statement. Or, press the F9 key to set a breakpoint at the cursor insertion point. Then, a red dot will mark the breakpoint.

To remove a breakpoint, use either technique for setting a breakpoint. To remove all breakpoints at once, use the Clear All Breakpoints command in the Debug menu.

How to work in break mode In break mode, a yellow arrowhead marks the current execution

point, which points to the next statement that will be executed. To step through your code one statement at a time, press the F11

key or click the Step Into button on the Debugging toolbar. To continue normal processing until the next breakpoint is

reached, press the F5 key.

Page 21: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 21

A for loop with a breakpoint and an execution point

Page 22: C# Tutorial MSM_Murach chapter-05-slides

Slide 22

Using the Debugger to Watch a While Loop Take a close look at the “Future Value” spreadsheet Review “Future Value with While Loop” program in Class

Activities folder Run the code Instruction step through the code slowly to see exactly what is

happening

Page 23: C# Tutorial MSM_Murach chapter-05-slides

Slide 23

In-Class Activity

• Can you– Get the number of students today.– Using a loop, calculate the number of students

each year for the number of years, adding in the number of new students each year.

– Don’t forget about compounding.

Text boxes

Read Only Text Box

Page 24: C# Tutorial MSM_Murach chapter-05-slides

In-Class Activity

• Playing with While loops– Meaningless activity– Forces you to use While loop– Encourage use of debugger

• Debugger…get it…sorry– Look through my solution in the “In Class

Exercises” folder on the Z-drive and then see if you can code this loop on your own

Each roach is 0.002 cubic feet & has a weekly growth rate of 95%

Page 25: C# Tutorial MSM_Murach chapter-05-slides

Slide 25

How to code for loops The for statement is useful when you need to increment or

decrement a counter that determines how many times the for loop is executed.

Within the parentheses of a for loop, you code three expressions:

(1) an initialization expression that assigns a starting value to the counter variable; (2) a Boolean expression that specifies the condition under which the loop executes; and (3) an increment expression that indicates how the counter variable should be incremented or decremented each time the loop is executed.

Page 26: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 26

The syntax of the for statement for (initializationExpression; booleanExpression; incrementExpression) { statements }

A for loop that stores the numbers 0 through 4 in a string

With a single statement string numbers = null; for (int i = 0; i < 5; i++) numbers += i + "\n";

With a block of statements string numbers = null; for (int i = 0; i < 5; i++) { numbers += i; numbers += "\n"; }

Page 27: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 27

A for loop that adds the numbers 8, 6, 4, and 2 int sum = 0; for (int j = 8; j > 0; j-=2) { sum += j; }

A for loop that calculates a future value for (int i = 1; i <= months; i++) { futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate); }

Page 28: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 28

The Future Value form

The property settings for the form Default name Property Setting Form1 Text Future Value AcceptButton btnCalculate CancelButton btnExit

Page 29: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 29

The property settings for the controls Default name Property Setting label1 Text Monthly Investment: label2 Text Yearly Interest Rate: label3 Text Number of Years: label4 Text Future Value: textBox1 Name txtMonthlyInvestment textBox2 Name txtInterestRate textBox3 Name txtYears textBox4 Name txtFutureValue

ReadOnly True TabStop False

Page 30: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 30

The property settings for the controls (continued) Default name Property Setting button1 Name btnCalculate

Text &Calculate button2 Name btnExit

Text E&xit

Additional property settings The TextAlign property of each of the labels is set to MiddleLeft. The TabIndex properties of the controls are set so the focus moves

from top to bottom and left to right.

Page 31: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 31

The code for event handlers in the Future Value application private void btnCalculate_Click(object sender, System.EventArgs e) { decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); decimal yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text); int years = Convert.ToInt32(txtYears.Text); int months = years * 12; decimal monthlyInterestRate = yearlyInterestRate / 12 / 100; decimal futureValue = 0m; for (int i = 0; i < months; i++) { futureValue = (futureValue + monthlyInvestment) * (1 + monthlyInterestRate); }

Page 32: C# Tutorial MSM_Murach chapter-05-slides

Murach’s C# 2010, C5 © 2010, Mike Murach & Associates, Inc. Slide 32

The code for event handlers in the Future Value application (continued) txtFutureValue.Text = futureValue.ToString("c"); txtMonthlyInvestment.Focus(); } private void btnExit_Click(object sender, System.EventArgs e) { this.Close(); }

Page 33: C# Tutorial MSM_Murach chapter-05-slides

Slide 33

Using the Debugger to Watch a For Loop Take a close look at the “Future Value” spreadsheet Review “Future Value with For” program in Class Activities

folder Run the code Instruction step through the code slowly to see exactly what is

happening

Page 34: C# Tutorial MSM_Murach chapter-05-slides

Slide 34

In-Class Activity

• Can you convert this loop from a while loop to a for loop?

Text boxes

Read Only Text Box

Page 35: C# Tutorial MSM_Murach chapter-05-slides

In-Class Activity

• Can you change this loop from a while loop to a for loop?

Page 36: C# Tutorial MSM_Murach chapter-05-slides

Slide 36

In-Class Activity• This will be a tricky one!

– Blank out txtNumericOnly.Text– Store the alphanumeric number in a string– Use the .Length method to figure out how

many characters are in the string– Create a loop that will be used to step

through the characters in the string• Extract a character using the .Substring method• If it is a letter that is on your phone keypad,

translate it to the corresponding number.• If it is not a letter on your telephone keypad,

don’t translate it to anything else• Use the + operator to concatenate this one

character string onto the end of txtNumericOnly.Text