control structures: getting started sequence and selection also arithmetic operators, data types,...

30
Control Structures: Getting Started Sequence and Selection also arithmetic operators, data types, logical operators

Post on 21-Dec-2015

230 views

Category:

Documents


1 download

TRANSCRIPT

Control Structures: Getting Started

Sequence and Selection also arithmetic operators, data types,

logical operators

Introduction• Structured Programming: techniques that

bring clarity in developing and modifying programs.

• Algorithms: Set of instructions and the order in which they are to be executed (e.g. showerdressed)

Pseudocode

• An almost English language that helps programmers to develop algorithms and plan code

• Used to describe executable statements

• Executable statements are actions

• Non-executable statements include variable declarations and comments

• E.g. Assign 0 to counter vs. counter=0

Arithmetic operators

• Most of you know (+, -, *,

• / is floating point division 7 / 4 = 1.75

• \ is integer division 7 \ 4 = 1

• Mod is modulus

• ^ is exponent

• Rules of operator precedence (also called order of operations): ( ), ^, pos and neg, * and /, \, mod, +, -

Common primitive data types

• Boolean• Byte• Date• Decimal• String• Integer• Single• Long• Char • Double

Control Structures

A payroll company calculates the gross earnings per week of employees. Employees’ weekly salaries are based on the number of hours they worked and their hourly wages.

For the first 40 hours, employees earn their hourly rate

Anything above 40, employees earn 1.5* their hourly rate

overtTime pay = (HoursWorked-40) * (1.5*HourlyRate)

Control Structures

• Sequence, Selection, Repetition (Iteration)

• Sequence– E.g. A B C D– A transfer of control occurs when an

executed statement does not directly follow the previous statement

Control Structures• Selection (IF…Then, IF…Then…Else,

Select case)– If (income>expenses) THEN buy ipod ELSE

wait– Returns Boolean data type (True/False)

• Iteration (or repetition) – While…End While, Do While…Loop, Do…

Loop While, Do Until…Loop, Do…Loop Until, For…Next, and For Each…Next

Operators

• In order to evaluate a condition for a selection statement need relational and equality operators

> < >= <= = <> += -= *= /= \= ^=

• Control structures can be nested and stacked.

Selection

If-then, If-then-Else, Case Select

Nested if then else pseudocode

If student’s grade is greater than or equal to 90

Display “A”

Else

If student’s grade is greater than or equal to 80

Display “B”

Else

If student’s grade is greater than or equal to 70

Display “C”

Else

If student’s grade is greater than or equal to 60

Display “D”

Else

Display “F”

Back to Salary Problem

Problem: Input (Hours/wages) Calculate (salary) Display (earnings)

Pseudocode:-Get hours worked and hourly wages from the textbox-If hours worked are less than or equal to 40

Gross earnings equals hours worked times hourly wages

-ElseGross earnings equals 40 times hourly wage plus hours above 40 times wage and a half

-Display gross earnings

Dim wage, gross As Decimal Dim hours As Double Const HOUR_LIMIT As Integer = 40

If hours <= HOUR_LIMIT Then gross = wage * hours Else gross = HOUR_LIMIT * wage gross += (hours - HOUR_LIMIT) * wage * 1.5 End If

Another If-then Example

Dental Office Billing Application

• Calculate charge based on selected procedures

• Calculate the total charges

How such an application may look

Dental Payment Pseudocode

When user clicks calculateIf “Cleaning” Checkbox is selected

Add cost of a cleaning to totalIf “Cavity filling” Checkbox is selected

Add cost of receiving filling to the total

If “X-Ray” Checkbox is selectedAdd cost of receiving X-Ray to

the totalDisplay total

Dental Payment Partial Code

If cleanCheckBox.Checked = True Then total += 35End If

If cavityCheckBox.Checked = True Then total += 150End If

If xrayCheckBox.Checked = True Then total += 85End If

Logical Operators• AndAlso = both conditions must be true

• OrElse = either or both are true

• Xor = one condition must be true and the other must be false

Logical OperatorsIf gender = Female AndAlso age>= 65 then

seniorFemales +=1

Adds one if individual is both female and >= 65

If gender = Female OrElse age>= 65 then

seniorFemales +=1

Adds 1 if the individual female, if he or she is >= 65 or both

Logical Operators

If gender = Female Xor age>= 65 then

seniorFemales +=1

Would add 1 if individual if

• Individual is male but >=65

• Individual is female but < 65

Would not add one if both conditions were true or both were false

Logical Operators

Not = enables the programmer to reverse the meaning of a condition

If not (grade = value) then…If (grade <> value)

Don’t use this unless you really have to…it can be very confusing to follow…

Addition assignment operator

• Count += 1

• Same as: count = count + 1

• You may use either

• Also Count -= 1 decrements the value stored in count by 1

Another Selection option: Select Case

• Useful when there are many different options – it is a multiple selection statement

• Can take the place of layers of nested or stacked ifs. This is much preferred over too many nested ifs (more than 3 layers)

• The expression following the keywords Select Case is called the controlling expression

Case Statements

• Conditions are checked in the case statements

• Multiple values tested in a single case statement are separated by a comma

Select Case ExampleSelect Case Grade

Case “A”Display = “Excellent”

Case “B” Display = “Very Good”

Case “C” Display = “Good”

Case “D” Display = “Poor”

Case “F” Display = “Failure”

End Select

Case Else

• Case Else can be helpful with error checking

• But be careful where you use it. Using before any of your Case Statements results in a syntax error

ElseIf vs. Select Case

If grade =“A” ThendisplayLable.Text=“Excellent”

ElseIf grade=“B” ThendisplayLabel.Text=“Very Good”

ElseIf grade=“C” ThendisplayLabel.Text=“Good”

ElseIf grade=“D” ThendisplayLabel.Text=“Poor”

ElseIf grade=“F” ThendisplayLabel.Text=“Failure”

ElsedisplayLabel.Text=“Invalid Grade”

End If

Select case gradeCase “A” displayLabel.Text=“Excellent”

Case “B” displayLabel.Text=“Very Good”

Case “C” displayLabel.Text=“Good”

Case “D” displayLabel.Text=“Poor”

Case “F” displayLabel.Text=“Failure”

Case Else displayLabel.Text=“Invalid Grade”

End Select

Select Case Options• Case Is < 10• message = "restricted access"• Case 1645 To 1689• message = "technitions"• Case 8345• message = "custodians"• Case 9998, 1006 To 1008• message = "scientists"• Case Else• message = "access denied"• End Select

Bad Case Statement

• Case 51 To 30

• Here the case statement is ignored and may result in a logic error

Try the following• Write a select statement that tells the user

to purchase a book if it is less than $50 otherwise keep searching

• Write a select statement that chooses a dollar amount to charge a customer based on an order: Hamburger = $1.50, Double Cheeseburger = 2, Fries = $1, Onion Rings = $1.5, Drink = $1. Allow the customer to order as much as he or she wants.