Академический Документы
Профессиональный Документы
Культура Документы
Introduction
Computer language has certain rules for constructing statements. Syntax (structure of a statement) must be correct. Computer cannot understand your program unless you follow the strict syntax rules. The programmer has to identify various types of values. Although VB do not require data declaration, in this class we will explicitly declare all data types to indicate our understanding of the data. By doing so the compiler can then perform additional error checking.
The programmer will also has to distinguish between data that may change and those rarely, if ever, change. Values that may often change are classified as variables. Values That rarely change are classified as constants.
Program is a set of instructions (code) for the computer to follow to complete a specific task.
VB program generally consists of one or more section of code, called event procedure, each containing a set of VB program statements. In VB, an event procedure always starts with Private Sub and ends with End Sub.
Private Sub cmdKlik_Click . We will look at what . are the statements that we can write-in here . - VB statements End Sub
VB Statements
Every Visual Basic statement contains some combination of the following: 1. 2. 3. 4. Keywords or reserved words Literals or constants Variables Operators or special symbols
1. Keywords Words or symbols that VB recognizes as having some predefined meaning as part of VB programming language
Examples
property names
We will learn more keywords as we progress
VB Statements (contd)
2. Literals (or Constants)
Specific values that we want to use in a program Often used to set an initial value of something Can be classified into two types: strings & numeric String Literals any sequence of characters surrounded by quotation marks
Examples
VB Statements (contd)
Numeric Literals used when working with numbers
combination of the digits 0 to 9, and may contain one decimal point and/or a sign (+/-) at the beginning cannot begin with a decimal point Example of valid and invalid numeric literals Valid
21 -308 3.14159 0.125 700000 700000.125 4922.11.3 .06 RM10,456.00 124
Invalid
(765)432-1111
String Concatenation
Concatenate means to join two or more character strings into a single, longer, character string Use & operator Examples
Fakulti & Kejuruteraan & Awam returns FakultiKejuruteraanAwam Fakulti & & Kejuruteraan Awam returns Fakulti Kejuruteraan Awam Fakulti & Kejuruteraan & txtKursus.text returns Fakulti Kejuruteraan ? Fakulti & Kejuruteraan & kod returns Fakulti Kejuruteraan
?
The value of text property of txtKursus control
Continue a long vb statements to two or more lines by using the space and underscore ( _ ) characters at the end of each line. When you combine line continuation and string concatenation in the same statement, you close a partial string with a or complete the name of an object before using the line continuation symbol. To force VB to print string on a new line use reserve word vbnewline. lblmessage.caption= Hello & txtname.text & _ vbnewline & Welcome to My Class. & _ This is a Visual Basic Class for _
Comments
Words of explanation within a program that provide information for other programmers (also yourself) who need to use or update the program in future. May include: purpose of the program. name of person who wrote or revised it. when it was written. clarify the purpose of a block of code within a larger program.
comments begin with an apostrophe ( )
PROGRAM : PURPOSE :
VB Statements (contd)
3. Variables A variable can be defined as a location in the computers memory that has the programmer-given name.
This is the place where the programmer store values that change from one use of the program to another or that changes while the program is running.
The programmer must decide on the name and also indicate what data type will be stored in that memory location. The data type affects how much memory is allocated for the variable.
Data Types
Data type
Boolean Currency Date Double Integer
Description
Logical data (2 bytes) Monetary values (8 bytes) Date and time (8 bytes) High precision floating point numbers (8 bytes) Small integer numbers (2 bytes) True or false
Range
15 digits to the left of the decimals, four digits to the right of the decimals January 1,0100 to December 31,999 Floating point numbers up to 14 digits of accuracy -32,768 to 32,767
Long
Single String
-2,147,483,648 to 2,147,483,647
Floating point numbers up to 6 digits of accuracy Varies based on the size of string
Variant
Dependent upon what is being stored, should NOT be used under normal circumstances
Variables
Before a variable may be used, the programmer has to declare the variable by specifying a name and a data type. Variables are typically grouped together at the beginning of an event procedure. The first time a variable is used it should appear on the left side of an assignment statement to receive its initial value.
The expression on the RHS of an assignment statement is evaluated before an assignment is made.
N = N+1
This is OK
VB Variable Naming Requirements Must not exceed 255 characters. Must begin with a letter. Cannot contain an embedded period, space or type-declaration character. Must be unique. Cannot be the same as a keyword. Not case sensitive. Standard Guidelines for Naming Variables Be meaningful and descriptive.
(Ex. Load, Span, Width)
Use mixed case, with a capital letter at the start of each new word.
(Ex. PtLoad, ICNo, MatrixNo)
Declaring Variables
Variable declarations are typically grouped together at the beginning of an event procedure. The general format : Dim VariableName As Type
Example
Dim Nama As String Dim BilPelajar As Integer Dim PointLoad As Single When we include Option Explicit in our programs, all variables must be declared before they can be used. To automatically include the Option Explicit statement at the beginning of every program code, select from the menu;
Data Conversion
Input and output information displayed on a form through textbox & label are stored as a string in the property of the controls. This information can be directly copied to a string variable by using the assignment (=) operator. If the information is made up of numeric characters and we want to store it as a numeric variable, so that we can perform mathematical calculation, we have to convert the information to numeric form using conversion functions.
Example,
Distance = Val(txtJarak.text) CreditHour= CInt(txtCredit.text) CPA = CSng(txtCPA.text) Please refer to the supplementary notes on Conversion Functions
Variables are often used in assignment statements along with control properties and literals. Statements Explanation
Declaring variable Name as data type string
Assigning the string entered into textbox txtName to variable Name Declaring variable Width and Depth as Single Val( ) a function to convert string to numbers Convert the string in textbox to numbers and assign it to a variable Declaring Variable Assigning the strings in textboxes to variables
Depth = Val(txtDepth.text)
Dim Message as String Name = txtName.text Age = txtAge.text
Message = Hello & Name & _ vbnewline & You are & Age & _ years old
Constants
Constants, like variables, are named storage locations in memory VB prevents the value of a constant from being changed during program execution Two types of Constant a) Symbolic constant b) User-Defined constant a) Symbolic Constant Names assigned to most widely used values in VB
Colour Constants
w w w w w w w w w Constant Value Description vbBlack 0x0 vbRed 0xFF vbGreen 0xFF00 vbYellow 0xFFFF vbBlue 0xFF0000 vbMagenta 0xFF00FF vbCyan 0xFFFF00 vbWhite 0xFFFFFF Black Red Green Yellow Blue Magenta Cyan White
Constants (contd)
Symbolic constant example
Constants (contd)
b) User-Defined Constant Constant defined by the user to be used in VB. Syntax, Const NAME As Type = value
Example,
Numeric
String
Variable
Constant
Variable
Constant
Variable
VB Statements (contd)
4. Operators Three types of Operators Arithmetic Operators Comparison Operators Logical Operators
a) Arithmetic Operators
Operator
^
Operation
exponential
*,/ \
Mod
1)
\ and Mod Prior to division, the dividend & divisor are rounded to integer. The result of \ is rounded (truncated) to the direction of zero.
2)
+,-
Arithmetic Operators
Expression 9.2/1.6 9.2\1.6 Value 5.75 4
9.2mod1.6
9.2^1.6 17^5 Rules of precedence
1
34.84 1419857.0
Operations with the higher precedence are evaluated prior to Operations with equal precedence are performed from left to
Arithmetic to VB Expressions
Normal Arithmetic Expression Equivalent VB Statement
Area = b*h Ixx = b*h^3/12
Speed = (distance * 1e3)/(time*3.6e3) M= (P*( L a) * x / L) (P * ( x a)) k = M / (b * d ^2 * fcu) z = d * ( 0.5 + (0.25 k/0.9)^0.5) As = M / (0.8 * fy * z)
A=3
B=4 C =A+ B A=C*A
3 3 4
3
21 21 21
4
4 4 16
7
7 7 7
picResults.Print A - B
B=B*B End Sub
Operators (contd)
b) Comparison Operators (Relational)
Operator > < Comparison
Greater than Less than
>=
<= = <>
All have the same precedence; they are evaluated in order of appearance from left to right. Compare values of literals, variables and control properties. Placed between two values and returns a Boolean value. Values must be compatible types, eg. String to string, number to number. Use conversion functions when required.
The ANSI (ASCII) code values determine whether one character is greater than another in a string comparison; general rule 0<9<A<Z<a<z. Table below shows a few of the values. ANSI 32 33 34 35 48 49 57 65 Characters (space) ! # 0 1 9 A ANSI 66 90 97 98 122 123 125 126 Characters B Z a b z { } ~
Rs>= 0
StuName=Anis StuName<> 123>9 123 > 9
True
False True True False
(Credit*3-25)> 0
True
c)
Operators (contd)
Operation Logical not (reversing its Boolean value) Logical and Logical or
AND returns true when both relations expressions are true. OR returns true as long as at least one of the relations
expressions is true.
In general arithmetic operators are evaluated first, then relational operators, and logical operators are evaluated last.
9
10 11 10 11
Ali
Lau Ani
True
True False False False
True
True True True False
We will use comparison and logical operators later in selective and repetitive structures.
Example
2.
Form Event
Arithmetic operator Command buttons & label Click Event show result
32
Example 4 (contd)
Flowchart
Arithmetic Operator Buttons
Start
Get the 2 numbers Carry out the appropriate Arithmetic operation End Display the results in the label
Exit Button
Start
End
Example 4 (contd)
Test Plan
Sample Input Expected Output
Add 2 and 5
Subtract 5 from 9 Multiply 3 and 7 Divide 8 by 4
7
4 21 2
34
Example 4 (contd)
3. Interface Input controls: two textboxes and labels Processing needs: 4 arithmetic operation buttons & an exit button Output Needs: One label to display the results
Label1
Label2
txtFirstNo txtSecondNo
cmdDivide cmdSubtract
lblResult
cmdEnd
35
Example 4 (contd)
Value of Property
Commandbutton: cmdSubtract
Commandbutton: cmdMultiply Commandbutton: cmdAdd Label: lblResult Commandbutton: cmdEnd Label: Label1
Caption Font
. . Caption Caption Caption Font Caption font
Label: Label2
36
Example 4 (contd)
4. Coding The coding for the command buttons is then written, i.e. event procedures
Option Explicit Dim No1 As Single, No2 As Single, Result As Single Private Sub cmdDivide_Click()
No1 = Val(txtFirstNo.Text) No2 = Val(txtSecondNo.Text) Result = No1 / No2 lblResult.Caption = txtFirstNo.Text & " DIVIDED BY " & _ txtSecondNo.Text & " EQUALS TO " & Result
End Sub Private Sub cmdAdd_Click()
No1 = Val(txtFirstNo.Text) No2 = Val(txtSecondNo.Text) Result = No1 + No2 lblResult.Caption = txtFirstNo.Text & " PLUS " & _ txtSecondNo.Text & " EQUALS TO " & Result
End Sub
37
Example 4 (contd)
Coding (contd)
Private Sub cmdMultiply_Click()
No1 = Val(txtFirstNo.Text) No2 = Val(txtSecondNo.Text) Result = No1 * No2 lblResult.Caption = txtFirstNo.Text & " TIMES " & _ txtSecondNo.Text & " EQUALS TO " & Result
End Sub
No1 = Val(txtFirstNo.Text) No2 = Val(txtSecondNo.Text) Result = No1 - No2 lblResult.Caption = txtFirstNo.Text & " MINUS " & _ txtSecondNo.Text & " EQUALS TO " & Result
End Sub
End
End Sub
38
Example 4 (contd)
5. Test & Debug After testing and debugging the the program is now competed. When the program is run
Enter numbers 8 and 4 in the textbox, then click
Example 4a Triangle
Problem: Write a program to calculate the length of the sides, perimeter and area triangle where the coordinates of the sides are known.
The program should: Provide facility for the user to enter input data. Display the side lengths, perimeter and area. Provide a read-me message on different form.
Example 4a Triangle
Algorithm Input x & y coordinates of the points Calculate the length of the sides Add the side length to get the perimeter Calculate the area Display results Equations Length = [(x1-x2)2+(y1-y2)2] 0.5
Area = 0.5[(y1x2+y2x3+y3x1)-(x1y2+x2y3+x3y1)]
Example 4a Triangle
Example 4a Triangle
Source Codes Option Explicit Private Sub cmdReadMe_Click() frmtriangle.Hide frmReadMe.Show End Sub Private Sub CmdCalc_Click() 'Declaration of Variables Dim X1 As Single, X2 As Single, X3 As Single Dim Y1 As Single, Y2 As Single, Y3 As Single Dim S1 As Single, S2 As Single, S3 As Single Dim Perimeter As Single, Area As Single 'Assignment of Variables X1 = Val(txtX1.Text): X2 = Val(txtX2.Text): X3 = Val(txtX3.Text) Y1 = Val(txtY1.Text): Y2 = Val(txtY2.Text): Y3 = Val(txtY3.Text)
Example 4a Triangle
'Calculations S1 = Sqr((X1 - X2) ^ 2 + (Y1 - Y2) ^ 2) S2 = Sqr((X2 - X3) ^ 2 + (Y2 - Y3) ^ 2) S3 = Sqr((X3 - X1) ^ 2 + (Y3 - Y1) ^ 2) Perimeter = S1 + S2 + S3 Area = Abs(0.5 * (Y1 * X2 + Y2 * X3 + Y3 * X1 _ - Y2 * X1 - Y3 * X2 - Y1 * X3)) 'Displaying Results lblResult.Caption = "Length of side S1 = " & _ FormatNumber(S1, 3) & vbNewLine & _ "Length of side S2 = " & FormatNumber (S2, 3) & _ vbNewLine & "Length of side S3 = " & FormatNumber (S3, 3) _ & vbNewLine & "Perimeter = " & FormatNumber (Perimeter, 3) _ & vbNewLine & "Area = " & FormatNumber (Area, 3) End Sub
Keywords ______ begin the body of an event procedure and keywords ______ end the body of an event procedure. A location in a computers memory that may contain different values at various times throughout program execution is called a ______. What is the assignment operator in VB? What is the basic difference between a string and numeric data? The _____ character is the symbol for the string concatenation operator. What character in VB indicates the start of a comment? In VB, how do you continue long statements on another line?
3. 4. 5. 6. 7.
8.
9.
Option Explicit forces explicit variable declaration. The variables PeLaJaR and pelajar are identical. Declarations can appear anywhere in a body of an event procedure. Integer division has the same precedence as floatingpoint division. VB syntax always requires arithmetic expressions to be enclosed in parentheses otherwise, syntax errors occur. An integer datatype can store the value 50000.
f)
11.
Determine whether or not the name is the valid variable name: Sales.2004 Income 05 Food&Drink Number? Car_1 2143Test1 val _under
13.
c)
14.
(5)(5)
Indicate whether each expression evaluates to true or false. a) b) c) d) Not (10 >= 8) (A = a) Not (A = a) (CAT = CAT) And (1 < 2)
Complete the tables below by filling in the value of each variable after each line is executed.
X Private Sub cmdCompute_Click() X=2 Y = 3 * X^2 X=Y+3 Y
picResults.Cls
picResults.Print X + 5 Y=Y+X/2 End Sub Bal
Private Sub cmdCompute_Click() Bal = 30 Ker = 0.3 Dise = 7 Bal = Bal + Ker * Bal Bal = Bal - Dise End Sub
KerX
Dise
Programming Exercise
1. Create a user interface and set the properties of controls as shown below. Write a program that fulfill the following requirements. a) Ask the user to type in the name and title in the textboxes. Enable the Greet button when the title textbox is filled. b) When Greet button is clicked, display the title and name on the first line of the label, followed by other appropriate message on the following lines. Enable the Clear and End buttons. c) When Clear button is clicked, clear the contents of the textboxes and label, and disable the command buttons.
Name
frmForm txtName txtTitle cmdGreet cmdClear cmdEnd You can also use visible property instead of enabled lblGreeting
Property
Caption Font Size Font Size Caption Caption Enabled Caption Enabled Caption
Value
HANDS-ON 2 Arial 10,Bold Arial 10,Bold Greet Clear False End False
Programming Exercise
2. Write a VB program to calculate the area, perimeter and moment of inertia of a semi circle and circle about their centroidal x-axis as shown below. Use picturebox for input and labels to display the output.
Ix=pr4/8 - 8r4/9p
Ix=pr4/4
3. Develop a program to calculate the MOI of I, H, T and C sections. 4. Write a program to calculate the support reactions of a simply supported beam carrying: a)uniformly distributed loaded (udl) over the span. b)triangular distributed load over the span. c)A point and udl over the span. 5. Write a program to calculate the magnitude and direction of the resultant force of three concurrent forces acting on a particle.
the END