Decision Structure - 1 ISYS 350.

Slides:



Advertisements
Similar presentations
Work with Data and Decision Structure. Murach’s Java SE 6, C3© 2007, Mike Murach & Associates, Inc. Slide 2.
Advertisements

VB.Net Introduction - 2. Counter Example: Keep track the number of times a user clicks a button Need to declare a variable: Dim Counter As Integer Need.
IF Function Decision: Action based on condition. Examples SF State Tuition calculation: –
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Making Decisions.
C# Introduction ISYS 512. Major Differences Between VB Project and C# Project The execution starts from the Main method which is found in the Program.cs.
© 1999, by Que Education and Training, Chapter 5, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
Work with Data and Decision Structure. Slide 2 Note: String and Date are classes.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
LESSON 12-1 Preparing Payroll Time Cards
Decision Structure - 1 ISYS 350. Decision: Action based on condition Examples Simple condition: – If total sales exceeds $300 then applies 5% discount;
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Decision Structure - 2 ISYS 350. Complex Condition with Logical Operators The logical AND operator (&&) and the logical OR operator (||) allow you to.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Expression and Decision Structure ISYS 350. Performing Calculations Basic calculations such as arithmetic calculation can be performed by math operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Decision Structure - 2 ISYS 350. Complex Condition with Logical Operators The logical AND operator (&&) and the logical OR operator (||) allow you to.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
C# - FCL/Form & Control Validation John Kelleher.
Decisions Action based on condition. Examples Simple condition: –If total sales exceeds $300 then applies 5% discount; otherwise, no discount. More than.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Decision Structure - 1 ISYS 350. Decision: Action based on condition Examples Simple condition: – If total sales exceeds $300 then applies 5% discount;
Functions BUS 782. What are functions? Functions are prewritten formulas. We use functions to perform calculations. Enclose arguments within parentheses.
Introduction to Methods ISYS 350. Methods Methods can be used to break a complex program into small, manageable pieces – This approach is known as divide.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
IF Function Decision: Action based on condition. Examples SF State Tuition calculation: –
Use TryParse to Validate User Input
Decision Structure - 2 ISYS 350.
Decision Structure ISYS 350.
Decision Structure - 1 ISYS 350.
Chapter 4: Making Decisions.
Lesson 04: Conditionals Topic: Introduction to Programming, Zybook Ch 3, P4E Ch 3. Slides on website.
Chapter 4: Making Decisions.
Computer Programming I
The Selection Structure
Use TryParse to Validate User Input
Hosted by Ms. Appel.
Chapter 4: Making Decisions.
Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Javascript Conditionals.
Programming with Microsoft Visual Basic 2008 Fourth Edition
Programming Interface Controls
Programming Interface Controls
Decision Structure - 2 ISYS 350.
Decision Structure - 1 ISYS 350.
Control Statement Examples
Making Decisions in a Program
Lesson 04 Control Structures I : Decision Making
Work with Data and Decision Structure
Decision Structure - 2 ISYS 350.
Part A – Doing Your Own Input Validation with Simple VB Tools
SELECTION STATEMENTS (2)
Part B – Structured Exception Handling
Decision Structures ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure - 2 ISYS 350.
Microsoft Visual Basic 2005: Reloaded Second Edition
Decision Structure - 1 ISYS 350.
Decision: Action based on condition
Decision Structure - 2 ISYS 350.
Functions BUS 782.
Boolean Expressions to Make Comparisons
Programming Interface Controls
Presentation transcript:

Decision Structure - 1 ISYS 350

Decision: Action based on condition Examples Simple condition: If total sales exceeds $300 then applies 5% discount; otherwise, no discount. More than one condition: Taxable Income < =3000 no tax 3000 < taxable income <= 10000 5% tax Taxable income > 10000 15% tax Complex condition: If an applicant’s GPA > 3.0 and SAT > 1200: admitted

Relational Operators A relational operator determines whether a specific relationship exists between two values Operator Meaning Expression > Greater than x > y Is x greater than y? < Less than x < y Is x less than y? >= Greater than or equal to x >= y Is x greater than or equal to y? <= Less than or equal to x <= y Is x less than or equal to you? == Equal to x == y Is x equal to y? != Not equal to x != y Is x not equal to you?

A Simple Decision Structure The flowchart is a single-alternative decision structure It provides only one alternative path of execution In C#, you can use the if statement to write such structures. A generic format is: if (expression) { Statements; etc.; } The expression is a Boolean expression that can be evaluated as either true or false Cold outside True Wear a coat False

if Statement with Boolean Expression sales > 50000 if (sales > 50000) { bonus = 500; } True bonus = 500 False

Tuition Calculation (1) Tuition is $1200. If you take more than 12 units, each unit over 12 will be charged $200. private void button1_Click(object sender, EventArgs e) { int units; double tuition; units = int.Parse(textBox1.Text); tuition = 1200.00; if (units > 12) tuition = 1200.00 + 200 * (units - 12); } textBox2.Text = tuition.ToString("C");

Example of if-else Statement if (temp > 40) { MessageBox.Show(“hot”); } else MessageBox.Show(“cold”); temp >40 display “hot” display “cold” True False

Tuition Calculation (2) If total units <= 12, then tuition = 1200 Otherwise, tuition = 1200 + 200 per additional unit private void button1_Click(object sender, EventArgs e) { int units; double tuition; units = int.Parse(textBox1.Text); if (units <= 12) tuition = 1200.00; else tuition = 1200.00 + 200 * (units - 12); textBox2.Text = tuition.ToString("C"); } Note: If the if block contains only one line code, then the { } is optional.

Compute Weekly Wage For a 40-hour work week, overtime hours over 40 are paid 50% more than the regular pay. private void button1_Click(object sender, EventArgs e) { double hoursWorked, hourlyPay, wage; hoursWorked = double.Parse(textBox1.Text); hourlyPay = double.Parse(textBox2.Text); if (hoursWorked <= 40) wage=hoursWorked*hourlyPay; else wage=40*hourlyPay + 1.5*hourlyPay*(hoursWorked-40); textBox3.Text = wage.ToString("C"); }

Example: if with a block of statements If total sales is greater than 1000, then the customer will get a 10% discount ; otherwise, the customer will get a 5% discount. Create a form to enter the total sales and use a button event procedure to compute and display the net payment in a textbox. And display a message “Thank you very much” if then total sales is greater than 1000; otherwise display a message “Thank you”.

private void button1_Click(object sender, EventArgs e) { double totalSales, discountRate, netPay; string myMsg; totalSales=double.Parse(textBox1.Text); if (totalSales <= 1000) discountRate = .05; netPay = totalSales * (1 - discountRate); myMsg = "Thank you!"; } else discountRate = .1; myMsg = "Thank you very much!"; textBox2.Text = netPay.ToString("C"); MessageBox.Show(myMsg);

Practices 1. The average of two exams is calculated by this rule: 60% * higher score + 40% * lower score. Create a form with two textboxes to enter the two exam scores and use a button event procedure to compute and display the weighted average with a MessageBox.Show statement. 2. An Internet service provider offers a service plan that charges customer based on this rule: The first 20 hours: $10 Each additional hour: $1.5 Create a form with a textbox to enter the hours used and use a button event procedure to compute and display the service charge with a MessageBox.Show statement.

Practices 3. FICA Taxes (Social Security): The Social Security (FICA) tax contains two parts. The Social Security (Old Age, Survivors, and Disability Insurance) FICA tax is based on the first $87,900 paid at the rate of 6.2% with a maximum amount withheld of $5450. The Medicare (Medical Hospital Insurance) FICA tax is based on all earnings paid, at the rate of 1.45%. Create a form with a textbox to enter an employee’s annual salary and use a button event procedure to compute and display the Social Security Tax with a MessageBox.Show statement.

The if-else-if Statement Example: Rules to determine bonus: JobCode = 1, Bonus=500 JobCode = 2, Bonus = 700 JobCode = 3, Bonus = 1000 JobCode = 4, Bonus=1500

The if-else-if Statement You can also create a decision structure that evaluates multiple conditions to make the final decision using the if-else-if statement In C#, the generic format is: if (expression) { } else if (expression) … else

Code Example private void button1_Click(object sender, EventArgs e) { int jobCode; double bonus; jobCode = int.Parse(textBox1.Text); if (jobCode == 1) { bonus = 500; } else if (jobCode == 2) { bonus = 700; } else if (jobCode == 3) { bonus = 1000; } else { bonus = 1500; } MessageBox.Show("Your bonus is: " + bonus.ToString("c")); }

Example Special tax: CA: 1% WA: 1.5% NY: 1.2% Other states: 0.5%

Code private void button1_Click(object sender, EventArgs e) { string state; double taxRate; state = textBox1.Text; if (state == "CA") { taxRate = 0.01; } else if (state == "WA") { taxRate = 0.015; } else if (state == "NY") { taxRate = .012; } else { taxRate = .005; } MessageBox.Show("The tax rate is: " + taxRate.ToString("p")); }

Tax Rate Schedule Rules to determine tax rate: Taxable Income < =3000 no tax 3000 < taxable income <= 10000 5% tax 10000<Taxable income <= 50000 15% tax Taxable income>50000 25% double taxableIncome, taxRate, tax; taxableIncome = double.Parse(textBox1.Text); if (taxableIncome <= 3000) { taxRate = 0; } else if (taxableIncome<=10000) taxRate= .05; else if (taxableIncome <= 50000) taxRate = .15; else taxRate = .25; tax = taxableIncome * taxRate; textBox2.Text = tax.ToString("C");

Rules to determine letter grade Avg>=90 A 80<=Avg<90 B 70<=Avg<80 C 60<=Avg<70 D Avg<60 F

Compare these two programs double grade = double.Parse(textBox1.Text); if (grade < 60) { MessageBox.Show("F"); } else if (grade < 70) MessageBox.Show("D"); else if (grade < 80) MessageBox.Show("C"); else if (grade < 90) MessageBox.Show("B"); else MessageBox.Show("A"); double grade = double.Parse(textBox1.Text); 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");

Input Validation Numbers are checked to ensure they are: Within a range of possible values Reasonableness Not causing problems such as division by 0. Containing only digits IsNumeric Texts are checked to ensure correct format. Phone #, SSN. Required field

Text Box Validation Useful property: Useful events CausesValidation: true Useful events TextChanged: default event Triggered whenever the textbox is changed. Validating – useful for validating data entered in the box Triggered just before the focus shifts to other control.

Data Entered in Textbox1 cannot be greater than 2000 private void textBox1_Validating(object sender, CancelEventArgs e) { double enteredData; enteredData = double.Parse(textBox1.Text); if (enteredData > 2000) MessageBox.Show("The data cannot be greater than 2000!"); e.Cancel=true; } Note: e.Cancel=true;

Throwing an Exception In the following example, the user may entered invalid data (e.g. null) to the milesText control. In this case, an exception happens (which is commonly said to “throw an exception”). The program then jumps to the catch block. You can use the following to display an exception’s system error message: catch (Exception ex) { MessageBox.Show(ex.Message); } Or a user-defined error message: catch ( ) MessageBox.Show(“User-defined error message”);

Use Try/Catch to Detect Data Syntax Error { double miles; double gallons; double mpg; miles = double.Parse(milesTextBox.Text); gallons = double.Parse(gallonsTextBox.Text); mpg = miles / gallons; mpgLabel.Text = mpg.ToString(); } catch MessageBox.Show("Invalid data was entered."): Note: Show a system generated error message: catch (Exception ex) { MessageBox.Show(ex.Message); }

Use Try Catch with the Validating event: Testing for digits only This example uses the Double.Parse method trying to convert the data entered in the box to double. If fail then it is not numeric. private void textBox1_Validating(object sender, CancelEventArgs e) { try double.Parse(textBox1.Text); e.Cancel = false; } catch e.Cancel = true; MessageBox.Show("Enter digits only");

Testing for digits only and cannot be greater than 2000 private void textBox1_Validating(object sender, CancelEventArgs e) { try double myData; myData= double.Parse(textBox1.Text); if (myData>2000) MessageBox.Show("The data cannot be greater than 2000!"); e.Cancel=true; } catch e.Cancel = true; MessageBox.Show("Enter digits only");

Compare these two programs double grade = double.Parse(textBox1.Text); 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"); double grade = double.Parse(textBox1.Text); if (grade >=90) { MessageBox.Show("A"); } if (grade >=80) MessageBox.Show("B"); if (grade >=70) MessageBox.Show("C"); if (grade >=60) MessageBox.Show("D"); if (grade < 60) MessageBox.Show("F");