Presentation is loading. Please wait.

Presentation is loading. Please wait.

Modular Programming Splitting your program into functions and procedures.

Similar presentations

Presentation on theme: "Modular Programming Splitting your program into functions and procedures."— Presentation transcript:

1 Modular Programming Splitting your program into functions and procedures

2 Well written code makes use of modular programming. This simply means that programs are organised into modules or sub-programs. Advantages Each sub-program can be developed and tested as a standalone program Bugs can be located within a specific sub-program Maintenance can be carried out on each Programs can be sub-divided and developed by many programmers The two main types of modules are subroutines (procedures) and functions. Modular Programming

3 A procedure is a subroutine that performs a specific task in a program. A procedure can be invoked by: a)an event e.g. Private Sub cmdCalculate_Click() b)being called when needed e.g. Call Validate Here’s how to create a procedure in VB6: Private Sub InputNames() Statements End Sub Procedures in VB6.0

4 A function is a subroutine that always returns a value e.g. a function could be used to return the result of a calculation. Note: The value returned from the function must always be assigned to a variable or a control! If CalcTax() was a function then you could return a value to a label e.g. lblAmount.Caption = CalcTax() Here’s how to create a function in VB6: Private Function CalcTax () As Single Statements End Function or you could return a value to an expression e.g. Amount = Estimate *.2 + CalcTax() *.14 Functions in VB 6.0

5 Global variables are declared at the start of a program and can be used anywhere in the program. Pros and cons Can be used anywhere in the program Declared once at the start  If value changes then changes for the rest of the program  Can be changed by mistake Global Variables

6 Local variables are declared within a procedure or function and can only be used by that subroutine. Pros Different variables can have the same name Save memory as created and destroyed during subroutine runtime Make subroutines ‘standalone’ so easy to reuse in other programs Reduce risk of accidental change of global value Local Variables

7 The two methods of parameter passing are: i.By reference (in and out) A parameter is simply the value of a variable that can be passed between subroutines. age = 25 variableparameter Subroutine IN Subroutine INOUT ii. By value (in) Parameters

8 Parameter passed is the actual variable itself. Any changes to the parameter persist beyond the call i.e. change the original value. Subroutine A 25age age = 25 Subroutine B Private Sub check (ByRef age as integer) 25age age = 42 42 age 42age Note: An array should always be passed by reference due to memory overheads. Passing Parameters By Reference

9 A copy of the current value of parameter is passed in and any changes do not affect the original value. 25 age Subroutine ASubroutine B 25 a age = 25 Private Sub check (ByVal a) 42 a a = 42 Note: In sub B the variable a is an alias i.e. a copy of the actual parameter. alias Passing Parameters By Value

10 There are a number of advantages: Greater control of data flow Reduced risk of accidental change More efficient use of memory Sub-programs are more ‘self-contained’ Improved reliability and robustness Here’s how to pass parameters in VB6: Call AddVat (cost, total) Private Sub AddVat (ByVal c as currency, ByRef total as currency) statements End Sub Advantages of Passing Values Using Parameters

11 1 Dimensional Arrays When you need to store a lot of the same kind of values

12 Why do we need Arrays? All of our programs up until now have used variables that can only store one piece of information. If we wanted to create a program that got the user to type in 10 scores we would need to declare 10 variables, one for each score. If we had to change the program to store 100 scores we’d be fed up typing the number of variable declarations we would need.

13 Why do we need Arrays? We need one variable that has 10 spaces in it, one for each score we need to store. We call this type of variable an array and it’s made up of a variable name and a subscript which tells the computer what item in the array we want. You need to be careful though because the first item of the array has a subscript of 0 not 1. Main Memory Ten locations in memory are called score and the computer uses the subscript to identify individual scores. Score(0)Score(1)Score(2)Score(3)Score(4)Score(5)Score(6)Score(7)Score(8)Score(9) 52107743085

14 Declaring an Array Tells the computer you need a new variable VB Data TypeArray Name This is the number of the last item of the array. Because we start from 0 this creates an array with spaces for 10 pieces of information Dim Name(9) as String Just like simple variables, arrays need to be declared before they are used. To declare an array of string values in VB6.0 you use the following command.

15 Exercise on Declaring Arrays 1.The scores for 20 ice skaters, each score is a decimal number between 0 and 10 2.The names of 5 doctors 3.The price of 8 items on a shopping receipt 4.The total number of goals scored for each team in the premiership. There are 12 teams 5.Whether a question in a 30 question paper was right or wrong, Dim SkaterScore(19) as Single Dim DoctorName (4) as String Dim ReceiptItem(7) as Currency Dim PremiershipTeam(11) as Integer Dim Answer(29) as Boolean

16 Assigning Values to an Array The first item in the array is the string “Mr Donaldson” The tenth item in the array is the string “Stephen Kennedy” The second item in the array is the string “Lynsey Clark” The third item in the array is the string “Graeme Craig” Name(0) = “Mr Donaldson” Name(1) = “Lynsey Clark” Name(2) = “Graeme Craig” … Name(9) = “Stephen Kennedy”

17 Exercise on Assigning Values to an Array 1.The score 1.5 for the fifth skater in the SkatersScores array 2.The name “Dr Brown” for the 2nd doctor in the array you declared to store doctors names in. 3.The price 2.99 as the 5th item in the array you declared to store items on a shopping receipt. 4.The 23 goals scored by the team in 11th place in the array you declared to store the total number of goals scored by each team in the premiership. 5.Question 13 marked as wrong, (false), as the 13th item in the array you declared to store whether 30 questions were right or wrong. SkaterScore(4) = 1.5 DoctorName(1) = “Dr Brown” ReceiptItem(4) = 2.99 PremiershipTeam(10) = 23 Answer(12) = false

18 Useful Functions for Converting User Input Handy ways to make sure your program doesn’t crash

19 What it Does:- Converts any expression into a number. An expression that only contains non-numeric characters such as A, *, £ etc or starts with these characters is converted to a zero. Making sure input is always converted into a number Function Used:- Val() How to Use It:- Val(expression) Code Example:- number = Val(txtNumber.text)

20 Changing the number of decimal places What it Does:- Rounds an expression (that produces a number) to the number of decimal places the user has asked for. Function Used:- Round() How to Use It:- Round(expression, no of d.p) Code Example:- roundednumber = Round(DecimalNumber, 2)

21 Converting a number so you have just the whole number part What it Does:- Returns the whole number part of a decimal number and discards any digits after the decimal place Function Used:- Int() How to Use It:- Int(expression) Code Example:- WholeNumber = Int(DecimalNumber)

22 Useful Functions and Keywords for Formatting Output Making the data you display neat and tidy

23 What it Does:- Converts any expression into a particular format that can be displayed in a VB control like a text box or picture box. Users can either type in a standard format like “fixed” or “currency” or create their own custom format Changing the Format of Data Function Used:- Format() How to Use It:- Format(expression, “format to be used”) Code Example:- picDisplay.print (Format(decimal, “fixed”)

24 Useful Keywords for Output What they Do:- vbTab tells the computer to add a tab and vbNewline tells the computer to start a new line Keywords Used:- vbTab and vbNewline How to Use them:- “ piece of text” & vbTab & “2 nd piece of text” & vbNewline Code Example:- picDisplay.Print(“Height:- “ & vbTab & height & vbNewline

25 Handling Strings Slicing, dicing and rearranging strings of characters

26 Working with Strings Often when we have programs that work with text we need to change the text that users have entered in some way. We can either  split the text up into several strings and store them in separate string variables, (creating substrings)  join two strings together, (concatenation).

27 Concatenation String Variable that we are using to store the concatenated string Variable that stores the cost of diesel A piece of text which is inside quotation marks Concatenation operator which joins the variable and text together Display = “The cost of diesel is £” & DieselCost Joining a piece of text (string literal) to the value stored inside of a variable

28 Finding the Length of a String Every string has a length, which is the number of characters contained in that string. We can use the Len() function to find the length of a string Length = Len(MyName) Name of the string variable we want to find the length of Function that returns the length of the string Integer variable that holds the length of the string What is the length of the following string “Why did the chicken cross the road?”

29 Creating Substrings When we only want part of a string variable we need to create a substring. For example we might want just the title “Mr” from the name “Mr Donaldson”. We can use the Mid() to return any part of another string for us Substring = Mid( StringToSplit, StartPosition, LengthOfSubstring) Number or Integer variable that tells us how many characters we want in our substring Number or Integer variable that tells us the start of the substring String variable we want to get the substring from

30 Finding Substrings Often we want the computer to find the start position of a particular piece of text within a string so that we can use Mid to extract this substring. To find a substring we use the Instr() function to return a number that gives the location of the string or 0 if it can’t find it. StartPositionOfText = Instr( 1, StringToSearch, “ ” ) String variable we want to search through Position in the string where we want to start searching Function that returns the start position of a piece of text in a string or 0 if its not there Piece of text that we are searching for, in this case a space

31 Multiple Outcome Selection Getting the computer to make a decision between multiple

32 The CASE statement improves the IF..THEN..ELSE construct where more than two conditions are possible. ‘Implement using CASE Select Case mark Case Is >= 70 grade = “A" Case Is >= 60 grade = “B" Case Is >= 50 grade = “C" Case Else grade = “Fail" End Select ‘Algorithm using nested IFs If mark >= 70 Then grade = “A" Else If mark >= 60 Then grade = “B“ Else If mark >= 50 Then grade = “C" Else grade = “Fail" End If CASE makes the code more readable so aids maintenance. Multiple Outcome Selection

Download ppt "Modular Programming Splitting your program into functions and procedures."

Similar presentations

Ads by Google