Expression and Decision Structure ISYS 350. Performing Calculations Basic calculations such as arithmetic calculation can be performed by math operators.

Slides:



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

1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
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: –
Complex Conditions. Logical Operators: AND, OR, NOT AND Cond1Cond2Cond1 AND Cond2T TF FTF OR Cond1Cond2Cond1 OR Cond2T TF FTF NOT CondNOT Cond T F.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Making Decisions.
1 Selection Structures. 2 Making Decisions Sample assignment statements to figure worker pay with possible overtime PayAmount = Hours * Rate PayAmount.
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.
Work with Data and Decision Structure. Slide 2 Note: String and Date are classes.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Expression ISYS 350. Performing Calculations Basic calculations such as arithmetic calculation can be performed by math operators OperatorName of the.
Decision Structures and Boolean Logic
2440: 211 Interactive Web Programming Expressions & Operators.
Computer Science Selection Structures.
C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows.
Chapter 4 Selection Structures: Making Decisions.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
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.
Chapter Making Decisions 4. Relational Operators 4.1.
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,
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
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.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
IF Function Decision: Action based on condition. Examples SF State Tuition calculation: –
A First Book of C++ Chapter 4 Selection.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Decision Structure - 2 ISYS 350.
Expression ISYS 350.
Decision Structure ISYS 350.
Decision Structure - 1 ISYS 350.
Chapter 4: Making Decisions.
Topics The if Statement The if-else Statement Comparing Strings
Expression ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure - 1 ISYS 350.
Topics The if Statement The if-else Statement Comparing Strings
Working with DateTime Data
Work with Data and Decision Structure
Decision Structure - 2 ISYS 350.
Expression ISYS 350.
Decision Structures ISYS 350.
Expression ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure - 1 ISYS 350.
Decision: Action based on condition
Decision Structure - 2 ISYS 350.
Boolean Expressions to Make Comparisons
Expression ISYS 350.
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Decision Structure - 1 ISYS 350.
Expression ISYS 350.
Presentation transcript:

Expression and Decision Structure ISYS 350

Performing Calculations Basic calculations such as arithmetic calculation can be performed by math operators OperatorName of the operatorDescription +AdditionAdds two numbers -SubtractionSubtracts one number from another *MultiplicationMultiplies one number by another /DivisionDivides one number by another and gives the quotient %ModulusDivides one number by another and gives the remainder Other calculations: Use Math class’s methods. Example: Math.Pow(x, y) double x = 3.0, y = 2.0, z; z=Math.Pow(x,y);

Formula to Expression

Increment/Decrement Operators ++IncrementAdds 1 to the operand (x = x + 1). -- DecrementSubtracts 1 from the operand (x = x - 1). int x = 14; int y = 8; Int z = 10; int result7 = --y; // result7 = 7 int result8 = ++x; // result8 = 15, x = 15 ++z; // z= 11 double a = 8.5; double b = 3.4; double result15 = --a; // result15 = 7.5 double result16 = ++b; // result16 = 4.4

Compound (Shortcut) Operators Operator += Adding the operand to the starting value of the variable. -= Subtracting the operand from the starting value of the variable. *= Multiplying the operand by the starting value of the variable. /= Dividing the operand by the starting value of the variable. %= Remainder after dividing the right operand by the value in the variable.

Decrement/Increment by 1 private void button1_Click(object sender, EventArgs e) { int myInt; myInt = int.Parse(textBox1.Text); // myInt-=1; // myInt = --myInt; --myInt; textBox1.Text = myInt.ToString(); } private void button2_Click(object sender, EventArgs e) { int myInt; myInt = int.Parse(textBox1.Text); //myInt += 1; //myInt = ++myInt; ++myInt; textBox1.Text = myInt.ToString(); }

Decrement/Increment by any Step Value private void button1_Click(object sender, EventArgs e) { int stepValue; stepValue = int.Parse(textBox2.Text); int myInt; myInt = int.Parse(textBox1.Text); myInt -= stepValue; // myInt = myInt - stepValue; textBox1.Text = myInt.ToString(); } private void button2_Click(object sender, EventArgs e) { int stepValue; stepValue = int.Parse(textBox2.Text); int myInt; myInt = int.Parse(textBox1.Text); myInt += stepValue; // myInt = myInt + stepValue; textBox1.Text = myInt.ToString(); }

Prefix/Postfix Increment/Decrement Operators int a = 5; int b = 5; int y = ++a; // a = 6, y = 6 int z = b++; // b = 6, z = 5 When you use an increment or decrement operator as a prefix to a variable, the variable is incremented or decremented and then the result is assigned. When you use an increment or decrement operator as a postfix to a variable, the result is assigned and then the variable is incremented or decremented.

Counter Example: Keep track the number of times a user clicks a button Need to declare a variable: int Counter=0; Need to increase the counter by 1 when the button is clicked: Counter = Counter + 1; // Or Counter+=1; // Or ++Counter; Question: Where to declare this variable?

Example int Counter = 0; private void button1_Click(object sender, EventArgs e) { Counter = Counter + 1; textBox1.Text = Counter.ToString(); } private void button1_Click(object sender, EventArgs e) { int Counter = 0; Counter = Counter + 1; textBox1.Text = Counter.ToString(); } Incorrect: Correct:

Variable Scope The scope of a variable determines its visibility to the rest of a program. –Procedural-level scope: declared in a procedure and visible only in the procedure. –Class-level scope: declared in a class but outside any procedure; visible to all procedures in the class.

Decision Structure

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 <= % tax Taxable income > % 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 OperatorMeaningExpressionMeaning >Greater thanx > yIs x greater than y? <Less thanx < yIs x less than y? >=Greater than or equal tox >= yIs x greater than or equal to y? <=Less than or equal tox <= yIs x less than or equal to you? ==Equal tox == yIs x equal to y? !=Not equal tox != yIs 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 Wear a coat True False

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

Tuition Rules (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 = ; if (units > 12) { tuition = * (units - 12); } textBox2.Text = tuition.ToString("C"); }

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

Tuition Rules (2) If total units <= 12, then tuition = 1200 Otherwise, tuition = per additional unit private void button1_Click(object sender, EventArgs e) { int units; double tuition; units = int.Parse(textBox1.Text); if (units <= 12) tuition = ; else tuition = * (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; netPay = totalSales * (1 - discountRate); myMsg = "Thank you very much!"; } textBox2.Text = netPay.ToString("C"); MessageBox.Show(myMsg); }

Throwing an Exception I n 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 default error message: catch (Exception ex) { MessageBox.Show(ex.Message); } try { 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."): }

Use Try/Catch to Detect Data Syntax Error try { 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; netPay = totalSales * (1 - discountRate); myMsg = "Thank you very much!"; } textBox2.Text = netPay.ToString("C"); MessageBox.Show(myMsg); } catch (Exception ex) { MessageBox.Show(ex.Message); }

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.

Complex Condition with Logical Operators The logical AND operator (&&) and the logical OR operator (||) allow you to connect multiple Boolean expressions to create a compound expression The logical NOT operator (!) reverses the truth of a Boolean expression OperatorMeaningDescription &&ANDBoth subexpression must be true for the compound expression to be true ||OROne or both subexpression must be true for the compound expression to be true !NOTIt negates (reverses) the value to its opposite one. ExpressionMeaning x >y && a < bIs x greater than y AND is a less than b? x == y || x == zIs x equal to y OR is x equal to z? ! (x > y)Is the expression x > y NOT true?

Logical Operators: &&, ||, ! && Cond1Cond2Cond1 && Cond2T TF FTF || Cond1Cond2Cond1 || Cond2T TF FTF ! Cond! Cond T F

Examples Write a complex condition for: 12 <= Age <= 65 Use a complex condition to describe age not between 12 and 65. X <= 15 is equivalent to: X<15 AND X =15? (T/F)

More Complex Conditions University admission rules: Applicants will be admitted if meet one of the following rules: – 1. Income >= 100,000 – 2. GPA > 2.5 AND SAT > 900 An applicant’s Income is 150,000, GPA is 2.9 and SAT is 800. Admitted? – Income >= 100,000 OR GPA > 2.5 AND SAT >900 How to evaluate this complex condition? – AND has higher priority

Scholarship: Business students with GPA at least 3.2 and major in Accounting or CIS qualified to apply: – 1. GPA >= 3.2 – 2. Major in Accounting OR CIS Is a CIS student with GPA = 2.0 qualified? – GPA >= 3.2 AND Major = “Acct” OR Major = “CIS” Is this complex condition correct? – Parenthesis, ( )

NOT Set 1: Young: Age < 30 Set 2: Rich: Income >= 100,000 YoungRich

Young: Age private void button1_Click(object sender, EventArgs e) { double Age, Income; Age = double.Parse(textBox1.Text); Income = double.Parse(textBox2.Text); if (Age ) MessageBox.Show("You are young and rich"); else MessageBox.Show("You are not young or not rich"); }

Boolean (bool) Variables and Flags You can store the values true or false in bool variables, which are commonly used as flags A flag is a variable that signals when some condition exists in the program – False – indicates the condition does not exist – True – indicates the condition exists Boolean good; // bool good; if (mydate.Year == 2011) { good = true; } else { good = false; } MessageBox.Show(good.ToString());

Using Boolean Variables and && private void button1_Click(object sender, EventArgs e) { bool Young=false, Rich=false; double Age, Income; Age = double.Parse(textBox1.Text); Income = double.Parse(textBox2.Text); if (Age < 30) Young = true; if (Income > ) Rich = true; if (Young && Rich) MessageBox.Show("You are young and rich"); else MessageBox.Show("You are not young OR not rich"); }

Using Boolean Variables and || private void button1_Click(object sender, EventArgs e) { bool Young=false, Rich=false; double Age, Income; Age = double.Parse(textBox1.Text); Income = double.Parse(textBox2.Text); if (Age < 30) Young = true; if (Income > ) Rich = true; if (Young || Rich) MessageBox.Show("You are young OR rich"); else MessageBox.Show("You are not young and not rich"); }

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 if (expression) { } … else { } int 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"); }

if-else-if Example private void button1_Click(object sender, EventArgs e) { bool Young=false, Rich=false; double Age, Income; Age = double.Parse(textBox1.Text); Income = double.Parse(textBox2.Text); if (Age < 30) Young = true; if (Income > ) Rich = true; if (Young && Rich) MessageBox.Show("You are young and rich"); else if (Young && !Rich) MessageBox.Show("You are young but not rich"); else if (!Young && Rich) MessageBox.Show("You are not young but rich"); else MessageBox.Show("You are not young and not rich"); }

Working with DateTime Get current date: – DateTime thisDate=DateTime.Today; Get current date and time: – DateTime thisDate=DateTime.Now; Calculate # of days between two dates: – myDate = DateTime.Parse(textBox1.Text); – DaysBetween = thisDate.Subtract(myDate).Days;

Compute Age Given DOB: Age =65, Old DateTime myDate, thisDate=DateTime.Today; double Age; myDate = DateTime.Parse(textBox1.Text); Age = (thisDate.Subtract(myDate).Days / 365); MessageBox.Show(Age.ToString()); If (Age<30) MessageBox.Show(“Young”); elseif (Age<65) MessageBox.Show(“Middle”); else MessageBox.Show(“Old”);

Date Comparison DateTime thisDate, currentDate = DateTime.Today; thisDate = DateTime.Parse(textBox1.Text); if (currentDate>thisDate) MessageBox.Show("after"); else MessageBox.Show("before");