If, Subroutines and Functions

Slides:



Advertisements
Similar presentations
Procedural programming in Java
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
VBA Modules, Functions, Variables, and Constants
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Program Design and Development
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
Apply Sub Procedures/Methods and User Defined Functions
1 Subroutines and Functions Chapter 6 in Deitel, Deitel and Nieto.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Why to Create a Procedure
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
1 Visual Basic Checkboxes Objects and Classes Chapt. 16 in Deitel, Deitel and Nieto.
Chapter 4: The Selection Process in Visual Basic.
Lecture Set 5 Control Structures Part A - Decisions Structures.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Copyright © 2001 by Wiley. All rights reserved. Chapter 4: The Selection Process in Visual Basic Selection Process Two Alternative Structure If..Then..ElseIf.
1 Chapter 5 - General Procedures 5.1 Function Procedures 5.2 Sub Procedures, Part I 5.3 Sub Procedures, Part II 5.4 Modular Design.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
110-G1 Motivation: Within a program, may have to perform the same computation over and over Many programs share the same computation (e.g. sorting) To.
Working with the VB IDE. Running a Program u Clicking the”start” tool begins the program u The “break” tool pauses a program in mid-execution u The “end”
1 Flow Control II Code: Select-Case and For-Next Controls: Frames and OptionButtons.
CPS120: Introduction to Computer Science Decision Making in Programs.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
22/11/ Selection If selection construct.
1 Flow Control Ifs, loops. 2 Data Type At the lowest level, all data in a computer is written in 1’s and 0’s (binary) How the data gets interpreted, what.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Practical Programming COMP153-08S Week 5 Lecture 1: Screen Design Subroutines and Functions.
‘Tirgul’ # 2 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #2.
1 CS105 Discussion 5 – Variables and If Announcements MP 1 due on Monday Midterm 1 on Tuesday If you need a conflict, request it NOW!!
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Debugging, Static Variables, ByRef, ByValue Chapt. 6 in Deitel, Deitel and Nieto.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
31/01/ Selection If selection construct.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Controlling Program Flow with Decision Structures.
More Visual Basic Code: if-then-else, for loops Controls: Multiple forms, List Boxes, Radio buttons, frames,
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Selection Using IF THEN ELSE CASE Introducing Loops.
Sub Procedures and Functions Visual Basic. Sub Procedures Slide 2 of 26 Topic & Structure of the lesson Introduction to Modular Design Concepts Write.
IE 8580 Module 4: DIY Monte Carlo Simulation
A variable is a name for a value stored in memory.
VBA - Excel VBA is Visual Basic for Applications
COMPUTATIONAL CONSTRUCTS
IS 350 Application Structure
Visual Basic 6 (VB6) Data Types, And Operators
3rd prep. – 2nd Term MOE Book Questions.
3rd prep. – 2nd Term MOE Book Questions.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 4 - Visual Basic Schneider
More Selections BIS1523 – Lecture 9.
Chapter 3: Introduction to Problem Solving and Control Statements
Chapter (3) - Looping Questions.
If selection construct
If selection construct
Chapter 7: Using Functions, Subs, and Modules
Data Types List Box Combo Box Checkbox Option Box Visual Basic 6.0
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Introduction to Computer Programming IT-104
Presentation transcript:

If, Subroutines and Functions Chapter 4 and 5 in Schneider

Resolution Two definitions of “resolution” A solution … of a problem The act … of separating into constituent or elementary parts (Webster’s New Universal Unabridged Dictionary) One of the primary techniques for solving complex problems is “divide and conquer” Break the problem into manageable pieces Solve the pieces Reassemble the pieces into a complete solution

Approaching problems Top down: begin with an overall view of the problem and break it down into parts Bottom up: begin with the pieces one believes will be needed to solve the problem, build up from there Middle out: A combination of the above

Modules Modules are one of the “constituent parts” into which a programmer breaks Visual Basic code A form is a module Another “unit” of programming is the object

Divide and Conquer Example

Divide and Conquer Example Option Explicit Dim EmployeeName As String Dim Hours As Integer Dim Wage As Double Dim Salary As Double Private Sub cmdCalculate_Click() GetInfo CalculateWeeklySalary PrintResult End Sub They’re getting rid of the currency type so use double Problem broken into three modules (top down) These are “calls”

The GetInfo Module Private Sub GetInfo() EmployeeName = txtFirstName.Text & _ " " & txtLastName.Text GetHours GetWage End Sub This module is further broken down into more modules

GetHours Module Private Sub GetHours() If IsNumeric(txtHours.Text) Then Hours = CInt(txtHours.Text) Else MsgBox ("Please enter a number (e.g. 34)” _ & “for the Hours.") txtHours.Text = "" txtHours.SetFocus End If End Sub Built-in function, has string as argument and returns a Boolean

If Then Else If Condition (evaluates to Boolean) Then Statements if condition is true Else Statements if condition is false End If

If-Then Example If State=“PA” Then Price=Price*(1.06) End If ‘State ‘Recalculates the price factoring in the PA ‘sales tax if the state is PA ‘Note strings are more easily compared in VB

Condition A condition is an expression that evaluates to a Boolean value (true or false) It often involves a comparison A > B (is A greater than B?) A >= B (is A greater than or equal to B?) A < B (is A less than B?) A <= B (is A less than or equal to B?) A=B (is A equal to B?) A <> B (is A not equal to B?) ‘(does not use !)

Compound Conditions Boolean operators can be used to combine conditions And: both expressions must evaluate to true for combination to be true Or: if either expression evaluates to true, the combination is true Not: if an expression evaluates to true, Not(expression) evaluates to false and vice versa

GetWage Module Private Sub GetWage() If IsNumeric(txtWage.Text) Then Wage = CDbl(txtWage.Text) Else MsgBox ("Please enter a number “ _ & “ (e.g. 7.95) for the Wage.") txtWage.Text = "" txtWage.SetFocus End If End Sub Puts cursor in textbox so it is ready for user to type in.

CalculateWeeklySalary Module Private Sub CalculateWeeklySalary() If Hours > 40 Then Salary = (Hours - 40) * 1.5 * Wage + _ 40 * Wage Else Salary = Hours * Wage End If End Sub

PrintResult Module Private Sub PrintResult() lblSalary.Caption = EmployeeName & _ " earned " lblSalary.Caption = lblSalary.Caption & _ Format$(Salary, "currency") lblSalary.Caption = lblSalary.Caption & _ " the week of " & Date & "." End Sub

Code maintenance Modularization makes the code easier to maintain If the way the data is obtained changes, we need only change the GetInfo module If we alter the overtime rules, we need only change the CalculateWeeklySalary module If we decide to cut an actual check, we need only change the PrintResult module

Reduce Repeated Code Another possible benefit of modules is the reduction of repeated code A given module can be called more than once from more than one location in the code

Select a Color Recall we must change the form’s backcolor property as well as the backcolor property of all the optionbuttons, and we must do that in click method of each of the optionbuttons To prevent a lot of repetition of code, we will use a subroutine

Add Procedure Does not return anything so sub Used only by this form so private

Add Procedure Result Or just type this; actually VB supplies the End Sub automatically

Calling Subroutines Private Sub optBlue_Click() Color = vbBlue Call ColorForm End Sub Private Sub optGreen_Click() Color = vbGreen ColorForm Call ColorForm subroutine using keyword Call Call ColorForm subroutine without keyword Call

Subroutine ColorForm Private Sub ColorForm() frmSelectColor.BackColor = Color optRed.BackColor = Color optBlue.BackColor = Color optGreen.BackColor = Color optYellow.BackColor = Color optCyan.BackColor = Color optMagenta.BackColor = Color End Sub Open parenthesis; close parenthesis

Scope If a variable is declared at the top of the module (form), it is referred to as global and is available to all of the procedures belonging to that module (form) If a variable is declared within a procedure (subroutine or function), it is referred to as local and is available only within that procedure

What’s the difference? Global variables should be fundamental to the problem and needed by several procedures Local variables are those that are needed in one or two procedures only

An Example For example the i used as a counter in a loop For i=1 To n is only needed within the for loop within one procedure, so it should be declared locally This way i cannot be confused with other counters in the problem (even if they are also called i) Duplicate variable names can be a big problem in longer programs, proper use of scope limits the difficulty

Passing a Parameter To get local information from one procedure to another, one “passes” the information The information that is passed is placed in the parentheses

Passing a Parameter Option Explicit Private Sub Form_Load() Call optRed_Click End Sub Private Sub optBlue_Click() Call ColorForm(vbBlue) Look Ma, no global variables Passing a parameter

Local ColorForm Private Sub ColorForm(Color As Long) frmSelectColor.BackColor = Color optRed.BackColor = Color optBlue.BackColor = Color optGreen.BackColor = Color optYellow.BackColor = Color optCyan.BackColor = Color optMagenta.BackColor = Color End Sub Passed variable and its type

What has been gained? First, the variable color is now local to ColorForm meaning that the variable color can be used elsewhere in the program without problem Second, the variable color (which corresponds to a memory location) exits only for the duration of ColorForm, so memory is freed up

Information Hiding “The process of hiding details of an object or function. Information hiding is a powerful programming technique because it reduces complexity. …. The programmer can then focus on the new object without worrying about the hidden details.” “Information hiding is also used to prevent programmers from changing --- intentionally or unintentionally -- parts of a program.” I.e. to prevent “SIDE-EFFECTS” (http://www.webopedia.com)

Multiple programmers Most code is written by teams of coders One should be able to use a module without detailed knowledge of how it works (its implementation) If a module uses global variables, then someone using module must declare these variables And if two modules use the same global variables, there can be conflicts

To and Fro We have seen how to get local information to a module, now we must consider how to get it back VB distinguishes between subroutines and functions; the difference is that functions return a value (send back some information) to whatever subroutine called it

Weekly Salary Revisited

New cmdCalculate_Click Option Explicit Private Sub cmdCalculate_Click() Dim EmployeeName As String Dim Hours As Integer Dim Wage As Double Dim Salary As Double All variables local now

New cmdCalculate_Click (Cont.) Three functions return name, hours and wage respectively, note they are part of assignment statement EmployeeName = GetName() Hours = GetHours() Debug.Print Hours Wage = GetWage() Salary = CalculateWeeklySalary(Hours, Wage) Call PrintResult(EmployeeName, Salary) End Sub CalculateWeeklySalary now a function Debug.Print prints information in the intermediate Window

GetName Function Private Function GetName() As String GetName = txtFirstName.Text & " " _ & txtLastName.Text End Function Whatever you want returned assign to the function’s name Type of thing that gets returned

GetHours Function Private Function GetHours() As Integer If IsNumeric(txtHours.Text) Then GetHours = CInt(txtHours.Text) Else MsgBox ("There was an error in the hours.") txtHours.Text = "" txtHours.SetFocus GetHours = 0 End If End Function Need to return something even if there was a mistake, better to test on validate method

GetWage Function Private Function GetWage() As Double If IsNumeric(txtWage.Text) Then GetWage = CDbl(txtWage.Text) Else MsgBox ("There was an error in the Wage.") txtWage.Text = "" txtWage.SetFocus GetWage = 0 End If End Function

CalculateWeeklySalary Function Private Function CalculateWeeklySalary(Hours _ As Integer, Wage As Double) As Double If Hours > 40 Then CalculateWeeklySalary = (Hours - 40) * _ 1.5 * Wage + 40 * Wage Else CalculateWeeklySalary = Hours * Wage End If End Function

PrintResult Subroutine Private Sub PrintResult(EmployeeName As _ String, Salary As Double) lblSalary.Caption = EmployeeName & _ " earned " lblSalary.Caption = lblSalary.Caption & _ Format$(Salary, "currency") lblSalary.Caption = lblSalary.Caption & _ " the week of " & Date & "." End Sub

ElseIf If Grade > 94 Then Letter_Grade = “A” ElseIf Grade > 86 Then Letter_Grade = “B” ElseIf Grade > 78 Then Letter_Grade = “C” ElseIf Grade > 70 Then Letter_Grade=“D” Else Letter_Grade=“F” EndIf

Target Resize Program: Passing a control as an argument

Target Resize Program: Passing a control as an argument

Target Code Private Sub Form_Load() shaCircle1.Tag = 0.9 End Sub

Target Code Private Sub Form_Resize() Call CircleUpdate(shaCircle1) End Sub

Target Code Private Sub CircleUpdate(MyCircle As Shape) MyCircle.Width = MyCircle.Tag * _ frmTarget.ScaleWidth MyCircle.Height = MyCircle.Tag * _ frmTarget.ScaleHeight MyCircle.Left = frmTarget.ScaleWidth / 2 - _ MyCircle.Width / 2 MyCircle.Top = (frmTarget.ScaleHeight - _ MyCircle.Height) \ 2 End Sub