SlideShare una empresa de Scribd logo
1 de 28
It is easier to read, understand and manage things if they are broken down into sections.  Books are divided into chapters, essays are written in paragraphs, school subjects are split into units,  school years are split into register classes.  All of these things have been broken down into manageable ‘chunks’.  Each ‘chunk’ has something in common.  The chapter in a book is one part of the story.  The unit at school is all on one topic.  One register class all have the same guidance teacher, may all take German or all play in the school wind band. There is usually a list at the start of things to show what each of the ‘chunks’ are.  The contents page at the beginning of a book, a course description of a subject at school or a list of register classes. Procedures & Parameters Sub-programs make your program more  readable ,  maintainable, modular and robust . The same applies to programming. It is much easier to read, understand and manage a program if it is broken down into sections.  Each section should perform a main step from your design.  These sections are often known as  procedures .  In Visual Basic a procedure is called a  sub-program When you write out the pseudocode for your program design then the main steps listed  will each become sub-programs.  At the beginning of your program, after you have listed the variables you will use, you will have to list the sub-programs you will use as well.
For Example… This would be written in code as: It’s worth remembering that the order you list the sub-programs in is the order they will run in. Private Sub cmdCalculate_click() DIM number1 as integer DIM number2 as integer DIM answer as integer Call get_numbers Call calculate Call display_result END Sub Variable statements Sub-program statements Pseudocode Sub-program name Main Steps 1.  Get two numbers get_numbers 2.  Calculate the sum calculate 3.  Display the answer in message box Display_result
Private Sub cmdCalculate_click() DIM number1 as integer DIM number2 as integer DIM answer as integer Call get_numbers( ) Call calculate( ) Call Display_result( ) END Sub Sub get_numbers ( ) Number1 = InputBox(“Enter the first number”) Number2 = InputBox(“Enter the second number”) End Sub Sub calculate ( ) Answer = number1+number2 End Sub Sub Display_result( ) txtAnswer.text = answer End Sub So a whole program written with sub-programs would look something like this: Variable statements Sub-program get_numbers Sub-program calculate Sub-program display_result Sub-program statements
Private Sub cmdCalculate_click( ) DIM number1 as integer DIM number2 as integer DIM answer as integer Sub Display_result( ) txtAnswer.text = answer End Sub Sub calculate ( ) Answer = number1+number2 End Sub Sub get_numbers ( ) Number1 = InputBox(“Enter the first number”) Number2 = InputBox(“Enter the second number”) End Sub END Sub Call Display_result( ) Call calculate( ) Call get_numbers( ) Running order of a program which uses sub-programs
There are two different ways you can use variables within your program.  Global Variables and Local Variables Variables Global Variables  Global variables are variables whose value is available throughout your program for use by different sub programs.  Global variables are declared right at the beginning of your program, before you call any sub programs. It is NOT good programming practise to make all your variables global. Global variables are more likely to be altered by mistake and produce errors in your code.  Where possible, Local variables should be used. It will always be necessary to have some global variables as you will normally want to move some data between different sub programs, for example a value taken in in one sub program might be used in a calculation in another and displayed in a third.
Local Variables  Local variables are variables which are used in only one sub program.  They are not declared at the beginning of your code – instead the dimensioning takes place within the sub program. The value stored in a local variable can only be changed, used and viewed in the sub routine it was declared in. You should try to use Local variables whenever possible as it reduces the chances of values being changed  by accident elsewhere in your code and makes the program easier to maintain and update.  It is also considered good programming practise to use Local variables where possible.
Global Variable  number Dimensioned at the start of the program Used in different sub programs –  the value from one is passed into and used in the other Local variables  counter  and  answer dimensioned within the sub program and used only in that sub program Local and Global variables
Sub-Programs & Parameters You can’t use sub-programs in Visual Basic without also using  parameters .  Parameters handle the  flow of data  within your program for all  global  variables.  A parameter can be either a  variable  or a  value .  Parameters can be passed  into  and  out of  a sub-program. Parameters improve the  reliability  and  robustness  of your program You must list all the parameters you intend to use in each sub- program.  This list must be included as part of the CALL statement and as part of the actual sub-program.
There are two different ways to pass parameters between sub-programs. You can pass parameters by VALUE or you can pass parameters by REFERENCE Passing Parameters Passing Parameters by Value Parameter Passing by  VALUE is  when a value is passed  into  a subprogram for use by the subprogram, but the  changed  value is  not  passed out. Parameters passed by Value are indicated by putting brackets around the parameter name. Passing Parameters by Reference Parameter Passing by  REFERENCE is  when a value is passed  into  a subprogram for use by the subprogram, and then the  changed  value is passed  out  to be used by other sub-programs. Parameters are passed by Reference by default and are simply listed in the parameter list.
Private Sub cmdBegin_Click() Dim number1 As Integer Dim number2 As Integer Dim answer As Integer Call get_numbers (number1, number2) Call calculate ((number1), (number2), answer) Call display_answer ((answer)) End Sub Sub get_numbers (number1, number2) number1 = InputBox("Enter number 1") number2 = InputBox("Enter number 2") End Sub Sub calculate (number1, number2, answer) answer = number1 + number2 End Sub Sub display_answer (answer) txtAnswer.Text = answer End Sub Example Comments The parameters are shown in blue number1 and number2 are  changed  in the get_numbers sub-program and the changed data needs to be used elsewhere so are passed by  reference . The same parameters are listed here in the exact same  order  they are listed in the main program. number1 and number2 are simply passed into the calculate sub-program but are  not changed  and so are passed by  value ,  answer is  changed  and needs to be passed by  reference . answer is passed into the display_answer sub-program but is  not changed  and so is passed by  value .
Sub-programs and parameters make designing your program even more crucial. You need to indicate in your design where and how parameters will be used. This could be by adding data flows to structure diagrams Or by indicating data flow in pseudocode. number1 number2 number1 number2 answer answer 1. Set up variables 2. Get numbers OUT: number1, number2 3. Calculate answer IN: number1, number2.  OUT: answer 4. Display answer IN: answer 5. End Design Calculate Display answer Get  Numbers Main
Try this program out in Visual Basic.
IF register_class = “4A” OR register_teacher = “4I” OR register_teacher = “5A” THEN guidance_teacher = “Ms Graham” Else IF register_teacher = “4B” OR register_teacher = “4G”  OR register_teacher = “5C” THEN guidance_teacher = “Miss Stott” Else IF register_teacher = “4C” OR register_teacher = “4K” OR register_teacher = “5E” THEN guidance teacher = “Mrs Skellern” …  (and so on) END IF IF register_class = “4A” THEN guidance_teacher = “Ms Graham” Else IF register_teacher = “4B” THEN guidance_teacher = “Miss Stott” Else IF register_teacher = “4C” THEN guidance teacher = “Mrs Skellern” …  (and so on) END IF Using the CASE statement A CASE statement is a more efficient way of performing a multiple choice in programming.  You could use the IF… THEN… ELSE IF… ELSE IF… ELSE IF …  but it gets quite messy and you have to repeat the condition of the choice each time. For Example: The IF method gets even more messy if you have multiple possibilities giving the same result. For Example:
SELECT CASE register_ class CASE IS “4A”,”4I”,”5A” guidance_teacher = “Ms Graham” CASE IS “4B”, ”4G”,”5C”   guidance_teacher = “Miss Stott” CASE IS “4C”, “4K”, “5E”   guidance_teacher = “Mrs Skellern” END SELECT The CASE statement will perform this same task much more neatly and efficiently. SELECT CASE register_ class Case Is “4A”,”4I”,”5A” guidance_teacher = “Ms Graham” Case Is “4B”, ”4G”,”5C”   guidance_teacher = “Miss Stott” Case Is “4C”, “4K”, “5E”   guidance_teacher = “Mrs Skellern” End Select This is the variable you are checking This is the first condition (or conditions) to check if it meets. The comma means OR. This is what happens if the condition is met.  There can be more than one line of code here.
The CASE statement treats number ranges differently from other Visual Basic structures. The default for a CASE condition is CASE IS.  So CASE IS can be  exactly something  or more or less than  one  number.  You  cannot  have a number range –  CASE IS  >20  AND  <40 . If you need a number range you need to use CASE…..TO –  CASE  20  TO  40
When using random numbers you need to use the  RND  command. Randomize  is the word used to mix up a list of numbers each time a program is run.  It is a  pre-defined function . The  value of the random number is between 0 and 1  (a real number or a fraction).  If we want a bigger number we have to multiply the random number by the biggest amount we want.  To see how random numbers work,  look at the following program: Create random number Display random number Output Random Numbers
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Output Inserting the word RANDOMIZE gives truly random results
Validation and Conditional Loops You need to remember to validate the input to any program.  This will greatly reduce run-time errors caused by unexpected data and will also assist the users to enter the right data and be clear what they are doing.  It will also help the testing phase. A simple validation could be something like entering a price which is less than £10. Private Sub cmdBegin_Click() DIM cost as Integer Cost = INPUTBOX(“Please enter the cost”) txtCost.text = cost END SUB Private Sub cmdBegin_Click() DIM cost as Integer DO Cost = INPUTBOX (“Please enter the cost”) LOOP UNTIL cost < 10 txtCost.text = cost END SUB No validation – you can enter what you like Simple validation Keeps asking until you enter a valid number – no error message If you wanted to make sure the cost of an item was less that £10 you would need to keep asking the user to enter the cost UNTIL it was less than £10.  They might enter it correctly the first time, in which case they don’t need to be asked again or they might get it wrong one hundred times in which case the program will loop until they enter a cost that is less than £10. The problem here is that there is no message to tell the user why they keep getting asked for the same thing. You can add a condition which will check if the input is ok and print a helpful error message if it is not. This program will ask the user to enter the cost of an item and will display it in a text box.  However, there is no way to check whether the cost is less than £10.  To check this (this is called VALIDATION) you will need to use a conditional loop. A conditional loop is where some lines of code in your program will repeat until a certain condition is met.
Private Sub cmdBegin_Click() DIM cost as Integer DO Cost = INPUTBOX (“Please enter the cost”) IF cost >=10 THEN MSGBOX(“The cost must be less than £10”) END IF LOOP UNTIL cost < 10 txtCost.text = cost END SUB Private Sub cmdBegin_Click() DIM cost as Integer DO Cost = INPUTBOX (“Please enter the cost”) IF cost >=10 THEN MSGBOX(“The cost must be less than £10”) END IF LOOP UNTIL cost > 0 AND cost < 10 txtCost.text = cost END SUB This is better, every time an invalid cost is entered a message is displayed stating why and asking for the data again. This is correct – as it is a cost it also checks the number is greater than 0.  The error message is still displayed and there is no chance the data entered will be inappropriate. It is much more difficult to validate text input, you can help eliminate problems by converting all text input to either upper or lower case, as Visual Basic considers them as different in a comparison  - “john” would be considered as different from “John”.  It is not always appropriate to convert all text to upper or lowercase. You can also count the number of characters entered – this can help with things like postcodes which are a fixed length.
So far all the variables you have used have been single item variables. As you write more complex programs you will find you need many similar variables in one program. If you were going to read in 10 pupils marks you could have 10 individual variables. Dim mark1 as integer Dim mark2 as integer Dim mark3 as integer Dim mark4 as integer Dim mark5 as integer Dim mark6 as integer Dim mark7 as integer Dim mark8 as integer Dim mark9 as integer Dim mark10 as integer This would also require 10 input statements Mark1 = inputbox(“Please enter Mark 1”) Mark2 = inputbox(“Please enter Mark 2”) Mark3 = inputbox(“Please enter Mark 3”) Mark4 = inputbox(“Please enter Mark 4”) Mark5 = inputbox(“Please enter Mark 5”) Mark6 = inputbox(“Please enter Mark 6”) Mark7 = inputbox(“Please enter Mark 7”) Mark8 = inputbox(“Please enter Mark 8”) Mark9 = inputbox(“Please enter Mark 9”) Mark10 = inputbox(“Please enter Mark 10”) This would require 10 variables txtMark1.text = mark1 txtMark2.text = mark2 txtMark3.text = mark3 txtMark4.text = mark4 txtMark5.text = mark5 txtMark6.text = mark6 txtMark7.text = mark7 txtMark8.text = mark8 txtMark9.text = mark9 txtMark10.text = mark10 And 10 output statements This is obviously an awful lot of repetitive code.  There is a much better way of storing and using data which is related.  This is using an array. Using Arrays
An array stores a number of variables in a special data structure.  If you wanted to store a  large amount of one type of data  then you could use an  array . An array to  holds them all together  and  treats them as one thing .  The program can then refer to the whole array or any single element of the array. You would declare an array like this: Array name The number of elements in the array Array data type DIM mark(10) as Integer The memory sets aside an area divided into elements Mark 1 2 3 4 5 6 7 8 9 10 So this element is referred to as Mark(6) and this one is Mark (8) An input statement would look like this:  Mark(3) = Inputbox(“Please enter mark 3) The data entered would be placed in the third element of the array.
To eliminate the need for multiple INPUT and OUTPUT statements you would use a FOR loop for array operations. FOR  counter  = 1 TO 10 Mark( counter ) = Inputbox(“Please enter the mark “) NEXT counter FOR  giraffe  = 1 TO 10 lstResults.additem Mark( giraffe ) NEXT counter Whatever variable is used in the FOR loop is also used for the element position in the Array.  As the loop goes round, the loop variable (counter or giraffe above) is incremented (goes up by one) so first time round counter = 1 and the input goes in Mark(1), next time round counter = 2 so the input goes in Mark(2) and so on.  Instead of 10 input statements or 10 output statements, those three lines of code will input or output all 10 data items.
You can also use FOR loops and arrays to take in more than one set of related data.  For example if you wanted to read in 6 student names and their marks.  You need to keep the names and marks separate because you might want to use the numeric data for comparisons or calculations. You will need to declare 2 arrays one for names and one for marks.  You will only need one FOR loop. Name Mark Jim 37 Bob 26 Sue 52 Jan 86 John 17 Peter 79 37 26 52 86 17 79 Jim Bob Sue Jan John  Peter Name Mark (1) (2) (3) (4) (5) (6) (1) (2) (3) (4) (5) (6) So this data Would be stored like this This means that the name and mark are stored in different arrays but in the same position, so could be accessed at the same time using one FOR loop
DIM name(6) as String DIM mark(6) as Integer DIM  pupil  as Integer DIM  result  as Integer FOR  pupil  = 1 TO 6 name( pupil ) = Inputbox(“Please enter the name”) mark( pupil ) = Inputbox (“please enter the mark”) NEXT  pupil FOR  result  = 1 TO 6 lstClassResults.additem name( result ) & “ “ & mark( result ) NEXT  result This code uses one FOR loop to read in both the name and the mark. A different FOR loop is used to display the data in a list box.
String Operations Visual Basic considers upper and lower case text to be different, so if you had a quiz program where the answer should be  true  and the user entered  TRUE,  when you perform the comparison to see if they got the answer right the program would say they got it wrong.  You can convert string data to upper and lower case to help prevent problems like this. To convert test to upper case or lower case you would use the UCase or LCase functions. lowercase_string = LCase(string_variable) uppercase_string = UCase(string_variable) Where  string_variable  is the original data and  lowercase_string  and  uppercase_string  is where the converted data is stored. You can use the Len function to find out how many characters are in a string variable.  It counts spaces as well as characters.  You will need to store the length as a numeric variable. Numeric_variable = Len(string_variable) If string_variable = “John Smith”  then  numeric_variable = 10 If string_variable = “Hello”  then  numeric_variable = 5
One of the operations you can do with string variables is string concatenation – this is adding the two strings together.  It is as simple as this: Newstring = string1+string2 DIM initial as String DIM surname as String DIM userID as String initial = Inputbox(“Please enter your initial”) surname = Inputbox(“Please enter your surname”) userID = surname+initial INPUT :  initial = V  surname = Mackenzie OUTPUT :  MackenzieV String Operations - Concatenation
String Operations – Sub String A Sub string operation is where you separate part of the string value.  You can take the first character, the middle three characters, the last two, the first  seven.  Basically you can separate whatever number of characters you want from wherever you want in the string. You need to use the Mid$ function for this: String_output = Mid$(string_input, start position, number or characters) String_out = Mid$(string_input, 2, 3 ) So if string_input = “Greetings” Then  String_out = “ree” If string_input = “Computing is Fun” Then String_out = “omp” Character to start at How many characters to extract
 

Más contenido relacionado

La actualidad más candente

Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c languagekamalbeydoun
 
Introduction to flowchart
Introduction to flowchartIntroduction to flowchart
Introduction to flowchartJordan Delacruz
 
Program slicing
Program slicing Program slicing
Program slicing Feras Tanan
 
Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Blue Elephant Consulting
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Blue Elephant Consulting
 
Pseudocode-Flowchart
Pseudocode-FlowchartPseudocode-Flowchart
Pseudocode-Flowchartlotlot
 
problem solving and design By ZAK
problem solving and design By ZAKproblem solving and design By ZAK
problem solving and design By ZAKTabsheer Hasan
 
Modular programming
Modular programmingModular programming
Modular programmingbhuwanbist1
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchartfika sweety
 
Programming process and flowchart
Programming process and flowchartProgramming process and flowchart
Programming process and flowcharthermiraguilar
 
Qbesic programming class 9
Qbesic programming class 9Qbesic programming class 9
Qbesic programming class 9bhuwanbist1
 
Ch1 principles of software development
Ch1 principles of software developmentCh1 principles of software development
Ch1 principles of software developmentHattori Sidek
 
Intro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileIntro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileBlue Elephant Consulting
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICAemtrajano
 
Programming flowcharts for C Language
Programming flowcharts for C LanguageProgramming flowcharts for C Language
Programming flowcharts for C LanguageAryan Ajmer
 

La actualidad más candente (19)

Algorithms
AlgorithmsAlgorithms
Algorithms
 
Flowcharts
FlowchartsFlowcharts
Flowcharts
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c language
 
Introduction to flowchart
Introduction to flowchartIntroduction to flowchart
Introduction to flowchart
 
Program slicing
Program slicing Program slicing
Program slicing
 
Flowchart
FlowchartFlowchart
Flowchart
 
Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2
 
Pseudocode-Flowchart
Pseudocode-FlowchartPseudocode-Flowchart
Pseudocode-Flowchart
 
problem solving and design By ZAK
problem solving and design By ZAKproblem solving and design By ZAK
problem solving and design By ZAK
 
Prg 211 prg211
Prg 211 prg211Prg 211 prg211
Prg 211 prg211
 
Modular programming
Modular programmingModular programming
Modular programming
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchart
 
Programming process and flowchart
Programming process and flowchartProgramming process and flowchart
Programming process and flowchart
 
Qbesic programming class 9
Qbesic programming class 9Qbesic programming class 9
Qbesic programming class 9
 
Ch1 principles of software development
Ch1 principles of software developmentCh1 principles of software development
Ch1 principles of software development
 
Intro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileIntro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … While
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICA
 
Programming flowcharts for C Language
Programming flowcharts for C LanguageProgramming flowcharts for C Language
Programming flowcharts for C Language
 

Destacado

Structural factors
Structural factorsStructural factors
Structural factorsKelly Bauer
 
Stem 71 24 multimedia elements - graphics
Stem 71 24   multimedia elements - graphicsStem 71 24   multimedia elements - graphics
Stem 71 24 multimedia elements - graphicsKelly Bauer
 

Destacado (6)

Mm Unit 2 Part 1
Mm Unit 2 Part 1Mm Unit 2 Part 1
Mm Unit 2 Part 1
 
Structural factors
Structural factorsStructural factors
Structural factors
 
Team teaching
Team teachingTeam teaching
Team teaching
 
Logo design
Logo designLogo design
Logo design
 
Stem 71 24 multimedia elements - graphics
Stem 71 24   multimedia elements - graphicsStem 71 24   multimedia elements - graphics
Stem 71 24 multimedia elements - graphics
 
Cmyk vs rgb
Cmyk vs rgbCmyk vs rgb
Cmyk vs rgb
 

Similar a Visual Basic

Program logic and design
Program logic and designProgram logic and design
Program logic and designChaffey College
 
Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingHamad Odhabi
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving TechniquesAshesh R
 
Csc 130 class 2 problem analysis and flow charts(2)
Csc 130 class 2   problem analysis and flow charts(2)Csc 130 class 2   problem analysis and flow charts(2)
Csc 130 class 2 problem analysis and flow charts(2)Puneet narula
 
Learn Programming with Livecoding.tv http://goo.gl/tIgO1I
Learn Programming with Livecoding.tv http://goo.gl/tIgO1ILearn Programming with Livecoding.tv http://goo.gl/tIgO1I
Learn Programming with Livecoding.tv http://goo.gl/tIgO1Ilivecoding.tv
 
PCCF UNIT 1.pptx
PCCF UNIT 1.pptxPCCF UNIT 1.pptx
PCCF UNIT 1.pptxDivyaKS12
 
Software development slides
Software development slidesSoftware development slides
Software development slidesiarthur
 
Fundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxFundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxEyasu46
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPTTheVerse1
 

Similar a Visual Basic (20)

Chapter 2- Prog101.ppt
Chapter 2- Prog101.pptChapter 2- Prog101.ppt
Chapter 2- Prog101.ppt
 
Program logic and design
Program logic and designProgram logic and design
Program logic and design
 
c#.pptx
c#.pptxc#.pptx
c#.pptx
 
Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programming
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
 
programming.ppt
programming.pptprogramming.ppt
programming.ppt
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Csc 130 class 2 problem analysis and flow charts(2)
Csc 130 class 2   problem analysis and flow charts(2)Csc 130 class 2   problem analysis and flow charts(2)
Csc 130 class 2 problem analysis and flow charts(2)
 
Ms vb
Ms vbMs vb
Ms vb
 
Learn Programming with Livecoding.tv http://goo.gl/tIgO1I
Learn Programming with Livecoding.tv http://goo.gl/tIgO1ILearn Programming with Livecoding.tv http://goo.gl/tIgO1I
Learn Programming with Livecoding.tv http://goo.gl/tIgO1I
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
PCCF UNIT 1.pptx
PCCF UNIT 1.pptxPCCF UNIT 1.pptx
PCCF UNIT 1.pptx
 
C programming
C programmingC programming
C programming
 
Vb introduction.
Vb introduction.Vb introduction.
Vb introduction.
 
Software development slides
Software development slidesSoftware development slides
Software development slides
 
Fundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxFundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptx
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
03b loops
03b   loops03b   loops
03b loops
 

Más de mrsmackenzie (16)

Visual Basic
Visual BasicVisual Basic
Visual Basic
 
Higher Homework
Higher HomeworkHigher Homework
Higher Homework
 
2b Bitmapped Graphics Storage
2b  Bitmapped Graphics Storage2b  Bitmapped Graphics Storage
2b Bitmapped Graphics Storage
 
2a Bitmapped Graphics Hardware
2a Bitmapped Graphics Hardware2a Bitmapped Graphics Hardware
2a Bitmapped Graphics Hardware
 
Prog Design
Prog DesignProg Design
Prog Design
 
New Computer Systems
New Computer SystemsNew Computer Systems
New Computer Systems
 
Sd Revision
Sd RevisionSd Revision
Sd Revision
 
Storyboard
StoryboardStoryboard
Storyboard
 
Sound File Size
Sound File SizeSound File Size
Sound File Size
 
Mm Unit 2 Part 2
Mm Unit 2 Part 2Mm Unit 2 Part 2
Mm Unit 2 Part 2
 
Mm Unit 6
Mm Unit 6Mm Unit 6
Mm Unit 6
 
Mm Unit 5
Mm Unit 5Mm Unit 5
Mm Unit 5
 
Mm Unit 4
Mm Unit 4Mm Unit 4
Mm Unit 4
 
Mm Unit 3
Mm Unit 3Mm Unit 3
Mm Unit 3
 
Vrml
VrmlVrml
Vrml
 
MMT 1
MMT 1MMT 1
MMT 1
 

Último

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Visual Basic

  • 1. It is easier to read, understand and manage things if they are broken down into sections. Books are divided into chapters, essays are written in paragraphs, school subjects are split into units, school years are split into register classes. All of these things have been broken down into manageable ‘chunks’. Each ‘chunk’ has something in common. The chapter in a book is one part of the story. The unit at school is all on one topic. One register class all have the same guidance teacher, may all take German or all play in the school wind band. There is usually a list at the start of things to show what each of the ‘chunks’ are. The contents page at the beginning of a book, a course description of a subject at school or a list of register classes. Procedures & Parameters Sub-programs make your program more readable , maintainable, modular and robust . The same applies to programming. It is much easier to read, understand and manage a program if it is broken down into sections. Each section should perform a main step from your design. These sections are often known as procedures . In Visual Basic a procedure is called a sub-program When you write out the pseudocode for your program design then the main steps listed will each become sub-programs. At the beginning of your program, after you have listed the variables you will use, you will have to list the sub-programs you will use as well.
  • 2. For Example… This would be written in code as: It’s worth remembering that the order you list the sub-programs in is the order they will run in. Private Sub cmdCalculate_click() DIM number1 as integer DIM number2 as integer DIM answer as integer Call get_numbers Call calculate Call display_result END Sub Variable statements Sub-program statements Pseudocode Sub-program name Main Steps 1. Get two numbers get_numbers 2. Calculate the sum calculate 3. Display the answer in message box Display_result
  • 3. Private Sub cmdCalculate_click() DIM number1 as integer DIM number2 as integer DIM answer as integer Call get_numbers( ) Call calculate( ) Call Display_result( ) END Sub Sub get_numbers ( ) Number1 = InputBox(“Enter the first number”) Number2 = InputBox(“Enter the second number”) End Sub Sub calculate ( ) Answer = number1+number2 End Sub Sub Display_result( ) txtAnswer.text = answer End Sub So a whole program written with sub-programs would look something like this: Variable statements Sub-program get_numbers Sub-program calculate Sub-program display_result Sub-program statements
  • 4. Private Sub cmdCalculate_click( ) DIM number1 as integer DIM number2 as integer DIM answer as integer Sub Display_result( ) txtAnswer.text = answer End Sub Sub calculate ( ) Answer = number1+number2 End Sub Sub get_numbers ( ) Number1 = InputBox(“Enter the first number”) Number2 = InputBox(“Enter the second number”) End Sub END Sub Call Display_result( ) Call calculate( ) Call get_numbers( ) Running order of a program which uses sub-programs
  • 5. There are two different ways you can use variables within your program. Global Variables and Local Variables Variables Global Variables Global variables are variables whose value is available throughout your program for use by different sub programs. Global variables are declared right at the beginning of your program, before you call any sub programs. It is NOT good programming practise to make all your variables global. Global variables are more likely to be altered by mistake and produce errors in your code. Where possible, Local variables should be used. It will always be necessary to have some global variables as you will normally want to move some data between different sub programs, for example a value taken in in one sub program might be used in a calculation in another and displayed in a third.
  • 6. Local Variables Local variables are variables which are used in only one sub program. They are not declared at the beginning of your code – instead the dimensioning takes place within the sub program. The value stored in a local variable can only be changed, used and viewed in the sub routine it was declared in. You should try to use Local variables whenever possible as it reduces the chances of values being changed by accident elsewhere in your code and makes the program easier to maintain and update. It is also considered good programming practise to use Local variables where possible.
  • 7. Global Variable number Dimensioned at the start of the program Used in different sub programs – the value from one is passed into and used in the other Local variables counter and answer dimensioned within the sub program and used only in that sub program Local and Global variables
  • 8. Sub-Programs & Parameters You can’t use sub-programs in Visual Basic without also using parameters . Parameters handle the flow of data within your program for all global variables. A parameter can be either a variable or a value . Parameters can be passed into and out of a sub-program. Parameters improve the reliability and robustness of your program You must list all the parameters you intend to use in each sub- program. This list must be included as part of the CALL statement and as part of the actual sub-program.
  • 9. There are two different ways to pass parameters between sub-programs. You can pass parameters by VALUE or you can pass parameters by REFERENCE Passing Parameters Passing Parameters by Value Parameter Passing by VALUE is when a value is passed into a subprogram for use by the subprogram, but the changed value is not passed out. Parameters passed by Value are indicated by putting brackets around the parameter name. Passing Parameters by Reference Parameter Passing by REFERENCE is when a value is passed into a subprogram for use by the subprogram, and then the changed value is passed out to be used by other sub-programs. Parameters are passed by Reference by default and are simply listed in the parameter list.
  • 10. Private Sub cmdBegin_Click() Dim number1 As Integer Dim number2 As Integer Dim answer As Integer Call get_numbers (number1, number2) Call calculate ((number1), (number2), answer) Call display_answer ((answer)) End Sub Sub get_numbers (number1, number2) number1 = InputBox(&quot;Enter number 1&quot;) number2 = InputBox(&quot;Enter number 2&quot;) End Sub Sub calculate (number1, number2, answer) answer = number1 + number2 End Sub Sub display_answer (answer) txtAnswer.Text = answer End Sub Example Comments The parameters are shown in blue number1 and number2 are changed in the get_numbers sub-program and the changed data needs to be used elsewhere so are passed by reference . The same parameters are listed here in the exact same order they are listed in the main program. number1 and number2 are simply passed into the calculate sub-program but are not changed and so are passed by value , answer is changed and needs to be passed by reference . answer is passed into the display_answer sub-program but is not changed and so is passed by value .
  • 11. Sub-programs and parameters make designing your program even more crucial. You need to indicate in your design where and how parameters will be used. This could be by adding data flows to structure diagrams Or by indicating data flow in pseudocode. number1 number2 number1 number2 answer answer 1. Set up variables 2. Get numbers OUT: number1, number2 3. Calculate answer IN: number1, number2. OUT: answer 4. Display answer IN: answer 5. End Design Calculate Display answer Get Numbers Main
  • 12. Try this program out in Visual Basic.
  • 13. IF register_class = “4A” OR register_teacher = “4I” OR register_teacher = “5A” THEN guidance_teacher = “Ms Graham” Else IF register_teacher = “4B” OR register_teacher = “4G” OR register_teacher = “5C” THEN guidance_teacher = “Miss Stott” Else IF register_teacher = “4C” OR register_teacher = “4K” OR register_teacher = “5E” THEN guidance teacher = “Mrs Skellern” … (and so on) END IF IF register_class = “4A” THEN guidance_teacher = “Ms Graham” Else IF register_teacher = “4B” THEN guidance_teacher = “Miss Stott” Else IF register_teacher = “4C” THEN guidance teacher = “Mrs Skellern” … (and so on) END IF Using the CASE statement A CASE statement is a more efficient way of performing a multiple choice in programming. You could use the IF… THEN… ELSE IF… ELSE IF… ELSE IF … but it gets quite messy and you have to repeat the condition of the choice each time. For Example: The IF method gets even more messy if you have multiple possibilities giving the same result. For Example:
  • 14. SELECT CASE register_ class CASE IS “4A”,”4I”,”5A” guidance_teacher = “Ms Graham” CASE IS “4B”, ”4G”,”5C” guidance_teacher = “Miss Stott” CASE IS “4C”, “4K”, “5E” guidance_teacher = “Mrs Skellern” END SELECT The CASE statement will perform this same task much more neatly and efficiently. SELECT CASE register_ class Case Is “4A”,”4I”,”5A” guidance_teacher = “Ms Graham” Case Is “4B”, ”4G”,”5C” guidance_teacher = “Miss Stott” Case Is “4C”, “4K”, “5E” guidance_teacher = “Mrs Skellern” End Select This is the variable you are checking This is the first condition (or conditions) to check if it meets. The comma means OR. This is what happens if the condition is met. There can be more than one line of code here.
  • 15. The CASE statement treats number ranges differently from other Visual Basic structures. The default for a CASE condition is CASE IS. So CASE IS can be exactly something or more or less than one number. You cannot have a number range – CASE IS >20 AND <40 . If you need a number range you need to use CASE…..TO – CASE 20 TO 40
  • 16. When using random numbers you need to use the RND command. Randomize is the word used to mix up a list of numbers each time a program is run. It is a pre-defined function . The value of the random number is between 0 and 1 (a real number or a fraction). If we want a bigger number we have to multiply the random number by the biggest amount we want. To see how random numbers work, look at the following program: Create random number Display random number Output Random Numbers
  • 17.
  • 18. Validation and Conditional Loops You need to remember to validate the input to any program. This will greatly reduce run-time errors caused by unexpected data and will also assist the users to enter the right data and be clear what they are doing. It will also help the testing phase. A simple validation could be something like entering a price which is less than £10. Private Sub cmdBegin_Click() DIM cost as Integer Cost = INPUTBOX(“Please enter the cost”) txtCost.text = cost END SUB Private Sub cmdBegin_Click() DIM cost as Integer DO Cost = INPUTBOX (“Please enter the cost”) LOOP UNTIL cost < 10 txtCost.text = cost END SUB No validation – you can enter what you like Simple validation Keeps asking until you enter a valid number – no error message If you wanted to make sure the cost of an item was less that £10 you would need to keep asking the user to enter the cost UNTIL it was less than £10. They might enter it correctly the first time, in which case they don’t need to be asked again or they might get it wrong one hundred times in which case the program will loop until they enter a cost that is less than £10. The problem here is that there is no message to tell the user why they keep getting asked for the same thing. You can add a condition which will check if the input is ok and print a helpful error message if it is not. This program will ask the user to enter the cost of an item and will display it in a text box. However, there is no way to check whether the cost is less than £10. To check this (this is called VALIDATION) you will need to use a conditional loop. A conditional loop is where some lines of code in your program will repeat until a certain condition is met.
  • 19. Private Sub cmdBegin_Click() DIM cost as Integer DO Cost = INPUTBOX (“Please enter the cost”) IF cost >=10 THEN MSGBOX(“The cost must be less than £10”) END IF LOOP UNTIL cost < 10 txtCost.text = cost END SUB Private Sub cmdBegin_Click() DIM cost as Integer DO Cost = INPUTBOX (“Please enter the cost”) IF cost >=10 THEN MSGBOX(“The cost must be less than £10”) END IF LOOP UNTIL cost > 0 AND cost < 10 txtCost.text = cost END SUB This is better, every time an invalid cost is entered a message is displayed stating why and asking for the data again. This is correct – as it is a cost it also checks the number is greater than 0. The error message is still displayed and there is no chance the data entered will be inappropriate. It is much more difficult to validate text input, you can help eliminate problems by converting all text input to either upper or lower case, as Visual Basic considers them as different in a comparison - “john” would be considered as different from “John”. It is not always appropriate to convert all text to upper or lowercase. You can also count the number of characters entered – this can help with things like postcodes which are a fixed length.
  • 20. So far all the variables you have used have been single item variables. As you write more complex programs you will find you need many similar variables in one program. If you were going to read in 10 pupils marks you could have 10 individual variables. Dim mark1 as integer Dim mark2 as integer Dim mark3 as integer Dim mark4 as integer Dim mark5 as integer Dim mark6 as integer Dim mark7 as integer Dim mark8 as integer Dim mark9 as integer Dim mark10 as integer This would also require 10 input statements Mark1 = inputbox(“Please enter Mark 1”) Mark2 = inputbox(“Please enter Mark 2”) Mark3 = inputbox(“Please enter Mark 3”) Mark4 = inputbox(“Please enter Mark 4”) Mark5 = inputbox(“Please enter Mark 5”) Mark6 = inputbox(“Please enter Mark 6”) Mark7 = inputbox(“Please enter Mark 7”) Mark8 = inputbox(“Please enter Mark 8”) Mark9 = inputbox(“Please enter Mark 9”) Mark10 = inputbox(“Please enter Mark 10”) This would require 10 variables txtMark1.text = mark1 txtMark2.text = mark2 txtMark3.text = mark3 txtMark4.text = mark4 txtMark5.text = mark5 txtMark6.text = mark6 txtMark7.text = mark7 txtMark8.text = mark8 txtMark9.text = mark9 txtMark10.text = mark10 And 10 output statements This is obviously an awful lot of repetitive code. There is a much better way of storing and using data which is related. This is using an array. Using Arrays
  • 21. An array stores a number of variables in a special data structure. If you wanted to store a large amount of one type of data then you could use an array . An array to holds them all together and treats them as one thing . The program can then refer to the whole array or any single element of the array. You would declare an array like this: Array name The number of elements in the array Array data type DIM mark(10) as Integer The memory sets aside an area divided into elements Mark 1 2 3 4 5 6 7 8 9 10 So this element is referred to as Mark(6) and this one is Mark (8) An input statement would look like this: Mark(3) = Inputbox(“Please enter mark 3) The data entered would be placed in the third element of the array.
  • 22. To eliminate the need for multiple INPUT and OUTPUT statements you would use a FOR loop for array operations. FOR counter = 1 TO 10 Mark( counter ) = Inputbox(“Please enter the mark “) NEXT counter FOR giraffe = 1 TO 10 lstResults.additem Mark( giraffe ) NEXT counter Whatever variable is used in the FOR loop is also used for the element position in the Array. As the loop goes round, the loop variable (counter or giraffe above) is incremented (goes up by one) so first time round counter = 1 and the input goes in Mark(1), next time round counter = 2 so the input goes in Mark(2) and so on. Instead of 10 input statements or 10 output statements, those three lines of code will input or output all 10 data items.
  • 23. You can also use FOR loops and arrays to take in more than one set of related data. For example if you wanted to read in 6 student names and their marks. You need to keep the names and marks separate because you might want to use the numeric data for comparisons or calculations. You will need to declare 2 arrays one for names and one for marks. You will only need one FOR loop. Name Mark Jim 37 Bob 26 Sue 52 Jan 86 John 17 Peter 79 37 26 52 86 17 79 Jim Bob Sue Jan John Peter Name Mark (1) (2) (3) (4) (5) (6) (1) (2) (3) (4) (5) (6) So this data Would be stored like this This means that the name and mark are stored in different arrays but in the same position, so could be accessed at the same time using one FOR loop
  • 24. DIM name(6) as String DIM mark(6) as Integer DIM pupil as Integer DIM result as Integer FOR pupil = 1 TO 6 name( pupil ) = Inputbox(“Please enter the name”) mark( pupil ) = Inputbox (“please enter the mark”) NEXT pupil FOR result = 1 TO 6 lstClassResults.additem name( result ) & “ “ & mark( result ) NEXT result This code uses one FOR loop to read in both the name and the mark. A different FOR loop is used to display the data in a list box.
  • 25. String Operations Visual Basic considers upper and lower case text to be different, so if you had a quiz program where the answer should be true and the user entered TRUE, when you perform the comparison to see if they got the answer right the program would say they got it wrong. You can convert string data to upper and lower case to help prevent problems like this. To convert test to upper case or lower case you would use the UCase or LCase functions. lowercase_string = LCase(string_variable) uppercase_string = UCase(string_variable) Where string_variable is the original data and lowercase_string and uppercase_string is where the converted data is stored. You can use the Len function to find out how many characters are in a string variable. It counts spaces as well as characters. You will need to store the length as a numeric variable. Numeric_variable = Len(string_variable) If string_variable = “John Smith” then numeric_variable = 10 If string_variable = “Hello” then numeric_variable = 5
  • 26. One of the operations you can do with string variables is string concatenation – this is adding the two strings together. It is as simple as this: Newstring = string1+string2 DIM initial as String DIM surname as String DIM userID as String initial = Inputbox(“Please enter your initial”) surname = Inputbox(“Please enter your surname”) userID = surname+initial INPUT : initial = V surname = Mackenzie OUTPUT : MackenzieV String Operations - Concatenation
  • 27. String Operations – Sub String A Sub string operation is where you separate part of the string value. You can take the first character, the middle three characters, the last two, the first seven. Basically you can separate whatever number of characters you want from wherever you want in the string. You need to use the Mid$ function for this: String_output = Mid$(string_input, start position, number or characters) String_out = Mid$(string_input, 2, 3 ) So if string_input = “Greetings” Then String_out = “ree” If string_input = “Computing is Fun” Then String_out = “omp” Character to start at How many characters to extract
  • 28.