350 likes | 678 Views
Modular Programming. Splitting your program into functions and procedures. Modular Programming. Well written code makes use of modular programming . This simply means that programs are organised into modules or sub-programs. Advantages
E N D
Modular Programming Splitting your program into functions and procedures
Modular Programming 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.
Procedures in VB6.0 A procedure is a subroutine that performs a specific task in a program. Here’s how to create a procedure in VB6: Private Sub InputNames() Statements End Sub • A procedure can be invoked by: • an event e.g. Private Sub cmdCalculate_Click() • being called when needed e.g. Call Validate
Functions in VB 6.0 A function is a subroutine that always returns a value e.g. a function could be used to return the result of a calculation. Here’s how to create a function in VB6: Private Function CalcTax () As Single Statements End Function If CalcTax()was a function then you could return a value to a label e.g. lblAmount.Caption = CalcTax() Note: The value returned from the function must always be assigned to a variable or a control! or you could return a value to an expression e.g. Amount = Estimate * .2 + CalcTax()* .14
Global Variables 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
Local Variables 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
age = 25 variable parameter Subroutine IN Subroutine IN OUT Parameters A parameter is simply the value of a variable that can be passed between subroutines. • The two methods of parameter passing are: • By reference (in and out) ii. By value (in)
age = 25 42 age 25 age 42 Passing Parameters By Reference Parameter passed is the actual variable itself. Any changes to the parameter persist beyond the call i.e. change the original value. Subroutine A Subroutine B Private Sub check (ByRef age as integer) age 25 age = 42 age Note: An array should always be passed by reference due to memory overheads.
25 25 42 Passing Parameters By Value A copy of the current value of parameter is passed in and any changes do not affect the original value. Subroutine A Subroutine B alias Private Sub check (ByVal a) age = 25 age a a = 42 Note: In sub B the variable a is an alias i.e. a copy of the actual parameter. a
Advantages of Passing Values Using Parameters • 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
1 Dimensional Arrays When you need to store a lot of the same kind of values
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 variabledeclarations we would need.
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.
Declaring an Array 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. Array Name VB Data Type Dim Name(9) as String 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 Tells the computer you need a new variable
Exercise on Declaring Arrays • The scores for 20 ice skaters, each score is a decimal number between 0 and 10 • The names of 5 doctors • The price of 8 items on a shopping receipt • The total number of goals scored for each team in the premiership. There are 12 teams • 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
Assigning Values to an Array The first item in the array is the string “Mr Donaldson” Name(0) = “Mr Donaldson” Name(1) = “Lynsey Clark” Name(2) = “Graeme Craig” … … Name(9) = “Stephen Kennedy” The second item in the array is the string “Lynsey Clark” The third item in the array is the string “Graeme Craig” The tenth item in the array is the string “Stephen Kennedy”
Exercise on Assigning Values to an Array • The score 1.5 for the fifth skater in the SkatersScores array • The name “Dr Brown” for the 2nd doctor in the array you declared to store doctors names in. • The price 2.99 as the 5th item in the array you declared to store items on a shopping receipt. • 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. • 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
Useful Functions for Converting User Input Handy ways to make sure your program doesn’t crash
Making sure input is always converted into a number Function Used:- Val() 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. How to Use It:- Val(expression) Code Example:- number = Val(txtNumber.text)
Changing the number of decimal places Function Used:- Round() What it Does:- Rounds an expression (that produces a number) to the number of decimal places the user has asked for. How to Use It:- Round(expression, no of d.p) Code Example:- roundednumber = Round(DecimalNumber, 2)
Converting a number so you have just the whole number part Function Used:- Int() What it Does:- Returns the whole number part of a decimal number and discards any digits after the decimal place How to Use It:- Int(expression) Code Example:- WholeNumber = Int(DecimalNumber)
Useful Functions and Keywords for Formatting Output Making the data you display neat and tidy
Changing the Format of Data Function Used:- Format() 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 How to Use It:- Format(expression, “format to be used”) Code Example:- picDisplay.print (Format(decimal, “fixed”)
Useful Keywords for Output Keywords Used:- vbTab and vbNewline What they Do:- vbTab tells the computer to add a tab and vbNewline tells the computer to start a new line How to Use them:- “piece of text” & vbTab & “2nd piece of text” & vbNewline Code Example:- picDisplay.Print(“Height:- “ & vbTab & height & vbNewline
Handling Strings Slicing, dicing and rearranging strings of characters
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).
Concatenation Joining a piece of text (string literal) to the value stored inside of a variable Variable that stores the cost of diesel A piece of text which is inside quotation marks Display = “The cost of diesel is £” & DieselCost Concatenation operator which joins the variable and text together String Variable that we are using to store the concatenated string
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 What is the length of the following string “Why did the chicken cross the road?” 35 Function that returns the length of the string Length = Len(MyName) Integer variable that holds the length of the string Name of the string variable we want to find the length of
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 Number or Integer variable that tells us the start of the substring Substring = Mid( StringToSplit, StartPosition, LengthOfSubstring) String variable we want to get the substring from Number or Integer variable that tells us how many characters we want in our substring
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. Position in the string where we want to start searching Piece of text that we are searching for, in this case a space StartPositionOfText = Instr( 1 , StringToSearch , “ ” ) Function that returns the start position of a piece of text in a string or 0 if its not there String variable we want to search through
Multiple Outcome Selection Getting the computer to make a decision between multiple
Multiple Outcome Selection The CASE statement improves the IF..THEN..ELSE construct where more than two conditions are possible. ‘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 End If End If ‘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 CASE makes the code more readable so aids maintenance.