T ODAY ’ S Q UOTE “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are–by.

Slides:



Advertisements
Similar presentations
Modular Design Using Subroutines (functions later)
Advertisements

Sub and Function Procedures
1 5.3 Sub Procedures, Part II Passing by Value Passing by Reference Sub Procedures that Return a Single Value Debugging.
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.
1 CS 106, Winter 2009 Class 10, Section 4 Slides by: Dr. Cynthia A. Brown, Instructor section 4: Dr. Herbert G. Mayer,
Chapter 4 General Procedures
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Visual Basic.NET Fundamentals. Objectives Use primitive data types, naming conventions, and style rules Understand and apply the control structures supported.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Chapter 4 - Visual Basic Schneider
Chapter 5 - VB.Net by Schneider
Chapter 4 - VB.Net by Schneider1 Chapter 4 General Procedures 4.1 Sub Procedures, Part I 4.2 Sub Procedures, Part II 4.3 Function Procedures 4.4 Modular.
Chapter 41 Sub Procedures, Part II Passing by Value Passing by Reference Local Variables Class-Level Variables Debugging.
Chapter 41 Sub Procedures, Part II (Continue). Chapter 42 Local Variable A variable declared inside a Sub procedure with a Dim statement Space reserved.
Chapter 41 Function Procedures (Continue I). Chapter 42 Lab Sheet 4.7: Code Private Sub btnCalculate_Click(...) _ Handles btnCalculate.Click Dim a, b.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
Chapter 41 General Procedures Sub Procedures, Part I Sub Procedures, Part II Function Procedures.
Chapter 4 Sec. 4.1, 4.2, 4.4 Procedures (User-defined)
Variables & Math Operators CE 311 K - Introduction to Computer Methods Daene C. McKinney.
Apply Sub Procedures/Methods and User Defined Functions
T ODAY ’ S Q UOTE "The computers do what you tell them to do, not what you want them to do. " ( Alexander Atanasov)
Subroutines and Functions Chapter 6. Introduction So far, most of the code has been inside a single method for an event –Fine for small programs, but.
Structured Programming Defn: This is an approach to program development that produces programs of high quality that are easy to test, debug, modify and.
Chapter 5 - VB 2008 by Schneider1 Chapter 5 - General Procedures 5.1 Sub Procedures, Part I 5.2 Sub Procedures, Part II 5.3 Function Procedures 5.4 Modular.
Why to Create a Procedure
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.
1 Chapter 6 – Repetition 6.1 Do Loops 6.2 For...Next Loops 6.3 List Boxes and Loops.
CS0004: Introduction to Programming Subprocedures and Modular Design.
Chapter 5 – Decisions 5.1 Relational and Logical Operators 5.2 If Blocks 5.3 Select Case Blocks.
Chapter 4 - VB 2008 by Schneider1 Chapter 4 – Decisions 4.1 Relational and Logical Operators 4.2 If Blocks 4.3 Select Case Blocks.
Chapter 5 - VB 2005 by Schneider1 Chapter 5 – Decisions 5.1 Relational and Logical Operators 5.2 If Blocks 5.3 Select Case Blocks 5.4 A Case Study: Weekly.
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.
Subroutines and Functions. Introduction So far, most of the code has been inside a single method for an event –Fine for small programs, but inconvenient.
INLS 560 – C ONDITIONALS Instructor: Jason Carter.
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.
Chapter 5 - VB 2005 by Schneider1 Chapter 5 – Decisions 5.1 Relational and Logical Operators 5.2 If Blocks.
Introduction to VB.NET 2005 Dr. McDaniel IDS4704 Spring 2005.
R EPETITION 1 Chapter 6. C HAPTER 6 – R EPETITION 6.1 Do Loops 6.2 Processing Lists of Data with Do Loops 6.3 For...Next Loops 6.4 A Case Study: Analyze.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
1 5.4 Modular Design Top-Down Design Structured Programming Advantages of Structured Programming.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Computing Higher – SD Unit - Topic 8 – Procedure and Standard Algorithms P Lynch, St Andrew’s High School Unit 2 Software Development Process Topic.
1Edited By Maysoon Al-Duwais. 2 General Procedures Function Procedure Sub Procedures, Part I Sub Procedures, Part II Modular Design Edited By Maysoon.
Week Procedures And Functions 7 A procedure is a collection of statements that performs a task.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
Starting Out with Visual Basic.NET 2 nd Edition Chapter 6 Sub Procedures And Functions.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Subroutines and Functions Chapter 6. Introduction So far, all of the code you have written has been inside a single procedure. –Fine for small programs,
1Edited By Maysoon Al-Duwais. 2 Devices for Modularity Visual Basic has two ways for breaking problems into smaller pieces: Sub procedures Function procedures.
Chapter 4 - VB 2008 by Schneider1 Chapter 4 – Decisions 4.1 Relational and Logical Operators 4.2 If Blocks 4.3 Select Case Blocks.
1 Chapter 5 – Decisions 5.1 Relational and Logical Operators 5.2 If Blocks 5.3 Select Case Blocks 5.4 A Case Study: Weekly Payroll.
Week 4 Relational and Logical Operators Dr. Jennifer Cunningham.
1Lect7 GC20111/2/ General Procedures Function Procedure Sub Procedures, Part I Sub Procedures, Part II Modular Design Lect7 GC20111/2/2015.
Chapter#8 General Procedures
Chapter 4 - Visual Basic Schneider
5.2 Sub Procedures, Part I Defining and Calling Sub Procedures
Chapter#8 General Procedures
Chapter 5 - General Procedures
If, Subroutines and Functions
Chapter 5 - General Procedures
Chapter 4 General Procedures
Objectives Use primitive data types, naming conventions, and style rules Understand and apply the control structures supported in Visual Basic .NET Explain.
Presentation transcript:

T ODAY ’ S Q UOTE “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are–by definition–not smart enough to debug it.” (Brian Kernighan)

A DMIN S TUFF Assignment #1 due Assignment #2 Posted to website Due Oct 11 Midterm Review session Oct 16 Midterm in class Oct 18 [2 hours long]

L OGICAL O PERATORS <less than <=less than or equal to >greater than >=greater than or equal to =equal to <>not equal to ASCII values are used to decide order for strings 4

C ONDITION Decisions are a result of evaluating a condition A condition is an expression involving relational and/or logical operators Result of the condition is Boolean 5

L OGICAL O PERATORS Used with Boolean expressions Not – makes a False expression True and vice versa And – will yield a True if and only if both expressions are True Or – will yield a True if at least one of both expressions are True 6

I F B LOCK The program will take a course of action based on whether a condition is true. If condition Then action1 ElseIf condition Then action2 Else action3 End If 7 Will be executed if condition is true Will be executed if condition is false Will be executed if condition is true

E XAMPLE 1: C ODE Private Sub btnEvaluate_Click(...) _ Handles btnEvaluate.Click Dim position As Integer = CInt(txtPosition.Text) Select Case position Case 1 txtOutcome.Text = "Win" Case 2 txtOutcome.Text = "Place" Case 3 txtOutcome.Text = "Show" Case 4, 5 txtOutcome.Text = "You almost placed in the money." Case Else txtBox.Text = "Out of the money." End Select End Sub 8 Selector Value Lists

C HAPTER 5 9

C HAPTER 5 - G ENERAL P ROCEDURES 5.1 Sub Procedures, Part I 5.2 Sub Procedures, Part II 5.3 Function Procedures 5.4 Modular Design 5.5 A Case Study: Weekly Payroll 10

D EVICES FOR M ODULARITY Visual Basic has two devices for breaking problems into smaller pieces: Sub procedures Function procedures 11

S UB P ROCEDURES Perform one or more related tasks General syntax Sub ProcedureName() statements End Sub 12

C ALLING A S UB P ROCEDURE The statement that invokes a Sub procedure is also referred to as a Call statement A Call statement looks like this: ProcedureName() The rules for naming Sub procedures are the same as the rules for naming variables Make them self-explanatory 13

E XAMPLE lstBox.Items.Clear() 14 Sub ExplainPurpose() ExplainPurpose() lstBox.Items.Add("") lstBox.Items.Add("Program displays a sentence") lstBox.Items.Add("identifying a sum.") End Sub

P ASSING V ALUES You can send values to a Sub procedure Sum(2, 3) Sub Sum(ByVal num1 As Double, ByVal num2 As Double) lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "." End Sub In the Sum Sub procedure, 2 will be stored in num1 and 3 will be stored in num2 15

A RGUMENTS AND P ARAMETERS Sum(2, 3) Sub Sum(ByVal num1 As Double, ByVal num2 As Double) 16 arguments parameters displayed automatically

S EVERAL C ALLING S TATEMENTS ExplainPurpose() Sum(2, 3) Sum(4, 6) Sum(7, 8) Output: Program displays a sentence identifying a sum. 17 Sub Sum(ByVal num1 As Double, ByVal num2 As Double) lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "." End Sub

P ASSING S TRINGS AND N UMBERS Demo("CA", 38) Sub Demo(ByVal state As String, ByVal pop As Double) txtBox,Text = state & " has population " & pop & _ " million." End Sub Note : The statement Demo(38, "CA") would not be valid. The types of the arguments must be in the same order as the types of the parameters. 18

V ARIABLES AND E XPRESSIONS Dim s As String = "CA" Dim p As Double = 19 Demo(s, 2 * p) Sub Demo(ByVal state As String, ByVal pop As Double) txtBox.Text = state & " has population " & pop & _ " million." End Sub Note : The variable names in the arguments need not match the parameter names. For instance, s versus state.. 19

C ALLING A Sub procedure can call another Sub procedure. Private Sub btnAdd_Click(...) Handles btnAdd.Click Sum(2, 3) End Sub Sub Sum(ByVal num1 As Double, ByVal num2 As Double) DisplayPurpose() lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "." End Sub 20

21 “Any code of your own that you haven’t looked at for six or more months might as well have been written by someone else.” (Eagleson’s Law)

5.2 S UB P ROCEDURES, P ART II Passing by Value Passing by Reference Lifetime and Scope of a Variable Debugging 22

B Y V AL AND B Y R EF Parameters in Sub procedure headers are proceeded by ByVal or ByRef ByVal stands for By Value ByRef stands for By Reference 23

P ASSING BY V ALUE When a variable argument is passed to a ByVal parameter, just the value of the argument is passed. After the Sub procedure terminates, the variable has its original value. 24

E XAMPLE 25 Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim n As Double = 4 Triple(n) txtBox.Text = CStr(n) End Sub Sub Triple(ByVal num As Double) num = 3 * num End Sub

S AME E XAMPLE : N NUM 26 Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num) End Sub Sub Triple(ByVal num As Double) num = 3 * num End Sub

P ASSING BY R EFERENCE When a variable argument is passed to a ByRef parameter, the parameter is given the same memory location as the argument After the Sub procedure terminates, the variable has the value of the parameter 27

E XAMPLE 28 Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num) End Sub Sub Triple(ByRef num As Double) num = 3 * num End Sub

E XAMPLE : NUM N 29 Private Sub btnOne_Click(...) Handles _ btnOne_Click Dim n As Double = 4 Triple(n) txtBox.Text = CStr(n) End Sub Sub Triple(ByRef num As Double) num = 3 * num End Sub

L IFETIME AND S COPE OF A V ARIABLE Lifetime: Period during which it remains in memory Scope: In Sub procedures, defined same as in event procedures Suppose a variable is declared in procedure A that calls procedure B. While procedure B executes, the variable is alive, but out of scope 30

D EBUGGING Programs with Sub procedures are easier to debug Why? 31

32 “The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” (Tom Cargill)

5.3 F UNCTION P ROCEDURES User-Defined Functions Having Several Parameters User-Defined Functions Having No Parameters User-Defined Boolean-valued Functions Comparing Function Procedures with Sub Procedures Named Constants 33

S OME B UILT -I N F UNCTIONS 34 FunctionExampleInputOutput IntInt(2.6) is 2number Math.RoundMath.Round(1.23,1) is 1.2 number, numbernumber FormatPercentFormatPercent(.12) is 12.00% numberstring FormatNumberFormatNumber( , 1) is 12,345.6 number, numberstring

F UNCTION P ROCEDURES Function procedures (aka user-defined functions) always return one value Syntax: Function FunctionName(ByVal var1 As Type1, _ ByVal var2 As Type2, _ …) As dataType statement(s) Return expression End Function 35

E XAMPLE : F ORM 36 txtFullName txtFirstName

E XAMPLE : C ODE Private Sub btnDetermine_Click(...) _ Handles btnDetermine.Click Dim name As String name = txtFullName.Text txtFirstName.Text = FirstName(name) End Sub Function FirstName(ByVal name As String) As String Dim firstSpace As Integer firstSpace = name.IndexOf(" ") Return name.Substring(0, firstSpace) End Function 37 Function call Return statement

E XAMPLE : F ORM 38 txtSideOne txtSideTwo txtHyp

E XAMPLE : C ODE Private Sub btnCalculate_Click(...) _ Handles btnCalculate.Click Dim a, b As Double a = CDbl(txtSideOne.Text) b = CDbl(txtSideTwo.Text) txtHyp.Text = CStr(Hypotenuse(a, b)) End Sub Function Hypotenuse(ByVal a As Double, _ ByVal b As Double) As Double Return Math.Sqrt(a ^ 2 + b ^ 2) End Function 39

F UNCTION H AVING N O P ARAMETERS Private Sub btnDisplay_Click(...) _ Handles btnDisplay.Click txtBox.Text = Saying() End Sub Function Saying() As String Dim strVar As String strVar = InputBox("What is your" _ & " favorite saying?") Return strVar End Function 40

C OMPARING F UNCTION P ROCEDURES WITH S UB P ROCEDURES Subs are accessed using a Call statement Functions are called where you would expect to find a literal or expression For example: result = functionCall lstBox.Items.Add ( functionCall ) 41

F UNCTIONS VS. P ROCEDURES Both can perform similar tasks Both can call other subs and functions Use a function when you want to return one and only one value 42

N AMED C ONSTANTS Constant: value does not change during program execution (different from variable) (ex. Minimum wage, sales tax rate, name of a master file, mathematical constants, etc.) 43

N AMED C ONSTANTS Const CONSTANT_NAME As DataType = value Const PI As Double = 3.14 Dim num As Double = 4 44

N AMED C ONSTANTS Convention Uppercase letters with words separated by underscore. Place them in the Declaration sections. 45

N AMED C ONSTANTS Const INTEREST_RATE As Double = 0.04 Const MINIMUM_VOTING_AGE As Integer = 18 Const MASTER_FILE As String = 3.14 interstEarned = INTEREST_RATE * CDbl(txtAmount.Text) If (age >= MINIMUM_VOTING_AGE) Then MessageBox.Show(“You are eligible to vote”) End If Dim sr As IO.StreamReader = IO.File.OpenText(MASTER_FILE) 46

47 “If debugging is the process of removing bugs, then programming must be the process of putting them in.” (Edsger W. Dijkstra)

5.4 M ODULAR D ESIGN Top-Down Design Structured Programming Advantages of Structured Programming 48

D ESIGN T ERMINOLOGY Large programs can be broken down into smaller problems "divide-and-conquer" approach called "stepwise refinement“ Stepwise refinement is part of top-down design methodology 49

T OP -D OWN D ESIGN General problems are at the top of the design Specific tasks are near the end of the design Top-down design and structured programming are techniques to enhance programmers' productivity 50

T OP -D OWN D ESIGN C RITERIA The design should be easily readable and emphasize small module size Modules proceed from general to specific as you read down the chart The modules, as much as possible, should be single minded. That is, they should only perform a single well-defined task Modules should be as independent of each other as possible, and any relationships among modules should be specified 51

T OP -L EVEL D ESIGN C HART 52

D ETAILED C HART 53

S TRUCTURED P ROGRAMMING Control structures in structured programming Sequences: Statements are executed one after another Decisions: One of two blocks of program code is executed based on a test for some condition Loops (iteration): One or more statements are executed repeatedly as long as a specified condition is true 54

A DVANTAGES OF S TRUCTURED P ROGRAMMING Goal to create correct programs that are easier to write understand Modify "GOTO –less" programming 55

C OMPARISON OF F LOW C HARTS 56

E ASY TO W RITE Allows programmer to first focus on the big picture and take care of the details later Several programmers can work on the same program at the same time Code that can be used in many programs is said to be reusable 57

E ASY TO D EBUG Procedures can be checked individually A driver program can be set up to test modules individually before the complete program is ready Using a driver program to test modules (or stubs) is known as stub testing 58

E ASY TO U NDERSTAND Interconnections of the procedures reveal the modular design of the program The meaningful procedure names, along with relevant comments, identify the tasks performed by the modules The meaningful variable names help the programmer to recall the purpose of each variable Because a structured program is self- documenting, it can easily be deciphered by another programmer 59

E XAMPLE Private Sub btnDetermine_Click() Handles btnDetermine.Click Dim num As Integer num = 2 MsgBox(Function1(num)) End Sub Function Function1(ByVal num As Integer) As Integer Debug.Print(num) num = num ^ 2 Function1 = Function2(num) End Function Function Function2(ByVal num As Integer) As Integer Debug.Print(num) num = num ^ 2 Function2 = Function1(num) End Function 60 What’s the result?

F UNCTION E XAMPLE How to calculate Factorials? Ex: 5! = 5 * 4 * 3 * 2 * 1 = 120