slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Wage Calculator Application Introducing Algorithms, Pseudocode and Program Control PowerPoint Presentation
Download Presentation
Wage Calculator Application Introducing Algorithms, Pseudocode and Program Control

Loading in 2 Seconds...

play fullscreen
1 / 85

Wage Calculator Application Introducing Algorithms, Pseudocode and Program Control - PowerPoint PPT Presentation

  • Uploaded on

7. Wage Calculator Application Introducing Algorithms, Pseudocode and Program Control. Outline. 7.1 Test-Driving the Wage Calculator Application 7.2 Algorithms 7.3 Pseudocode 7.4 Control Structures 7.5 If...Then Selection Statement

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Wage Calculator Application Introducing Algorithms, Pseudocode and Program Control' - Mercy

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
  • Wage Calculator Application
  • Introducing Algorithms,Pseudocode andProgram Control
  • 7.1 Test-Driving the WageCalculator Application
  • 7.2 Algorithms
  • 7.3 Pseudocode
  • 7.4 Control Structures
  • 7.5If...Then Selection Statement
  • 7.6If...Then...Else Selection Statement and Conditional If Expressions
  • 7.7 Constructing the WageCalculator Application
  • 7.8 Assignment Operators
  • 7.9 Formatting Text
  • 7.10 Using the Debugger: The Watch Window
In this tutorial you will learn:

Understand basic problem-solving techniques.

Understand control structures.

Understand and create pseudocode.

Use the If...Then and If...Then...Else selection statements to choose among alternative actions.

Use the assignment operators.

Use the debugger’s Watch window.

  • Structured programming
    • A technique for organizing program control that helps you develop applications that are clear and easier to debug and modify.
    • Applicable to most high-level languages, including Visual Basic.
7 1 test driving the wage calculator application
7.1 Test-Driving the Wage Calculator Application

Application Requirements

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. The application assumes a standard work week of 40 hours. The wages for 40 or fewer hours are calculated by multiplying the employee’s hourly wage by the number of hours worked. Any time worked over 40 hours in a week is considered “overtime” and earns time and a half. The total overtime earned is added to the user’s gross earnings for the regular 40 hours of work to calculate the total earnings for that week.

  • This application calculates earnings from hourly wage and hours worked per week.
7 1 test driving the wage calculator application cont
7.1 Test-Driving the Wage CalculatorApplication (Cont.)
  • To organize the GUI, we vertically aligned the TextBoxes on their right sides and made the TextBoxes the same size (Fig 7.1).
  • We also left aligned the TextBoxes’ descriptive Labels.

Figure 7.1|Wage Calculator application.

gui design tip
GUI Design Tip
  • When using multiple TextBoxes vertically, align the TextBoxes on their right sides, and where possible make the TextBoxes the same size. Left align the descriptive Labels for such TextBoxes.
7 1 test driving the wage calculator application cont1
7.1 Test-Driving the Wage CalculatorApplication (Cont.)
  • The employee’s earnings are the sum of the wages for the standard 40-hour work week (40*10) and the overtime pay (5*10*1.5)(Fig 7.2).

Figure 7.2| Calculating wages by clicking the CalculateButton.

7 2 algorithms
7.2 Algorithms
  • Computing problems can be solved by executing a series of actions in a specific order.
  • A procedure for solving a problem, called an algorithm, deals with:
    • the actions to be executed and
    • the order in which these actions are to be executed
7 2 algorithms cont
7.2 Algorithms (Cont.)
  • The following example demonstrates the importance of correctly specifying the order in which the actions are to be executed. Consider the “rise-and-shine algorithm” followed by one junior executive for getting out of bed and going to work:
    • (1) get out of bed,
    • (2) take off pajamas,
    • (3) take a shower,
    • (4) get dressed,
    • (5) eat breakfast and
    • (6) carpool to work.
  • This routine prepares the executive for a productive dayat the office.
7 2 algorithms cont1
7.2 Algorithms (Cont.)
  • Suppose that the same steps are performed in a slightly different order:
    • (1) get out of bed,
    • (2) take off pajamas,
    • (3) get dressed,
    • (4) take a shower,
    • (5) eat breakfast,
    • (6) carpool to work.
7 2 algorithms cont2
7.2 Algorithms (Cont.)
  • In this case, our junior executive shows up for work soaking wet.
  • Indicating the appropriate sequence in which to execute actions is equally crucial in computer programs.
  • Programcontrol refers to the task of orderingan application’s statements correctly.
7 3 pseudocode
7.3 Pseudocode
  • Pseudocode is an informal language that helps you formulate algo­rithms.
    • It is convenient and user friendly
    • Not an actual computer-programming language.
  • Pseudocode statements are not executed on computers.
  • Helps you think out an application before attempting to write it in a programming language.
software design tip
Software Design Tip
  • Pseudocode helps you conceptualize an application during the application-design process. Pseudocode statements can be converted to Visual Basic at a later point.
7 3 pseudocode cont
7.3 Pseudocode (Cont.)
  • Example of a pseudocode statement:

Assign 0 to the counter

  • The pseudocode statement above can be converted to the following Visual Basic statement:

counter = 0

7 3 pseudocode cont1
7.3 Pseudocode (Cont.)
  • Pseudocode normally describes only executablestatements—the actions performed when the corresponding Visual Basic application is run.
  • An example of a programming statement that is not executed is a declaration.
7 4 control structures
7.4 Control Structures
  • Sequentialexecution
    • Normally, statements in an application are executed one after another in the order in which they are written.
  • transferof control
    • Occurs when an executed statement does not directly follow the previously executed statement in the written application.
  • All programs can be written in terms of only three control structures:
    • the sequence structure,
    • the selection structure and
    • the repetition structure.
7 4 control structures cont
7.4 Control Structures (Cont.)
  • The sequencestructure is built into Visual Basic—unless directed to act otherwise, the computer executes Visual Basic statements sequentially—that is, one after the other in the order in which they appear in the application.
7 4 control structures cont1
7.4 Control Structures (Cont.)
  • The activitydiagram in Fig. 7.3 illustrates a typical sequence structure, in which two calculations are performed in order.
  • Figure 7.3| Sequence structure activity diagram.
7 4 control structures cont2
7.4 Control Structures (Cont.)
  • Activity diagrams are part of the UnifiedModelingLanguage(UML)—an industry standard for modeling software systems.
  • An activity diagram models the activity (also called the workflow) of a portion of a software system.
7 4 control structures cont3
7.4 Control Structures (Cont.)
  • Activity diagrams are composed of special-purpose symbols, such as
    • the action-statesymbol (a rectangle with its left and right sides replaced with arcs curving outward)
    • the diamondsymbol and the smallcircle symbol
    • transitionarrows, which represent the flow of the activity.
  • Like pseudocode, activity diagrams help you develop and represent algorithms. Activity diagrams clearly show how control structures operate.
7 4 control structures cont4
7.4 Control Structures (Cont.)
  • The activity diagram in Fig. 7.3 contains two actionstates that represent actions to perform.
  • Each action state contains an actionexpression.
  • The arrows in the activity diagram are called transition arrows.
    • Represent transitions that indicate the order in which the actions represented by the action states occur.
  • The solidcircle located at the top of the activity diagram represents the activity’s initial state
    • The beginning of the workflow before the application performs the modeled activities.
7 4 control structures cont5
7.4 Control Structures (Cont.)
  • The solid circle surrounded by a hollow circle that appears at the bottom of the activity diagram represents the finalstate
    • The end of the workflow after the application performs its activities.
  • In Fig. 7.3, the rectangles with the upper-right corners folded over are called notes in the UML
    • Like comments in Visual Basic applications
    • Explanatory remarks that describe the purpose of symbols in the diagram.
    • A dottedline connects each note with the element that the note describes.
7 4 control structures cont6
7.4 Control Structures (Cont.)

Selection Structures

  • A condition is an expression with a true or false value that is used to make a decision.
  • Conditions are evaluated to determine whether their value is true or false.
  • These values are of data type Boolean
    • Specified in Visual Basic code by using the keywordsTrue and False.
  • Refer to a condition as a Boolean expression.
7 4 control structures cont7
7.4 Control Structures (Cont.)
  • Visual Basic provides three types of selectionstructures.
  • The If...Then selection structure performs (selects) an action (or sequence of actions) based ona condition.
    • If the condition evaluates to True, the actions specified by the If...Then structure are executed.
    • If the condition evaluates to False, the actions specified by the If...Then structure are skipped.
7 4 control structures cont8
7.4 Control Structures (Cont.)
  • The If...Then...Else selection structure
    • …performs an action (or sequence of actions) if a condition is true
    • …performs a different action (or sequence of actions) if the condition is false.
  • The SelectCase structure performs one of many actions (or sequences of actions), depending on the value of an expression.
7 4 control structures cont9
7.4 Control Structures (Cont.)
  • The If...Then structure is called a single-selectionstructure because it selects or ignores a single action (or a sequence of actions).
  • The If...Then...Else structure is called a double-selectionstructure because it selects between two different actions (or sequences of actions).
  • The SelectCase structure is called a multiple-selectionstructure because it selects among many different actions or sequences of actions.-
7 4 control structures cont10
7.4 Control Structures (Cont.)

Repetition Structures

  • Visual Basic provides seven types of repetitionstructures for performing a statement or groupof statements repeatedly:
    • While...EndWhile
    • DoWhile...Loop
    • DoUntil...Loop
    • Do...LoopWhile
    • Do...LoopUntil
    • For...Next
    • ForEach...Next
7 4 control structures cont11
7.4 Control Structures (Cont.)


  • The words If, Then, Else, End, Select, Case, While, Do, Until, Loop, For, Next and Each are all Visual Basic keywords—Appendix E includes a complete list of Visual Basic keywords.
7 4 control structures cont12
7.4 Control Structures (Cont.)

Control Structure Notes

  • Visual Basic has 11 control structures
    • the sequence structure,
    • three types of selection structures and
    • seven types of repetition structures.
    • All Visual Basic applications are formed by combining as many of each type of control structure as is necessary.
  • All Visual Basic control structures aresingle-entry/single-exitcontrolstructures
    • Each has exactly one entry point and one exit point.
7 4 control structures cont13
7.4 Control Structures (Cont.)
  • Control structures are attached to one another by connecting the exit point of one control structure to the entry point of the next.
    • Similar to stacking building blocks, so we call itcontrol-structurestacking.
    • The only other way to connect control structures is through control-structurenesting, whereby one control structure can be placed inside another.
7 5 if then selection statement
7.5 If...Then Selection Statement
  • A selection statement chooses among alternative courses of action in an application.

If student’s grade is greater than or equal to 60 Display “Passed”

  • The preceding pseudocode If statement may be written in Visual Basic as


7 5 if then selection statement cont
7.5 If...Then Selection Statement (Cont.)
  • The condition between keywords If and Then determines whether the statement(s) within theIf...Then statement will execute.
    • If the condition is true, the body of theIf...Then statement executes.
    • If the condition is false, the body is not executed.
common programming error
Common Programming Error
  • Omitting the Then keyword in an If...Then statement is a syntax error. The IDE helps prevent this error by inserting the Then keyword after you write the condition.
good programming practice
Good Programming Practice
  • Visual Basic indents the statements inside If...Then statements to improve readability.

7.5 If...Then Selection Statement (Cont.)

  • Conditions in If...Then statements can be formed by using the equalityoperators and relationaloperators(also called comparisonoperators), which are summarized in Fig. 7.4.

Figure 7.4| Equality and relational operators.

common programming error1
Common Programming Error
  • Adding spaces between the symbols in the operators <>, >= and <= (as in <>, >=, <=) is a syntax error that Visual Basic fixes automatically.
common programming error2
Common Programming Error
  • Reversal of the operators <>, >= and<= (as in ><, =>, =<) is a syntax error thatVisual Basic fixes automatically.

7.5 If...Then Selection Statement (Cont.)

  • Figure 7.5 shows the syntax of the If...Then statement.
  • A statement’s syntax specifies how the statement must be formed to compile.

Figure 7.5|If...Thenstatement syntax.


7.5 If...Then Selection Statement (Cont.)

  • Figure 7.6 illustrates the single-selection If...Then statement.
  • This activity diagram contains the diamond, or decisionsymbol, which indicates that a decision is to be made.
  • The two sets of square brackets above or next to the arrows leading from the decision symbol are called guardconditions.

Figure 7.6|If...Then single-selection statement activity diagram.


7.5 If...Then Selection Statement (Cont.)

  • A decision symbol indicates that the workflow continues along a path determined by the guard conditions, which can be true or false.
  • Each transition arrow emerging from a decision symbol has a guard condition.
    • If a particular guard condition is true, the workflow enters the action state to which that transition arrow points.
    • Only one guard condition associated with a particular decision symbol can be true at once.

7.6 If...Then...Else Selection Statementand Conditional If Expressions

  • The If...Then selection statement performs an indicated action only when the condition evaluates to True; otherwise, the action is skipped.
  • The If...Then...Else selection statement allows you to specify that a different action is to be performed when the condition is true than when the condition is false.

If student’s grade is greater than or equal to 60 Display “Passed” Else Display “Failed”

The preceding pseudocode may be written in Visual Basic as

If studentGrade >= 60Then displayLabel.Text = "Passed"Else displayLabel.Text = "Failed"End If

good programming practice1
Good Programming Practice
  • Indent both body statements of anIf...Then...Else statement to improve readability. [Note: The Visual Basic IDE does this automatically.]

7.6 If...Then...Else Selection Statementand Conditional If Expressions (Cont.)

  • A standard indentation convention should be applied consistently throughout your applications.
  • The body of the Else clause is indented so that it lines up with the indented body of the If clause.
  • The If...Then...Else selection statement follows the same general syntax as the If...Then statement (Fig. 7.7).

Figure 7.7|If...Then...Else statement syntax.


7.6 If...Then...Else Selection Statementand Conditional If Expressions (Cont.)

  • The preceding If...Then...Else statement can also be written using a conditional If expression, as in

displayLabel.Text = If(studentGrade >= 60, "Passed", "Failed")

  • A conditional If expression starts with the keyword If and is followed by three expressions in parentheses—a condition, the value of the conditional expression if the condition is true and the value if the condition is false.

7.6 If...Then...Else Selection Statementand Conditional If Expressions (Cont.)

  • Figure 7.8 illustrates the flow of control in theIf...Then...Else double-selection statement.

Figure 7.8|If...Then...Else double-selection statement activity diagram.


7.6 If...Then...Else Selection Statementand Conditional If Expressions (Cont.)

  • NestedIf...Then...Elsestatements testfor multiple conditions by placing If...Then...Else statements inside other If...Then...Else statements.

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”



  • The preceding pseudocode may be written in Visual Basic as shown in Fig. 7.9.
good programming practice2
Good Programming Practice
  • If there are several levels of indentation, each level should be indented farther to the right by the same amount of space.


  • Most Visual Basic programmers prefer to use the ElseIfkeyword to write the preceding If...Then...Else statement, as shown in Fig. 7.10.
common programming error3
Common Programming Error
  • The Else clause must always be last in an If...Then...Else statement—following an Else clause with another Else or ElseIf clause is a syntax error.

7.6 If...Then...Else Selection Statementand Conditional If Expressions (Cont.)

  • The two statements are equivalent, but you should use the latter statement—it avoids deep indentationof the code.
  • The final portion of the If...Then...Else statement uses the Else keyword to handle all the remaining possibilities.
  • The Else clause must always be last in an If...Then...Else statement—following an Else clause with another Else or ElseIf clause is a syntax error.
  • Note that the latter statement requires only oneEndIf.

7.7 Constructing the Wage Calculator Application

  • Pseudocode describing the basic operation of the WageCalculator application.

When the user clicks the Calculate Button Retrieve the number of hours worked and hourly wage from the TextBoxes If the number of hours worked is less than or equal to 40 hours Gross earnings equals hours worked times hourly wage Else Gross earnings equals 40 times hourly wage plus hours above 40 times wage and a half Display gross earnings


7.7 Constructing the Wage CalculatorApplication (cont.)

  • Figure 7.11 lists the actions, controls and events that help you complete your own version of this application.
  • The Labels in the first row guide the user through the application.
  • The Button control, calculateButton, is used to calculate the employee’s wages.
  • The third column of the table specifies that we’ll be using this control’s Click event to perform the calculations.
  • The TextBoxes contain input from the user. The final control, earningsResultLabel, is a Label that displays the application’s output.

Action/Control/Event (ACE) Table for theWage Calculator Application

Figure 7.11 | Action/Control/Event table for the WageCalculator application.


Action/Control/Event (ACE) Table for theWage Calculator Application (Cont.)

  • To complete the WageCalculator application
    • add a Click event to the CalculateButton
    • declare the variables you need to calculate the employee’s wages
  • If you forget to add code to this Click event, the application won’t respond when the user clicks the CalculateButton.

Declaring Variables in the CalculateButton’sClick Event Handler

  • Double click the CalculateButton.
  • Lines 3–6 of Fig. 7.12 display the generated event handler.

Empty event handler

Figure 7.12|CalculateButtonevent handler.

  • The EndSub keywords (line 6) indicate the end of event handler calculateButton_Click.
  • The EndClass keywords (line 7) indicate the end ofclass WageCalculatorForm.

Declaring Variables in the CalculateButton’sClick Event Handler (Cont.)

  • A Double variable holds numbers with decimal points.
  • Type Decimal is used to store monetary amounts because this data type minimizes rounding errors in arithmetic calculations (Fig 7.13).

Variable declarations

Figure 7.13| Declaring variables of type Double and Decimal.


Declaring Variables in the CalculateButton’sClick Event Handler (Cont.)

  • A constant is an identifier whose value cannot be changed after its initial declaration.
  • Constants are declared with keyword Const(Fig 7.14).

Constant declaration

Figure 7.14| Creating a constant.

good programming practice3
Good Programming Practice
  • Constants (also called named constants) help make programs more readable by providing names for constant values.
good programming practice4
Good Programming Practice
  • Capitalize each letter in the name of a constant; separate each word in the name with an underscore.

Determining the User’s Wages

  • The Val function (Fig 7.15) returns the user input as Doubles.

Variable assignment

Figure 7.15| Assigning data to variables.

error prevention tip
Error-Prevention Tip
  • To reduce errors, the IDE sometimes adds keywords for you. One example is the adding of the keywords End...If when an If...Then or an If...Then...Else statement is created. This eliminates the possibility that such keywords will be forgotten or misspelled.

Determining the User’s Wages (Cont.)

  • This If...Then...Else statement (Fig 7.16) determines whether employees earn overtime in addition to their usual wages.

If…Then… Else statement

Figure 7.16|If...Then...Else statement to determine wages.


Determining the User’s Wages (Cont.)

  • Line 31 (Fig 7.17) assigns the value in earnings to the Text property of the LabelearningsResultLabel, implicitly converting earnings from a Decimalto a string.

Displaying output

Figure 7.17| Assigning the result toearningsResultLabel.


Determining the User’s Wages (Cont.)

  • Test the application (Fig 7.18).

Incorrectly formatted output

Figure 7.18|Wage Calculator with incorrectly formatted output.


7.8 Assignment Operators

  • Visual Basic provides several assignment operators for abbreviating assignment statements.
  • The statement
    • value = value + 3
  • adds 3 to the value in value, can be abbreviatedwith the addition assignment operator += as
    • value += 3

7.8 Assignment Operators (Cont.)

  • The += operator adds the value of the right operand to the value of the left operand and stores the result in the left operand.
  • Visual Basic provides assignment operators for several binary operators, including +, -, *, ^, / and \.
  • When an assignment statement is evaluated, the expression to the right of the operator is always evaluated first, then assigned to the variable on the left.

7.8 Assignment Operators (Cont.)

  • Figure 7.19 includes the assignment operators, sample expressions using these operators and explanations.

Figure 7.19| Assignment operators.


Using the Addition Assignment Operator

  • Add an assignment operator to the application’s code (Fig 7.20).

Addition assignmentoperator shortensstatement

Figure 7.20| Using the addition assignment operator in a calculation.


7.9 Formatting Text

  • Method String.Format controls how text displays.
  • Modifying the appearance of text for display purposes is known as textformatting.
  • String.Format takes as an argument a formatcontrolstring, followed by arguments that indicate the values to be formatted.
  • The format control string argument specifies how the remaining arguments are to be formatted.

Formatting the Gross Earnings

  • The format control string, “{0:C}” indicates that argument 0 should take the format specified by the letter after the colon; this letter is called the format specifier.
  • The format defined by the uppercase letter C represents the currency format, which is used to display values as monetary amounts (Fig 7.21).
  • The effect of the C format specifier varies, depending on the locale setting of your computer.

Formatting output as currency

Figure 7.21| Using the Format method to display the result as currency.

gui design tip1
GUI Design Tip
  • Format all monetary amounts using theC (currency) format specifier.

Formatting the Gross Earnings (Cont.)

  • Figure 7.22 shows several format specifiers.

Figure 7.22| Format specifiers for strings.



(1 of 2 )

KeywordConstspecifies constant



Condition between keywordsIfandThen

(2 of 2 )

Elsebody executes whencondition evaluates toFalse

Assignment operator assigns left operand result of adding left and right operands

Format result as currency


7.10 Using the Debugger: The Watch Window

  • The Watchwindow allows you to examine the value of a variable or expression.
  • You can use the Watch window to view changes in a variable’s value as the application executes, or you can change a variable’s value yourself.
  • Each expression or variable that is added to the Watch window is called a watch.

Using the Debugger: The Watch Window

  • Add breakpoints to the application (Fig 7.24).

Figure 7.24| Breakpoints added toWageCalculatorapplication.


Using the Debugger: The Watch Window (Cont.)

  • Run the application (Fig 7.25).

Figure 7.25|Wage Calculator application.

  • When a breakpoint is reached, application execution is paused, and the IDE switches into break mode.
  • Once the application has entered break mode, you are free to explore the values of various variables, using the debugger’s Watch window.

Using the Debugger: The Watch Window (Cont.)

  • To display the Watch window, select Debug>Windows>Watch.
  • To add a watch, you can type an expression into the Name column.
  • The value and type are added by the IDE (Fig. 7.26).
  • The number stored in wage is of type Decimal.
  • You can also highlight a variable name in the code and drag-and-drop that variable into the Watch window or right click the variable in the code and select Add Watch.

Figure 7.26|Watch window.


Using the Debugger: The Watch Window (Cont.)

  • The Watch window can evaluate arithmetic expressions.
  • Expressions containing the = symbol are treatedas Boolean expressions instead of assignment statements (Fig 7.27).

Complex expression

Boolean expression

Invalid expression

Figure 7.27| Examiningexpressions.


Using the Debugger: The Watch Window (Cont.)

  • To remove an expression, simply right click the expression in the Watch window and select DeleteWatch (Fig. 7.28).
  • Alternatively, click a variable in the Watch window and press the Delete key.

Delete Watch option

Figure 7.28| Deleting a watch.


Using the Debugger: The Watch Window (Cont.)

  • Modified values are displayed in red (Fig. 7.29).

Modified value appears in red

Figure 7.29| Modified values in Watchwindow.


Using the Debugger: The Watch Window (Cont.)

  • The Watch window (Fig 7.30) can be used to change the value of a variable by entering the new value in the Value column.
  • This option enables you to test various values to confirm the behavior of your application.

Value modified directly

Figure 7.30| Modifying values in a Watch window.


Using the Debugger: The Watch Window (Cont.)

  • Run the application (Fig 7.31).

Earnings result basedon altered input

Figure 7.31| Output displayed after the debugging process.