Unit 6 - Subroutines
Structured Programming Main Topics Structured Programming Subroutines Parameter Passing with Subroutines Control Structures and Subroutines Problem Solving with Structured Programming
What we will be doing this chapter Organizing Programs by breaking them up into “mini” programs Writing our own functions! (like Len, Asc, Chr, etc from last unit!)
I can… Define and describe structured programming and its purpose.
Why is Structured Programming Needed??? Look back at the past…. Programming in older versions of BASIC vs. Modern Styles of Programming “Spaghetti Code”: Hopelessly intertwined statements caused by numerous “jumps” between sections of code Nearly impossible to follow – would just between lines – no flow
What is Structured Programming?? Dividing a program into a hierarchy of modules or subprograms Large complicated problems are broken into smaller, easier to manage problems “Divide and Conquer” Method Example: Planning a Party
What is structured programming?? Program is broken up into modules Mini subproblems/sub routines Each subroutine includes its own: Purpose Declaration Statements Each acts like a separate mini program – but when all put together solve a bigger problem!
What is Structured Programming Modular Programming another name for structured programming Programming in this style then becomes about putting together the modules (mini programs) in a productive way. Ex: Finding the area of a Trapezoid
How to Write a Structured (Modular) Program Top- Down Design Breaking a large programming task (the “Top”) into smaller and smaller subtasks (the “Bottom”) Subprograms are implemented (written) by Subroutines Subroutines are accessed (used) by Call Statements Subroutines are called from the Main Program
Process of Top-Down Design First – identify the major tasks to be performed. Put in outline form – this outline becomes the basis of the main program Avoid thinking about details of how to implement the individual subprograms – but instead focus on the “Top” big picture Write the main program as a series of remarks (comments) and subroutine calles based on the outline of the major tasks
Then Work Down!! After you have the outline complete – then work down to fill in the details!!!! Each subroutine performs ONE of the major tasks – thus it has a VERY limited purpose This is where you deal with the details!
Advantages of Top-Down Structured Programming Programs will be easier to read! Will be full of documentation as each subprogram explains its purpose and function! Programs will be easier to write! Complicated problems broke down into smaller easier to manage subproblems Only after main tasks identified do you worry about the details. Programs are easier to use, change, adapt, modify, and debug
Advantages of Top-Down Structured Programming Programs are easier to reuse A module that performs a specific task can be Copied into another program needing the same task Can be reused in the same program by calling it multiple times. Other, more powerful programming languages require this kind of structure
Steps of Top-Down Structure Programming Start with an outline of the main program Write down English phrases to list and describe the major tasks to be performed AVOID thinking about the details of each major task Code the main program Translate each English phrase into one or two Visual Basic subroutine calls Use plenty of documentation to describe the actions and make the program more readable.
Steps of Top-Down Structure Programming Program the details by writing each subroutine. Open the form’s code window Define the Subroutine Give the Function a meaningful name! Select the type – “Sub” Select the Scope Type – normally “Private” Then type your code for that subroutine
Basics of Subroutine will ApPear in Code <Private or Public> Sub <name>() ... … End Sub
Steps of Top-Down Structure Programming Test the completed program Use a complete set of test data to be sure it works Makes any changes or refinements that are necessary or desireable
Homework Read Handout and Answer Corresponding Questions
Subroutines!!! I can write subroutines (mini programs) for a program with Structured Programming!
Structured Programming Dividing a program into hierarchy of modules or subprograms Large, complicated programs are broken into smaller, easier to manage subproblems Subprograms are implemented by Subroutines Subroutines are accessed by Call statements Subroutines are called from the Main Program
Subroutines One of Visual Basic’s ways of writing subprograms Two parts to a subroutine Subroutine Call (found in the main program) Subroutine Implementations (where written)
Subroutine IMplementation The actual CODE for the subproblem Note: Each time we write code for a button – we are writing a subroutine – “call” happens when button clicked! Syntax Private Sub <subroutine name>(<parameter list>) … End Sub
Subroutine Names MUST start with a letter Can contain letters, numbers, underscores Cannot be a reserved word (TextBox, Integer, etc)
Parameters Private Sub <subroutine name>(<parameter list>) Syntax Private Sub <subroutine name>(<parameter list>) … End Sub Parameter List is OPTIONAL – contains variables they are to be used within the subroutine!
Creating a Subroutine Open the Form’s code Window (View Code) Define the Subroutine Give the function a meaningful name Select type “Sub” Select scope – generally “Private” Then type the code for that subroutine part in the code window!
Subroutine Call The code used in the MAIN PROGRAM to access the subroutine! Syntax Call <subroutine name>(<parameter list>) Examples Call FindAverage(x, y) Call PrintOutput()
Unit6Ex1 Create an Example entitled Unit6Ex1 Add a Label with the words “Structured Programming Example” Add a ListBox! Stretch it out to make it wider! Create a Common Button with the words “Start” Double Click the Button
Unit6Ex1 Private Sub.... ‘ Call the first subroutine Call First() ‘ Call the second subroutine Call Second() ‘ Call the third subroutine Call Third() ‘ Call the fourth subroutine Call Fourth() End Sub
Name: First Type: Sub Scope: Private Creating Subroutines Stay in the Coding Menu. After “End Sub” we are going to start our own, new subroutine. Name: First Type: Sub Scope: Private Private Sub First() ListBox1.Items.Add(“This is the first subroutine”) End Sub
Subroutines 2, 3, and 4 Similar! Private Sub Second() ListBox1.Items.Add(“This is the second subroutine”) End Sub Private Sub Third() ListBox1.Items.Add(“This is the third subroutine”)
Subroutine 4! Private Sub Fourth () ListBox1.Items.Add(“This is the fourth subroutine”) End Sub
Create Another Subroutine Private Sub DividingLine() ListBox1.Items.Add(“----------------------------------”) End Sub
Alter our Main Program (Button) Private Sub.... ‘ Call the first subroutine Call First() ‘ Draw a Dividing Line Call DividingLine() ‘ Call the second subroutine Call Second()
Alter Main Program ‘ Call the third subroutine Call Third() ‘ Draw a Dividing Line Call DividingLine() ‘ Call the fourth subroutine Call Fourth() End Sub
Your program should have the following output: With a Partner!! Start a New Project Entitled: Unit6Ex2 Write a program that contains THREE subroutines. Prints your name Prints your partner’s name Prints a line of asterisks Your program should have the following output: **************************** First Person’s Name Second Person’s Name
With a Partner!! Be sure to: Use a command button to start the program Write your main program within this command button Use comments within the main program describing the actions
Homework Worksheet 6A
Parameter Passing with Subroutines Today we’ll be adding in PARAMETER Passing We used parameters with our functions last chapter we had to send in a “parameter” and the function did something with that parameter! Len used a string Mid used a string, starting integer, and number of integers
Recall Structured Programming – dividing a program into a hierarchy of modules/subprograms Subroutines: One of Visual Basic’s ways of writing subroutines Two parts: Subroutine Call (main program) Subroutine Implementation (code written separate from the main program) Each subroutine acts like its own program (own variables, input, If..Then.., loops, etc)
Problem If each subroutine is it’s own program, how is information shared between the different subprograms??? How do I get data that is help within one subroutine into another one for processing??? Answer: Parameters!!
Subroutines using a Parameter Subroutine Call Syntax Call <subroutine name> (<parameter list>) Subroutine Implementation Syntax Private Sub <subroutine name> (<parameter list>)
Parameter The parameter provides a method of transferring data from the main function. Ex: Len(word) takes in a STRING that we send in! Ex: Asc(“A”) takes in a CHARACTER that we send in! Ex: Chr(45) takes in an INTEGER that we send in!
Two Ways to Write a Parameter List ByVal sends the VALUE in….the variable in the main program will not be changed. Variables received from Main program declared in parameter statement of Subroutine!! In Main Program Dim x As Single x = -48 Call PrintSquare(x) ListBox1.Items.Add(x) Subroutine Private Sub PrintSquare(ByVal num As Single) num = num * num ListBox1.Items.Add(“The square is “ & num) End Sub
Subroutines Using parameters
Subroutines with parameters - ByVal Steps: The value of variable x from the main program is copied into the variable num in the subroutine Variable num is manipulated and the variable x goes unchanged.
Two Ways to Write a Parameter List ByRef sends the reference (where located in memory)….the variable in the main program can changed. In Main Program Dim x As Single x = -48 Call PrintSquare(x) ListBox1.Items.Add(x) Subroutine Private Sub PrintSquare(ByRef num As Single) num = num * num ListBox1.Items.Add(“The square is “ & num) End Sub
Subroutines Using parameters
Subroutines with parameters - ByRef Steps: The reference (location) of x from the main program is copied into the variable num in the subroutine Variable num are referencing the same location. Both are manipulated and the x value will have the same value as num after the subroutine has run.
Example 1: In Main Program Subroutine Dim x As Single Call Print Square(x) ListBox1.Items.Add(x) ListBox1.Items.Add(num) Subroutine Private Sub PrintSquare(ByVal num As Single) num = num * num ListBox1.Items.Add(“The square is “ & num) End Sub What if we tried to print out the variable from the subroutine?!? In the main?
What happens?? Num is NOT a variable of our main Program!! As a result it cannot be manipulated, printed, etc in our main program. Since it is defined in our SUBROUTINE our SUBROUTINE is where it is used. Does the same apply for the variables in our main program? Are they specific to the main program?!?
Example 2: In Main Program Dim x As Single x = -48 Call Print Square(x) ListBox1.Items.Add(x) Subroutine Private Sub PrintSquare(num As Single) num = num * num ListBox1.Items.Add(“The square is “ & num) ListBox1.Items.Add(“x = “ & x) End Sub What if we tried to print out the variable from the main in the subroutine?!?
What happens?? x is NOT a variable of our subroutine!! As a result it cannot be manipulated, printed, etc in our subroutine. Since it is defined in our Main program our Main Program is where it is used.
Sample Program: Finding the average of 3 numbers Let’s think this our using our Structured Programming model first…How should be break down our “big problem”
Subroutine Break Down: Our program will need 4 subroutines Intro: Introduced and examples the program EnterData: Allows the user to enter three numbers Calc Average: Calculates the Average OutputResults: Prints the three numbers and their average
Unit6ex3 Open a new form called Unit6Ex3 Create a Label and have it say: Average of Three Numbers Add a Command Button and have it say: Start Add a ListBox!
Code Window Think before you code!! What variables will we need?? How many variables?? In what order will our subroutines be called?? Write down in English BEFORE coding!
Unit6Ex3 Private Sub Button….. Dim a As Single ‘ first number Dim b As Single ‘ second number Dim c As Single ‘ third number Dim average As Single ‘ average of three numbers ‘ Program Introduction Call Intro()
UniT6ex3 ‘ Input Data Call EnterData(a, b, c) ‘ Find the Average Call CalcAverage(a, b, c, average) ‘ Output the results Call OutputResults(a, b, c, average) End Sub
First Subroutine: Intro Now we can think about the specifics of each What do we want the intro subroutine to do? Are any variables needed? If so…what??
First Subroutine: Intro Private Sub Intro() ListBox1.Items.Add(“Welcome to the Averaging Program”) ListBox1.Items.Add(“I find the average of 3 numbers!”) ListBox1.Items.Add(“Let’s get started!”) End Sub
Second Subroutine –EnterData What is the purpose of the second subroutine? Are any variables needed to be modified here?? What will our parameters be?
Second Subroutine – EnterData Private Sub EnterData(ByRef a As Single, ByRef b As Single, ByRef c As Single) a = InputBox(“Enter the first value”, “Input a”) b = InputBox(“Enter the second value”, “Input b”) c = InputBox(“Enter the third value”, “Input c”) End Sub **Use ByRef because all variables sent in will need to be changed!!**
Third Subroutine – Calculate the Average What is the purpose of the third subroutine? Are any variables needed to be modified here?? What will our parameters be?
Third Subroutine – Calculate the Average Private Sub CalcAverage(ByVal a As Single, ByVal b As Single, ByVal c As Single, ByRef average as Single) average = (a + b + c) / 3 End Sub **Use ByRef 0nly for average…because that is the only variable from the main program we want changed!!**
Fourth Subroutine – output Results What is the purpose of the third subroutine? Are any variables needed to be modified here?? What will our parameters be?
Fourth Subroutine – output Results Private Sub OutputResults(ByVal a As Single, ByValb As Single, ByVal c As Single, ByVal average as Single) ListBox1.Items.Add(“Three Values Entered: ” & a & “, “ & b & “, “ & c) ListBox1.Items.Add(“Average: “ & average) End Sub **Use ByVal for all no values sent in must in changed in main prog**
With a Partner: Trapezoid Area Recall we wrote a program at the beginning of the semester that found the area of a trapezoid! A = ½ h(b1 + b2) Rewrite this program using the four subroutines with parameters! Program Introduction Inputs height and lengths of the bases Calculate the area of the trapezoid Outputs the area in a textbox Recall: Use a button to start the program (main code) and use comments to describe the actions.
With a Partner: Slope of Line Recall we wrote a program at the beginning of the semester that found the slope of a line! Rewrite this program using the three subroutines with parameters! Inputs coordinates of the two points If x1 = x2…calculates the slope Outputs the slope or tells if the slope is undefined Recall: Use a button to start the program (main code) and use comments to describe the actions.
With a Partner: Trapezoid Area Recall we wrote a program at the beginning of the semester that found the area of a trapezoid! A = ½ h(b1 + b2) Rewrite this program using the four subroutines with parameters! Program Introduction Inputs height and lengths of the bases Calculate the area of the trapezoid Outputs the area in a textbox Recall: Use a button to start the program (main code) and use comments to describe the actions.
With a Partner: Slope of Line Recall we wrote a program at the beginning of the semester that found the slope of a line! Rewrite this program using the three subroutines with parameters! Inputs coordinates of the two points If x1 = x2…calculates the slope Outputs the slope or tells if the slope is undefined Recall: Use a button to start the program (main code) and use comments to describe the actions.
With a Partner: Trapezoid Area Recall we wrote a program at the beginning of the semester that found the area of a trapezoid! A = ½ h(b1 + b2) Rewrite this program using the four subroutines with parameters! Program Introduction Inputs height and lengths of the bases Calculate the area of the trapezoid Outputs the area in a textbox Recall: Use a button to start the program (main code) and use comments to describe the actions.
With a Partner: Slope of Line Recall we wrote a program at the beginning of the semester that found the slope of a line! Rewrite this program using the three subroutines with parameters! Inputs coordinates of the two points If x1 = x2…calculates the slope Outputs the slope or tells if the slope is undefined Recall: Use a button to start the program (main code) and use comments to describe the actions.
Review of Structured Programming and Subroutines What would the output of the program in front of you be.
Review What is Structured Programming? Name give advantages to Structured Programming What are the steps of Structured Programming?
What is Structured Programming? Review What is Structured Programming? Dividing a program into a hierarchy of modules or subprograms
Name give advantages to Structured Programming Review Name give advantages to Structured Programming Programs will be easier to read Programs will be easier to write. Programs will be easier to use, changes, adapt, modify, and debug Programs are easier to reuse Other more power programming languages require this structure
What are the steps of Structured Programming? Review What are the steps of Structured Programming? Start with an outline of the main program Code the main program Program the details by writing each subroutine Test the completed program
Control Structures, Subroutines, and Structured Programming I can describe methods for which the transfer of control is accomplished within a Visual Basic program.
Recall: Structured Programming – dividing a program into a hierarchy of modules/subprograms Subroutines: One of Visual Basic’s ways of writing subroutines Two parts: Subroutine Call (main program) Subroutine Implementation (code written separate from the main program) Each subroutine acts like its own program (own variables, input, If..Then.., loops, etc)
Recall: Control structures: Methods in which transfer of control (the order in which program statements are performed) is accomplished Three types Sequential (Linear) Selection (Branching/Decision) Iteration (Repetition/Looping) Often Represented using FLOWCHARTS (shows the flow of control!)
Control Structures Sequential (Linear) ONE flow **What all the programs we have done so far have looked like**
Control Structures Single selection: If…Then Selection (Decision) Split at Decisions - multiple paths Single selection: If…Then Double selection: If…Then…Else Multiple-selection: If…Then…ElseIf Select Case
Control Structures Repetition (Looping) repeat code numerous times Fixed repetition: For…Next Variable repetition: While Do While Do Unit Do Loop…While Do Loop…Until
Why Needed? Control Structures allowed us to create programs that followed a LOGICAL sequence Using forbidden control blocks that cause jumps (GoTo code) disrupts that logical sequence and flow of the program Remove the structure!
Control Structures and Subroutines When writing programs you need to consider…. The major tasks to be performed (determines subroutines!!) The actions involved in each major task (type of control structure to use!)
Structures Problem Solving with Top-Down Programming 4 things happen BEFORE we code the program!! Problem Definition What am I being asked to do? Write a brief description of the purpose of the program and what it is to accomplish Input/Output Format Specification What information will the program need to be given while executing What information will the program need to be printing
Structures Problem Solving with Top-Down Programming 4 things happen BEFORE we code the program!! Algorithm Design Write an outline of the major tasks to be performed Arrange this list into the order in which they are to be performed Determine the control structures needed to perform each task Data Structure Analysis What types of variables (strings, singles, integers, etc) will be needed? What will be the function (role) of each variable? What meaningful names can be given to the variables?
Structures Problem Solving with Top-Down Programming Coding the Program Outline the main program from the algorithm Code the main program as a series of call statements – including documentation for the variable list and description of the purpose of each Call statement Code the Subroutines – design and write each subroutine in detail, paying attention to the type of control structures used in each
Structures Problem Solving with Top-Down Programming 2 things happen After we code the program!! Testing the Program Design a complete set of test data that will demonstrate that the program functions property for all possible data and in all possible cases Does the program work ALL the time?? Does it crash when given “bad” input???
Structures Problem Solving with Top-Down Programming 2 things happen After we code the program!! Evaluation, Modification, and Refinement How can the program be improved? How can the output be improved to make it more readable, descriptive, and visually appealing? What features can be added to the program to make it a better, more useful, and more user friendly program? What changes are necessary to make the program work in all possible cases?