Lesson 04 Control Structures I : Decision Making MIT 31043, VISUAL PROGRAMMING Senior Lecturer in MIT Department of MIT Faculty of Management and Commerce South Eastern University of Sri Lanka
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 o A specific action is performed only if a certain condition exists o 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; Statements; etc.; Cold outside False True Wear a coat The expression is a Boolean expression that can be evaluated as either true or false
Relational Operators A relational operator determines whether a specific relationship exists between two values Operator Meaning Expression Meaning > 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?
Examples that use relational operators strfirstname == "Rapid" // equal to a string literal yearstextbox.text == "" // equal to an empty string strmessage == String.Empty // equal to an empty string dbldiscountpercent == 2.3 // equal to a numeric literal blnisvalid == false // equal to the false value deccode == decproductcode // equal to another variable strlastname!= "Apps" dblyears > 0 inti < intmonths // not equal to a string literal // greater than a numeric literal // less than a variable dblsubtotal >= 500 // greater than or equal to // a literal value intquantity <= intreorderpoint // less than or equal to // a variable Slide 5
BRANCHING Slide 6
BRANCHING Branching is the act of controlling which line of code should be executed next. The line to jump to is controlled by some kind of conditional statement. This conditional statement is based on a comparison between a test value and one or more possible values using Boolean logic. This section describes three branching techniques available in C#: o The ternary operator o The if statement o The switch statement Slide 7
The Ternary Operator The simplest way to perform a comparison is to use the ternary (or conditional) operator; this operator works on three operands. Slide 8
The if Statement The if statement is a far more versatile and useful way to make decisions. Unlike the ternary operator, if statements don t have a result (so you can t use them in assignments); instead, you use the statement to conditionally execute other statements. Slide 9
The if Statement The simplest use of an if statement is as follows, where <test> is evaluated (it must evaluate to a Boolean value for the code to compile) and the line of code that follows the statement is executed if <test> evaluates to true: if (sales > 50000) bonus = 500; if (sales > 50000) bonus = 500; sales > 50000 True False bonus = 500 Slide 10
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 Both sections of code can span multiple lines using blocks in braces: You can also specify additional code using the else statement in combination with an if statement. This statement is executed if <test> evaluates to false: Slide 11
Example of if-else Statement False temp >40 True display cold display hot if (temp > 40) MessageBox.Show( hot ); else MessageBox.Show( cold );
Example Slide 13
Checking More Conditions Using if Statements 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 Slide 14
Checking More Conditions Using if Statements Slide 15
Improved Marks Processor Slide 16
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 Operator Meaning Description && AND Both subexpression must be true for the compound expression to be true OR One or both subexpression must be true for the compound expression to be true! NOT It negates (reverses) the value to its opposite one. Expression Meaning x >y && a < b Is x greater than y AND is a less than b? x == y x == z Is 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 < 20 && minutes > 12) MessageBox.Show( The temperature is in the danger zone. ); The operator if (temperature < 20 temperature > 100) MessageBox.Show( The temperature is in the danger zone. ); The! Operator if (!(temperature > 100)) MessageBox.Show( The is below the maximum temperature. );
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: if (expression) if (expression) statements; else statements; else statements
A Sample Nested Decision Structure Salary >= 40000 Display Minimum salary requirement not met. yearsonjob >= 2 Display Minimum years at current job not met. Display You qualify for the load. End Slide 20
A Sample Nested Decision Structure if (salary >= 40000) else if (yearonjob >= 2) decisionlabel.text = "You qualify for the loan." else decisionlabel.text = "Minimum years at current " + "job not met." decisionlabel.text = "Minimum salary requirement " + "not met."
A Sample Nested Decision Structure if (strcustomertype == "R") if (dblsubtotal >= 100) decdiscountpercent =.2m; else decdiscountpercent =.1m; else // customertype isn't "R" decdiscountpercent =.4m; Slide 22
Example This program checks if the mark s range is above 100 or below 0 (zero). If the mark is out of range (0-100), an error message is show using the MessageBox. If it is within the range, calculation is executed. Slide 23
Example Slide 24
switch
The switch Multiple-Selection Statement C# provides the switch multiple-selection statement to perform different actions based on the possible values of an expression. Each action is associated with the value of a constant integral expression or a constant string expression that the variable or expression on which the switch is based may assume. A constant integral expression is any expression involving character and integer constants that evaluates to an integer value or a constant. A constant string expression is any expression composed of string literals that always results in the same string. A switch statement compares ONE variable against MULTIPLE possible values Slide 26
The syntax of the switch statement Supported data types: bool, char, String, integral, or enum Slide 27
Sample switch Statement switch (month) case 1: MessageBox.Show( January ); break; case 2: MessageBox.Show( February ); break; month case 3: MessageBox.Show( March ); break; Display January Display February Display March Display Error: Invalid month default: MessageBox.Show( Error: Invalid month ); break;
switch Example I: Lottory Slide 29
switch Example II: Month Finder Slide 30
A switch statement that falls through the first case label switch (strcustomertype) case "R": case "C": decdiscountpercent =.2m; break; case "T": decdiscountpercent =.4m; break; Slide 31
GUI Design Slide 32
GUI CheckBox A small area on a computer screen which, when selected by the user, shows that a particular feature has been enabled. A CheckBox control allows users to select a single or multiple options from a list of options. A typical CheckBox control has two possible states: o Checked state is when the CheckBox has check mark on o Unchecked is when the CheckBox is not checked Typically, we use a mouse to check or uncheck a CheckBox Checked property is true when a CheckBox is in checked state Slide 33
GUI CheckBox Slide 34
CheckedChanged Event Like the Click event for a button, the checkbox has CheckedChanged as its default event. The CheckedChanged event occurs when the value of the Checked property changes Slide 35
GUI RadioButton A RadioButton control provides a round interface to select one option from a number of options. Radio buttons are usually placed in a group on a container control such as a Panel or a GroupBox and one of them is selected. A typical RadioButton control has two possible states: o Checked state is when the button has check mark on o Unchecked is when the button is not checked Typically, we use a mouse to check or uncheck Checked property is true when a radiobutton is in checked state At a time only one radiobutton can be selected within a container Slide 36
GUI RadioButton Slide 37
GUI - PictureBox You can display images on your form by using the PictureBox control. It is a simple control which has a main purpose of displaying images. All you have to do is browse for the desired image and Visual Studio will import it to your project. You can use several image formats such as JPEG, GIF, PNG, and BMP. Properties Image ImageLocation SizeMode Description The image that will be displayed by the control. The path of the image to be displayed by the PictureBox. Tells how the image will be displayed. Slide 38
GUI PictureBox To display an image using the PictureBox control, there are multiple ways you can use. You can go to the Properties Window and find the Image property. Click the button to the right of it to bring out the Select Resource Dialog. Slide 39
GUI PictureBox Once the image is displayed, it may not look like you want it to. If the loaded image is larger the size of the PictureBox, then the image will be clipped. You can use the SizeMode property to change the way the image is positioned or resized inside the control. PictureBoxSizeMode Description Normal StretchImage AutoSize The image will be positioned in the upper-left corner of the PictureBox and if the image is larger than the PictureBox, the image will be clipped. Resizes the image to match the size of the PictureBox. Resizes the PictureBox to match the size of the image. CenterImage Zoom The image is centered inside the PictureBox. If the image is larger than the PictureBox, the image will be clipped. Fits the whole image inside the PictureBox while maintaining the image s size ratio. Slide 40
THANK YOU Slide 41