Copyright © 2012 Pearson Education, Inc. Chapter 4 Making Decisions.

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Making Decisions and Working With Strings
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Microsoft Visual Basic: Reloaded Chapter Five More on the Selection Structure.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Chapter 5: More on the Selection Structure Programming with Microsoft Visual Basic.NET, Second Edition.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 4 Making Decisions
Visual C++ Programming: Concepts and Projects
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Decision Structures and Boolean Logic
Chapter 4: Making Decisions. Understanding Logic-Planning Tools and Decision Making Pseudocode – A tool that helps programmers plan a program’s logic.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design First Edition by Tony Gaddis.
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;
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 4 Decision.
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.
Chapter 3:Decision Structures.  3.1 The if Statement  3.2 The if-else Statement  3.3 The if-else-if Statement  3.4 Nested if Statements  3.5 Logical.
Chapter 5: More on the Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition.
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.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Decision Structure - 2 ISYS 350. Complex Condition with Logical Operators The logical AND operator (&&) and the logical OR operator (||) allow you to.
Chapter 5: More on the Selection Structure
Programming with Microsoft Visual Basic th Edition
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.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Chapter Making Decisions 4. Relational Operators 4.1.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
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.
Chapter Five More on the Selection Structure Programming with Microsoft Visual Basic th Edition.
Decision Structure - 1 ISYS 350. Decision: Action based on condition Examples Simple condition: – If total sales exceeds $300 then applies 5% discount;
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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,
Decision Structure - 2 ISYS 350.
Decision Structure ISYS 350.
Decision Structure - 1 ISYS 350.
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Decision Structures and Boolean Logic
Chapter 4: Making Decisions.
Decision Structure - 2 ISYS 350.
Decision Structure - 1 ISYS 350.
Topics The if Statement The if-else Statement Comparing Strings
Lesson 04 Control Structures I : Decision Making
Work with Data and Decision Structure
Decision Structure - 2 ISYS 350.
Chapter 3:Decision Structures
Chapter 4: Decision Structures and Boolean Logic
Decision Structures ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure - 1 ISYS 350.
Decision Structure - 2 ISYS 350.
Decision Structure - 1 ISYS 350.
Chapter 4: Decision Structures and Boolean Logic
Presentation transcript:

Copyright © 2012 Pearson Education, Inc. Chapter 4 Making Decisions

Topics 4.1 Decision Structures and the if Statement 4.2 The if-else Statement 4.3 Nested Decision Structures 4.4 Logical Operators 4.5 bool Variables and Flags 4.6 Comparing Strings 4.7 Preventing Data Conversion Exceptions with the TryParse Method 4.8 Input Validation 4.9 Radio Buttons and CheckBoxes 4.10 The switch Statement 4.11 Introduction to List Boxes Copyright © 2012 Pearson Education, Inc.

4.1 Decision Structures A control structure is a logical design that controls the order in which statements execute A sequence structure is a set of statements that execute in the order that they appear A decision structure execute statements only under certain circumstances –A specific action is performed only if a certain condition exists –Also known as a selection structure

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 Copyright © 2012 Pearson Education, Inc. Cold outside Wear a coat True False

Relational Operators A relational operator determines whether a specific relationship exists between two values Copyright © 2012 Pearson Education, Inc. 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?

if Statement with Boolean Expression Copyright © 2012 Pearson Education, Inc. if (sales > 50000) { bonus = 500; } sales > bonus = 500 True False

4.2 The if-else statement An if-else statement will execute one block of statement if its Boolean expression is true or another block if its Boolean expression is false It has two parts: an if clause and an else clause In C#, a generic format looks: if (expression) { statements; } else { statements; } Copyright © 2012 Pearson Education, Inc.

Example of if-else Statement Copyright © 2012 Pearson Education, Inc. temp >40 display “hot”display “cold” TrueFalse if (temp > 40) { MessageBox.Show(“hot”); } else { MessageBox.Show(“cold”); }

4.3 Nested Decision Structures You can create nested decision structures to test more than one condition. Nested means “one inside another” In C#, a generic format is: Copyright © 2012 Pearson Education, Inc. if (expression) { if (expression) { statements; } else { statements; } else { statements }

A Sample Nested Decision Structure if (salary >= 40000) { if (yearOnJob >= 2) { decisionLabel.Text = "You qualify for the load." } else { decisionLabel.Text = "Minimum years at current " + "job not met." } else { decisionLabel.Text = "Minimum salary requirement " + "not met." } Copyright © 2012 Pearson Education, Inc. Salary >= yearsOnJob >= 2 Display “Minimum salary requirement not met.” Display “You qualify for the load.” Display “Minimum years at current job not met.” End

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 { } Copyright © 2012 Pearson Education, Inc. 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"); }

4.4 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 Copyright © 2012 Pearson Education, Inc. 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?

Sample Decision Structures with Logical Operators The && operator if (temperature 12) { MessageBox.Show(“The temperature is in the danger zone.”); } The || operator if (temperature 100) { MessageBox.Show(“The temperature is in the danger zone.”); } The ! Operator if (!(temperature > 100)) { MessageBox.Show(“The is below the maximum temperature.”); } Copyright © 2012 Pearson Education, Inc.

4.5 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 Copyright © 2012 Pearson Education, Inc. if (grandMaster) { powerLevel += 500; } If (!grandMaster) { powerLevel = 100; }

4.6 Comparing Strings You can use certain relational operators and methods to compare strings. For example, –The == operator can compare two strings string name1 = “Mary”; string name2 = “Mark”; if (name1 == name2) { } –You can compare string variables with string literals, too if (month ! = “October”) { } –The String.Compare method can compare two strings string name1 = “Mary”; string name2 = “Mark”; if (String.Compare(name1, name2) == 0) { } Copyright © 2012 Pearson Education, Inc.

4.7 Preventing Data Conversion Exception Exception should be prevented when possible The TryParse methods can prevent exceptions caused by users entering invalid data –int.TryParse –doubel.TryParse –decimal.TryParse The generic syntax is: int.TryParse(string, out targetVariable) The out keyword is required; it specifies that the targetVariable is an output variable Copyright © 2012 Pearson Education, Inc.

Samples of TryParse Methods // int.TryParse int number; if (int.TryParse(inputTextBox.Text, out number)) { } else { } //double.TryParse double number; if (double.TryParse(inputTextBox.Text, out number)) { } else { } //decimal.TryParse decimal number; if (decimal.TryParse(inputTextBox.Text, out number)) { } else { } Copyright © 2012 Pearson Education, Inc.

4.8 Input Validation Input validation is the process of inspecting data that has been entered into a program to make sure it is valid before it is used TryParse methods check if the user enters the data, but it does not check the integrity of the data. For example, –In a payroll program we might validate the number of hours worked. if (hours > 0 && hours <= 168) { } else { } –In a program that gets test scores, we can limits its data to an integer range of 0 through 100. if (testScore >= 0 && testScore <=100) { } else { } Copyright © 2012 Pearson Education, Inc.

4.9 Radio Buttons and Check Boxes Radio buttons allow users to select one choice from several possible choices –Clicking on a radio button, the program automatically deselects any others. This is known as mutually exclusive selection Check boxes allows users to select multiple options Copyright © 2012 Pearson Education, Inc.

RadioButton Control The.NET Framework provides the RadioButton Control for you to create a group of radio buttons Common properties are: –Text: holds the text that is displayed next to the radio button –Checked: a Boolean property that determines whether the control is selected or deselected Copyright © 2012 Pearson Education, Inc.

Working with Radio Buttons in Code In code, use a decision structure to determine whether a RadioButton is selected. For example, If (choiceRadioButton.Checked) { } else { } You do not need to use the == operator, although the following is equivalent to the above If (choiceRadioButton.Checked == true) { } else { } Copyright © 2012 Pearson Education, Inc.

CheckBox Control The.NET Framework provide the CheckBox Control for you to give the user an option, such as true/false or yes/no Common properties are: –Text: holds the text that is displayed next to the radio button –Checked: a Boolean property that determines whether the control is selected or deselected In code, use a decision structure to determine whether a CheckBox is selected. For example, If (option1CheckBox.Checked) { } else { } Copyright © 2012 Pearson Education, Inc.

The CheckedChanged Event Anything a RadioButton or a CheckBox control’s Checked property changes, a CheckedChanged event is raised You can create a CheckedChanged event handler and write codes to respond to the event Double click the control in the Designer to create an empty CheckedChanged event handler similar to: private void yellowRadioButton_CheckedChanged(object sender, EventArgs e) { } Copyright © 2012 Pearson Education, Inc.

4.10 The switch Statement The switch statement lets the value of a variable or an expression determine which path of execution the program will take It is a multiple-alternative decision structure It can be used as an alternative to an if-else-if statement that tests the same variable or expression for several different values Copyright © 2012 Pearson Education, Inc.

Generic Format of switch Statement swtich (testExpression) { case value_1: statements; break; case value_2: statements; break; … case value_n: statements; break; default: statements; break; } Copyright © 2012 Pearson Education, Inc. The testExpression is a variable or an expression that given an integer, string, or bool value. Yet, it cannot be a floating-point or decimal value. Each case is an individual subsection containing one or more statements, followed by a break statement The default section is optional and is designed for a situation that the testExpression will not match with any of the case

Sample switch Statement switch (month) { case 1: MessageBox.Show(“January”); break; case 2: MessageBox.Show(“February”); break; case 3: MessageBox.Show(“March”); break; default: MessageBox.Show(“Error: Invalid month”); break; } Copyright © 2012 Pearson Education, Inc. month Display “January” Display “February” Display “March” Display “Error: Invalid month”

4.11 Introduction to List Boxes A list box displays a list of items and allow the user to select an item from the list In C#, you can use the ListBox control to create a list box Commonly used properties are: –Text: Gets or searches for the text of the currently selected item in the ListBox –Items: Gets the items of the ListBox –SelectedItem: Gets or sets the currently selected item in the ListBox. When the user selects an item, the item is stored in this property. You can use the following to get the selected item from a list box: selectedFruit = fruitListBox.SelectedItem.ToString(); –SelectedIndex: Gets or sets the zero-based index of the currently selected item in a ListBox Copyright © 2012 Pearson Education, Inc.

SelectedItem An exception will occur if you try to get the value of a ListBox’s SelectedItem property when no item is selected Items in a list box have an index starting with 0 –The first item has index 0, the nth item has index n-1 –The SelectedIndex property keeps the index. If no item is selected the, value of SelectedIndex is -1 The following is an example to use SelectedIndex property to make sure that an item is selected before you get the value from SelectedItem. if (fruitListBox.SelectedIndex != -1) { } Copyright © 2012 Pearson Education, Inc.