Download presentation
Presentation is loading. Please wait.
1
Introduction to VB prepared by Dr. I A Moneim Reference Book Schneider
2
Visual Basic 6 Three editions: –Learning Edition –Professional Edition –Enterprise Edition Learning Edition is enough Others can also be utilized
3
Integrated Development Environment Integrated Development Environment (IDE) is a place to create your applications. It is integrated because you can virtually access all of the development tools from one screen called the interface. The IDE is also called the design environment.
4
Components of IDE The visual basic is made up of a number of components –Menu bar –Tool bar –Project explorer –Properties window –Form layout window –Toolbox –Form design –Object browser
5
Menu Bar Tool Bar Form Toolbox Form Designer Project Explorer Properties Window Form Layout Window IDE
6
Propertie s Window
7
View Code View Object Toggle Folders Project Explorer
8
Label Control Frame Control Check Box Combo Box Horizontal Scroll Bar Timer Control Shape Object OLE Control Image Object Directory List Box Picture Box Text Box Drive List Command Button Option Button List Box Vertical Scroll Bar File List Box Line Object Data Control Toolbox
9
Open Project Add Module Drop-Down List Project Wizard Dropdown List Paste Cut Undo End Start Project Explorer Window Form Layout Window Toolbox Add Standard Exe Project Add Form Menu Editor Copy Save ProjectFind Redo Break Properties Window Object Browser Data View Window Toolbar
10
Components of IDE The visual basic is made up of a number of components –Menu bar –Tool bar –Project explorer –Properties window –Form layout window –Toolbox –Form design –etc.
11
Menu Bar Tool Bar Form Toolbox Form Designer Project Explorer Properties Window Form Layout Window IDE
12
Label Control Frame Control Check Box Combo Box Horizontal Scroll Bar Timer Control Shape Object OLE Control Image Object Directory List Box Picture Box Text Box Drive List Command Button Option Button List Box Vertical Scroll Bar File List Box Line Object Data Control Toolbox
13
Introducing Controls Label: To display information Textbox: To get information Command Button: To initiate action (by clicking) Picture Box: To display text or graphics
14
The Label Information (text) is displayed only A few properties –Name –Caption –Width –Height –Font –BackColor –ForeColor Tryout the Label Walkthrough
15
The Textbox Information can be typed in at run time A few properties –Name –Height –Width –Text –Font –BackColor –ForeColor –Multiline Tryout the Text Box Walkthrough
16
The Command Buttons For initiating an action by clicking A few properties –Name –Caption: Ampersand (&) can also be used –Width –Height –Font –BackColor Tryout the Command Button Walkthrough
17
The Picture Box To display text or graphics A few properties –Name –Picture –Width –Height –Autosize –BackColor Tryout the Picture Box Walkthrough
18
The Form Object Control menu Caption Title Bar Min Button Max/Restore Close Button Border
19
The Form object NameCaption WidthHeight BackColorBorderStyle LeftTop StartUpPositionMaxButton MinButtonPicture Window for designing the user interface A few properties:
20
Setting Properties Setting free text properties 1.Select the property 2.Type the new value 3.Press ENTER or select a different property.
21
Setting Enumerated Properties The ENABLED properties can only be TRUE or FALSE. There are properties that have more than 2 possible values. These are represented by ENUMERATED properties.
22
Example For example to select the Start up position of a Form can be selected by RIGHT CLICKING on the arrow facing downward and toggling through all the possible values.
23
Setting Properties with Property Pages Some properties are more complex than others. Some properties require the use of property pages to select a value from them. An ellipse appears on the right of the property if it has a property page. One such example is the FONT property.
24
Font Property Page
25
Visual Basic Events Event : Action taken by the user e.g. –Clicking a Control –Double Clicking a Control –Getting Focus –Losing Focus etc.
26
Visual Basic Events (Contd.) Naming of Events –Clicking a Command Button 1 Command1_Click –Double Clicking a Picture Box 2 Picture2_DblClick –Text box 1 gets Focus Text1_GotFocus –Text box 1 loses Focus Text1_LostFocus
27
Visual Basic Events (Contd.) Names of events => objectName_event Events are pre-defined
28
Event Procedure Event Procedure: block of code to be executed when an event occurs General form Sub objectName_event() statements End Sub
29
Event Procedure (Contd.) E.g: Sub Command1_Click() statements End Sub Sub Text1_GotFocus() statements End Sub
30
Sub Text1_KeyPress(KeyAscii as Integer) statements End Sub Text1_KeyPress event will occur when Text1 has the focus and a key is pressed The Keypress Event Procedure
31
Sub Text1_KeyPress(KeyAscii as Integer) statements End Sub Keyascii –is a variable (of type Integer) –gets the ANSI value of the pressed key –value is used to display the corresponding character in the Text1 at the end of this procedure The Keypress Event Procedure (Contd.)
32
What will happen in these cases? Sub Text1_KeyPress(KeyAscii as Integer) Let KeyAscii =65 End Sub Sub Text1_KeyPress(KeyAscii as Integer) Let KeyAscii =0 End Sub The Keypress Event Procedure (Contd.)
33
Already known: –String –Single –Integer Data Types
34
Strings Storage: 10 bytes + string length Range: 0 to app. 2 billions chars. Declaration: Dim strVarLen As String (declares a string of a variable length) Data Types (Contd.)
35
Fixed-Length Strings Storage: Length of string Range: 1 to app. 65, 400 chars. Declaration: Dim strFixLen As String * 2 (declares a string of a fix size of 2 chars.) Data Types (Contd.)
36
Fixed-Length Strings Usage: Example Dim strText As String * 5 Let strText = “ Hello ” Picture1.Print strText Let strText = “ H ” Picture1.Print strText Let strText = “ HelloWorld ” Picture1.Print strText Data Types
37
Fixed-Length Strings Usage: Result: Hello(Complete string) H …. (H followed 4 spaces) Hello(First 5 characters only) => The length is fix Data Types
38
Integers Storage: 2 bytes Range: -32,768 to 32,767 Declaration: Dim intExample As Integer (declares intExample as an Integer variable) Data Types (Contd.)
39
Integers Usage: Example Dim count As Integer Let count= 6 Picture1.Print count Let count= count+1 Picture1.Print count Let count= 6/5 Picture1.Print count Let count= 2.33333 * 2 Picture1.Print count Data Types
40
Integer Usage: Result 6 7 1 (rounding to lower value) 5(rounding to higher value) => takes only whole number values Data Types
41
Long (Integer) Storage: 4 bytes Range: -2,147,483,648 to 2,147,483,647 Declaration: Dim lngExample As Long (declares lntExample as a long variable) Data Types (Contd.)
42
Long (Integer) Usage: Same as Integer Type except the range is much larger Data Types (Contd.)
43
Byte Storage: 1 byte Range: 0 to 255 Declaration: Dim bytExample As Byte (declares bytExample as a Byte type variable) Data Types (Contd.)
44
Byte Usage: Same as Integer Type except the range is positive and much smaller Data Types (Contd.)
45
Boolean Storage: 2 bytes Range: TRUE(1) or FALSE(0) Declaration: Dim blnState As Boolean (declares a Boolean type variable blnState) Data Types (Contd.)
46
Boolean Usage: Example Dim blnExample As Boolean Let blnExample= FALSE Picture1.Print blnExample Let blnExample= 1 Picture1.Print blnExample Let blnExample= 6 Picture1.Print blnExample Let blnExample= -8*7+5.2 Picture1.Print blnExample Data Types (Contd.)
47
Boolean Usage: Example FALSE TRUE =>Values other than 0 are TRUE Data Types (Contd.)
48
Single (Precision Floating-Point) Storage: 4 bytes Range: -3.4 … E38 to -1.4 … E-45 (negative) 1.4 … E-45 to 3.4 … E38 (positive) Declaration: Dim sngAverage As Single (declares a Single type variable sngAverage) Data Types (Contd.)
49
Double (Precision Floating-Point) Storage: 8 bytes Range: -1.7 … E308 to -4.9 … E-324 (negative) 4.9 … E-324 to 1.7 … E308 (positive) Declaration: Dim dblAverage As Double (declares a Double type variable dblAverage) Data Types (Contd.)
50
Double Usage: Example Dim sngValue As Single, dblValue As Double Let sngValue= 1/3 Picture1.Print sngValue Let dblValue= 1/3 Picture1.Print dblValue Data Types (Contd.)
51
Double Usage: Result 0.3333333(Single precision) 0.333333333333333 (Double precision) => Value of 1/3 represented more accurately by double than by single Data Types (Contd.)
52
Double Usage: Example Dim sngValue As Single, dblValue As Double Let sngValue= 1/3 Let sngValue= sngValue * 100000 Picture1.Print sngValue Let dblValue= 1/3 Let dblValue= dblValue * 100000 Picture1.Print dblValue Data Types (Contd.)
53
Double Usage: Result 33333.34(Single precision; rounding error) 33333.3333333333 (Double precision) => - The decimal point is floating; - Eventually both will be subjected to rounding errors value increases to large values - Still Double will remain more precise than Single Data Types (Contd.)
54
Currency Storage: 8 bytes Range: -922,337,203,685,477.5808 to 922,337,203,685,477.5807 Declaration: Dim curRevenue As Currency (declares a Currency type variable curRevenue) Data Types (Contd.)
55
Currency Usage: Example Dim curValue As Currency Let curValue= 1/3 Picture1.Print curValue Let curValue= 100*1/3 Picture1.Print curValue Data Types (Contd.)
56
Currency Usage: Result 0.3333 33333.3333 =>- The decimal point is NOT floating; - Could be used for currency and scientific research - No rounding problems for high values Data Types (Contd.)
57
Even more data types –Date Variable: for date and time –Object Variable –Variant Variable –………. Read the book for more info. Data Types (Contd.)
58
Not only +,-,*,^ But also: \ opeartor e.g: 5.1\2.04= 2 MOD operator e.g: 15.2 MOD 6=3 More on Operators
59
More on Operators (Contd.) Operator Precedence 1. ^ 2.- operator (indicating a negative value) 3. * and / operator 4. \ operator 5. MOD operator 6. + and - operator
60
Statements?
61
VB Statements Statements to change the properties of an object the general form: Let objectName.property = setting
62
Statements (Contd.) Let objectName.property = setting E.g: Let Text1.FontSize = 12 Let Text1.FontBold = TRUE Let Text1.Text = “ ”
63
Event Procedure (Contd.) Event procedure – general form Sub objectName_event() statements End Sub Example Sub Command1_Click() Let Text1.text = “” Let Text2.text= “ Hello ” End Sub
64
Viewing Code Margin Indicator Bar Procedure View Full Module View Object Box Procedures List Box Split Bar
65
Methods Another category of statements based on methods
66
Methods (Contd.) E.g: –Picture1.Cls Clears Picture1 Picture Box –Picture1.Print 3 Prints ‘ 3 ’ in the Picture1 Picture Box
67
Methods (Contd.) General form of these statements => objectName.Method parameters (if any)
68
The Print Method Picture1.Print m? Picture1.Print m; ? Picture1.Print m; n; r ? m, n, r are numbers e.g. 3, 5.2
69
Numbers Numeric Constants – 2, 5.6, 9, 10.005 Arithmetic Operations –Addition (2+3) –Subtraction (2-3) –Multiplication (2*3) –Division (2/3) –Exponentiation (2^3)
70
Numbers (Contd.) Numeric Expressions e.g. –(2+3)/5 –(5+2) * (2- 10/2) –2.5*2-3^2+14/7
71
Numbers (Contd.) How will this be calculated? –2+10/5 –5+2* 2- 1/10 –4*6-3^2+5/10 –3^2*5
72
Numbers (Contd.) Operator Precedence 1. ^ 2.- operator (indicating a negative value) 3. * and / operator 4. + and - operator
73
Numbers (Contd.) Use parenthesis ( ) to keep intentions clear (2+2)*2? 2+2*2? (5+ (5*2))/(2+1) ?
74
Strings E.g: –“ hello ” –“ 9/17/95 ” –“ 2+3 ”
75
What will be printed? Picture1.Print 2*3+2 Picture1.Print “ hello ” Picture1.Print “ 2*3+2 ”
76
Scientific Notation E=Exponent => Exponent of 10 E.g. – 1.2E+04 = 1.2 * 10^4 = 12000 – 1.2E+34 = 1.2 * 10^34 –1E-02 = 1 * 10^-2 =.01
77
Scientific Notation (Contd.) Display notation (Scientific or Standard) depends on magnitude
78
What this code will do? Let num1 = 6 Picture1.Print num1
79
Variables (Contd.) Conclusions: A variable holds a value The value can be assigned and then used
80
Variables (Contd.) What will this code do? Let result = 100*4 Picture1.Print result
81
Variables (Contd.) What will this code do? Let speed=50.3 Let timeElapsed =2 Let distance = speed*timeElapsed Picture1.Print distance
82
Variables (Contd.) Conclusions: The General Form: Let var = expression e.g.: Distance=speed*timeElapsed c= a*(2.2+b)+6 counter=counter+1
83
String Variables Sub Command1_Click () Picture1.Cls Picture1.Print “ hello ” Let today = “ 9/17/95 ” Let message = “ students of CS101 ” Picture1.Print today Picture1.Print “ hello ” ; message End Sub
84
String Variables (Contd.) Result: hello 9/17/95 hellostudents of CS101
85
String Variables (Contd.) Concatenation (use + or &) Sub Command1_Click () Picture1.Cls Let message_part1 = “ hello ” Let message_part2 = “ students of CS101 ” Let message= message_part1+message_part2 Picture1.Print message Picture1.Print message + “ on Sept. 19,2002 ” Let message= message_part1 & “ world ” Picture1.Print message End Sub
86
String Variables (Contd.) Displayed Result hellostudents of CS101 hellostudents of CS101 on Sept. 19,2002 hello world
87
Declaring Variable Types Dim var As String Dim var As Single
88
Declaring Variable Types (Contd.) Example program: Sub Command1_Click () Dim interestRate As Single Dim principal As Single Dim phrase as String Picture1.Cls Let InterestRate=.0655 Let principal =100 Let phrase = “ The balance after a year is ” Picture1.Print phrase;(1+interestRate)*principal End Sub
89
Declaring Variable Types (Contd.) Displayed Result: The balance after a year is 106.55
90
Declaring Variable Types (Contd.) Different ways of declaration –Dim interestRate As Single, principal As Single, phrase As String –Dim name$ (same as Dim name As String) –Dim price! (same as Dim price As Single) –Use the type declaration tag while using it E.g.: Let name$ = “ John ” Let price! = 65.66
91
Input/Output Using Text Box Contents of a text box is always a string Output the string by –Let Text1.Text= strvar Input the string by –Let strVar =Text1.Text
92
Input/Output Using Text Box (Contd.) Numbers in a textbox are also stored as strings Input a number by –Let numVar = Val(Text1.Text) Output a number by –Let Text1.Text=Str$(numVar)
93
Another example: Sub Command1_Click() Picture1.Cls Let rate = 50 Let timeElapsed = 14 Let distance = rate * timeElapsed Picture1.Print distance Let distance = 410 Let timeElaspsed = distance / rate Picture1.Print timeElapsed End Sub
94
Built-in Functions Take one or more input values Return an output value Already seen: –Val(..), Str$(..), Asc(..), Chr(..)
95
Built-in Numeric Functions Sqr: calculates square-root and returns the value as double data type e.g: –Sqr(9) is 3 –Sqr(0) is 0 –Sqr(2) is 1.414214 –Sqr(30*2+4) is 8
96
Built-in Numeric Functions Int: Greatest integer less than and equal to a number e.g: –Int(2.7) is 2 –Int(3) is 3 –Int(-2.7) is -3
97
Built-in String Functions Left$, Mid$, Right$, UCase$, Trim$ Left$( “ fanatic ”, 3) is “ fan ” Right$( “ fanatic ”, 3) is “ tic ” Left$( “ 12/15/93 ”,2) is “ 12 ” Right$( “ 12/15/93 ”, 2) is “ 93 ” Mid$( “ fanatic ”, 5,1) is “ t ” Mid$( “ 12/15/93 ”,4, 2) is “ 15 ” Ucase( “ Disk ” ) is “ DISK ” Ucase( “ 12two ” ) is “ 12TWO ” Trim$( “ 1 2 ” ) is “ 1 2 ” Trim$( “ -12 ” ) is “ -12 ”
98
Built-in Functions (Contd.) Len Len( “ Shenandoah ” ) is ? Len( “ Just a moment ” ) is ? Len( “ m ” ) is ?
99
Built-in Functions (Contd.) Len Len( “ Shenandoah ” ) is 10 Len( “ Just a moment ” ) is 13 Len( “ m ” ) is 1
100
Built-in Functions (Contd.) Instr Instr( “ Shenandoah ”, “ nand ” ) is ? Instr( “ Just a moment ”, “ ” ) is ? Instr( “ Croissant ”, “ ist ” ) is ?
101
Built-in Functions (Contd.) Instr Instr( “ Shenandoah ”, “ nand ” ) is 4 Instr( “ Just a moment ”, “ ” ) is 5 Instr( “ Croissant ”, “ ist ” ) is 0
102
Built-in Functions (Contd.) Format$ Format$(num, fmt) num: number, numeric expression, string of a number fmt: format string Result => String consisting of a formatted version of the number
103
Built-in Functions (Contd.) FunctionString Value Format$(12345.628, “ Standard ” )12,345.63 Format$(12345.628, “ Currency ” )$12,345.63 Format$(-1234, “ Standard ” )-1,234.00 Format$(-1234, “ Currency ” )($1,234.00) =>Result: two digits after decimal; Commas every three places to the left of the decimal point; leading ‘ $ ’ sign for currency
104
Built-in Functions (Contd.) FunctionString Value Format$(1/4, “ Standard ” )? Format$( “.2 ”, “ Currency ” )? Format$(-1234.8, “ Currency ” )?
105
Built-in Functions (Contd.) FunctionString Value Format$(1/4, “ Standard ” )0.25 Format$( “.2 ”, “ Currency ” )$0.20 Format$(-1234.8, “ Currency ” )($1,234.80)
106
Built-in Functions (Contd.) FunctionString Value Format$(12345.628, “ #,0 ” )12,346 Format$(-3.6, “ #,0 ” )-4 =>Result: Rounded; Commas every three places to the left of the decimal point
107
Built-in Functions (Contd.) FunctionString Value Format$(123.82, “ #,0 ” )? Format$(-3.2, “ #,0 ” )?
108
Built-in Functions (Contd.) FunctionString Value Format$(12345.628, “ Percent ” ) 1234562.80% =>Result: Multiplied by 100; trailing % sign; two digits after decimal
109
Built-in Functions (Contd.) FunctionString Value Format$(.06265, “ Percent ” )? Format$(1/8, “ Percent ” )?
110
Built-in Functions (Contd.) FunctionString Value Format$(.06265, “ Percent ” )6.27% Format$(1/8, “ Percent ” )12.50%
111
Built-in Functions (Contd.) FunctionString Value Format$(12345.628, “ Scientific ” )1.23E+04 =>Result: first number between 1 and 9.99 and of two digits after decimal; Exponent value preceded by E and sign;
112
Built-in Functions (Contd.) FunctionString Value Format$(-600.228, “ Scientific ” )? Format$(1/8, “ Scientific ” )?
113
Built-in Functions (Contd.) FunctionString Value Format$(-600.228, “ Scientific ” )-6.00E+02 Format$(1/8, “ Scientific ” )-1.25E-01
114
Built-in Functions (Contd.) Formatting dates: FunctionString Value Format$( “ 7/4/96 ”, “ Long Date ” )Thursday, July 4, 1996 Format$( “ 7/4/96 ”, “ Medium Date ” ) 04-Jul-96
115
Built-in Functions (Contd.) Fixed length string formatting: FunctionString Value Format$(1234567890, “ @@@@@@@@@@ ” )? Format$(123, “ @@@@@@@@@@ ” )? Format$( “ 1234.56 ”, “ @@@@@@@@@@ ” )? Format$( “ $1,234.56 ”, “ @@@@@@@@@@ ” )? Format$(1/4, “ @@@@@@@@@@ ” )?
116
Generating Random Numbers The function: Rnd Generates a random number from 0 up to but not including 1 Picture1.Print Rnd ‘ print a different number each time Let numvar= Rnd ‘ a random value is assigned
117
Generating Random Numbers (Contd.) The function: Rnd Display numbers from the set {1,2,3,4,5,6} randomly!
118
Generating Random Numbers (Contd.) The statement: Randomize Timer?
119
Generating Random Numbers (Contd.) The statement: Randomize Timer Sub Command1_Click ( ) Rem Display a lottery number Picture1.Cls Randomize Timer Picture1.Print Int(10*Rnd); Picture1.Print Int(10*Rnd) End Sub
120
Built-in Functions (Contd.) Abs(10) is 10 Abs(-10) is 10 Sgn(10) is 1 Sgn(0) is 0 Sgn(-10) is -1
121
Subprograms /Subroutines
122
Subprograms (Contd.) General Format Sub SubprogrammeName (list of parameters) statements End Sub
123
Subprograms (Contd.) Example 1 Sub ExplainPurpose ( ) Rem Explain the task performed by the program Picture1.Print “ This program displays sentences ” Picture1.Print “ identifying pairs of numbers and their sums. ” End Sub
124
Subprograms (Contd.) Example 2 Sub Add ( num1 As Single, num2 As Single ) Rem Display numbers and their sum Picture1.Print “ Sum of ” ; num1; ” and ” ; num2; ” is ” ; num1+num2 End Sub
125
Subprograms (Contd.) Examples: Sub ExplainPurpose ( ) Rem Explain the task performed by the program Picture1.Print “ This program displays sentences ” Picture1.Print “ identifying pair of numbers and their sums. ” End Sub Sub Add ( num1 As Single, num2 As Single ) Rem Display numbers and their sum Picture1.Print “ Sum of ” ; num1; “ and ” ; num2; “ is ” ; num1+num2 End Sub
126
Subprograms (Contd.) Using subprograms in a Program Sub Command1_Click( ) Rem Display the sum of several pairs of numbers Picture1.Cls Call ExplainPurpose Picture1.Print Call Add(2, 3) Call Add(4, 6) Call Add(7, 8) End Sub
127
Subprograms (Contd.) The Program ’ s result This program displays sentences identifying pair of numbers and their sums. Sum of 2 and 3 is 5 Sum of 4 and 6 is 10 Sum of 7 and 8 is 15
128
Subprograms (Contd.) Using subprograms in a Program Sub Command1_Click( ) Dim x As Single, y As Single, z As Single Picture1.Cls Let x = 2 Let y = 3 Call Add(x,y) Call Add(x+2, 2 * y) Let z = 7 Call Add(z, z+1) End Sub
129
Subprograms (Contd.) The Program ’ s result This program displays sentences identifying pair of numbers and their sums. Sum of 2 and 3 is 5 Sum of 4 and 6 is 10 Sum of 7 and 8 is 15
130
Subprograms (Contd.) Writing subprograms for a Program Sub Command_Click( ) Dim x As Single, y As Single, z As Single Picture1.Cls Call ComputeWage( “ Aslam ”, 5, 100) Call ComputeWage( “ Saleem ”, 6, 90) End Sub Result: Wage of Aslam is Rs. 500 Wage of Saleem is Rs. 540
131
Subprograms (Contd.) The Subprogram ComputeWage: Sub ComputeWage(Name As String, hourlyRate As Single, hours As Single) Rem Compute and displays employees wage Dim wage As Single wage = hourlyRate*hours Picture1. Print Name; ” wage is ” ; wage End Sub
132
Note: Read: Schneider (Section 4.1) Read Comments in Section 4.1 Do practice problems 4.1 Attempt questions of Exercise 4.1
133
Subprograms: Passing Variables Example 1: Subroutine Sub Triple( num As Single) Rem Triples a number Picture1.Print num; Let num = num*3 Picture1.Print num; End Sub
134
Subprograms: Passing Variables Example 1: Program Sub Command1_Click( ) Dim amt As Single Picture1.Cls Let amt=2 Picture1.Print amt; Call Triple(amt) Picture1.Print amt End Sub
135
Subprograms: Passing Variables Example 1: Result 2 2 6 6 => Variable was passed by reference in Example 1
136
Variable Passing by Val!
137
Subprograms: Passing Variables Example 2: Program Sub Command1_Click( ) Dim amt As Single Picture1.Cls Let amt=2 Picture1.Print amt; Call Triple((amt)) ‘ extra parentheses Picture1.Print amt End Sub
138
Subprograms: Passing Variables Example 2: Result 2 2 6 2 => Variable was passed by value in Example 2
139
Subprograms: Passing Variables Example 3: Subroutine Sub Triple( ByVal num As Single) Rem Triples a number Picture1.Print num; Let num = num*3 Picture1.Print num; End Sub
140
Subprograms: Passing Variables Example 3: Program Sub Command1_Click( ) Dim amt As Single Picture1.Cls Let amt=2 Picture1.Print amt; Call Triple(amt) Picture1.Print amt End Sub
141
Subprograms: Passing Variables Example 3: Result 2 2 6 2 => Variable was passed by value in Example 3 By default: Variable passing by reference To be precise you may use ByRef as in: Sub Triple( ByRef num As Single)
142
Subprograms: Local Variables Example 1 Sub Command1_Click( ) Picture1.Cls Call Three End Sub Sub Three( ) Dim num As Single Picture1.Print num Let num=3 Picture1.Print num End Sub
143
Subprograms: Local Variables Example 1: Result 0 3 => The variable num is local to the Subprogram; Lives only for the time the Subprogram is called; Initialized each time
144
Subprograms: Local Variables Example 2 Sub Command1_Click( )Sub Trivial ( )Dim x As Single Picture1.ClsPicture1. Print x; Let x = 2Let x = 3Picture1.Print x; Call TrivialEnd Sub Picture1.Print x; Call Trivial Picture1.Print x; End Sub
145
Subprograms: Local Variables Example 1: Result 2 0 3 2 0 3 2 => The variable x has separate identities in the Event procedure and in the subroutine
146
Subprograms: Form-Level Variables Example 1 Dim num1 As Single, num2 As Single Sub Command1_Click( )Sub AddAndIncrement ( ) Let num1 =2Picture1.Print num1+num2 Let num2 =3Let num1= num1+1 Picture1.ClsLet num2=num2+1 Call AddAndIncrementEnd Sub Picture1.Print Picture1.Print num1 Picture1.Print num2 End Sub
147
Example 1: Result 5 3 4 => The variable num1 and num2 known to all subprograms Subprograms: Form-Level Variables
148
Example 2 Dim pi As Single Sub Form_Load( ) Let pi = 3.14159 End Sub Sub Command1_Click ( ) Picture1.Cls Picture1.Print “ Circle area is: ” pi*5^2 End Sub
149
Example 2: Result Circle area is: 78.53975 => The variable pi is initialized in Form_load event Subprograms: Form-Level Variables
150
Functions
151
General Format : Subroutine Sub SubprogrammeName (list of parameters) statements End Sub General Format : Functions Sub FunctionName (list of parameters) As datatype statements FunctionName = expression End Function
152
Functions Examples: Function FtoC (t As Single) As Single FtoC = (5/9)*(t-32) End Function Function FirstName$ (nom As String) Dim firstSpace As Integer Rem Extract the first name from the full name nom Let firstSpace = Instr(nom, “ ” ) FirstName$ = Left$(nom, firstSpace-1) End Function
153
Functions Using function in a program Sub Command1_Click Dim x As Single Picture1.Print FtoC(212) x = FtoC(32) Picture1.Print x x = FtoC(81+32) Picture1.Print x End Sub
154
Functions (Contd.) Result: 100 0 45
155
Practice Problem Function Cider (g As Single, x As Single) As Single Cider=g*x End Function Sub DisplayNumOfGallons(galPerBu, apples As Single) Picture1.Cls Picture1.Print “ You can make ” ; Cider(galPerBu, apples); Picture1.Print “ gallons of cider. ” End Sub Sub GetData (gallonsPerBushel As Single, apples As Single) Let gallonsPerBushel =3 Let apples =9 End Sub Functions (Contd.)
156
Practice Problem Sub Command1_Click Rem How many gallons of apple cider can we make Dim gallonsPerBushel As Single, apples as Single Call GetData(gallonPerBushel, apples) Call DisplayNumOfGallons(gallonsPerBushel, apples) End Sub
157
Functions (Contd.) Practice Problem: Result You can make 27 gallons of cider
158
Modular Design Top-Down Design Structured Programming –Sequences –Decisions –Loops
159
Note: Read: Schneider (Section 4.2,4.3, 4.4) Read comments and do practice problems of these sections Attempt questions of Exercises
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.