Data Types, Variables, Assignment Statements

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.

Programs & Program Statements

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.

Skeleton sample of an event procedure

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

Private Sub End Dim

property names
We will learn more keywords as we progress

VB Statements (cont‘d)
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

“07-5531000” “Name” “123” A zero-length string that contains no characters, “”
not even a space

456.125 4922.11.06 RM10. 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.00 “124” Invalid (765)432-1111 Reason Not Valid Contains parenthesis & dash -ve sign at end Two decimal points Starts with decimal point Contains RM and comma Contains quotation marks .125 700000 700000.VB Statements (cont‘d)  Numeric Literals • used when working with numbers • combination of the digits 0 to 9.3 .14159 0.

text returns “Fakulti Kejuruteraan ? “ •“Fakulti” & “Kejuruteraan” & kod returns “Fakulti Kejuruteraan ?“ The value of text property of txtKursus control The value of kod variable . longer. character string Use “&” operator Examples  •“Fakulti” & “Kejuruteraan” & “Awam” returns “FakultiKejuruteraanAwam” •“Fakulti” & “” & “Kejuruteraan Awam” returns “Fakulti Kejuruteraan Awam“ •“Fakulti” & “Kejuruteraan” & txtKursus.String Concatenation  Concatenate means to join two or more character strings into a single.

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.caption= “Hello” & txtname.text & _ vbnewline & “Welcome to My Class.Continuing Long Lines  Continue a long vb statements to two or more lines by using the space and underscore ( _ ) characters at the end of each line. lblmessage. When you combine line continuation and string concatenation in the same statement. “ & _ “ This is a Visual Basic Class for” _   & “ Engineering Students” space .

UTM ‘ DATE : 21 July 2006 .  clarify the purpose of a block of code within a larger program. FKA.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. comments begin with an apostrophe ( ‘ )  ‘ PROGRAM : ‘ PURPOSE : ‘ Calculator To Calculate the result of arithmetic operation of two number ‘ PRORGAMMER ITUCE.  when it was written.

We will take a look at the fundamental data types .VB Statements (cont‘d) 3. • The data type affects how much memory is allocated for the variable. • 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. Variables • A variable can be defined as a location in the computer’s memory that has the programmer-given name. • The programmer must decide on the name and also indicate what data type will be stored in that memory location.

767 Long Single String Large integer numbers (4 bytes) Small floating point numbers (4 bytes) Character data (10 bytes + string length) -2.483. four digits to the right of the decimals January 1.147.647 Floating point numbers up to 6 digits of accuracy Varies based on the size of string Variant Store any data type Dependent upon what is being stored.768 to 32.648 to 2.0100 to December 31.483.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.147. should NOT be used under normal circumstances Data types that we will use most in this course .999 Floating point numbers up to 14 digits of accuracy -32.

The first time a variable is used it should appear on the left side of an assignment statement to receive its initial value. Variables are typically grouped together at the beginning of an event procedure. N = N+1 This is OK . the programmer has to declare the variable by specifying a name and a data type.Variables  Before a variable may be used.    The expression on the RHS of an assignment statement is evaluated before an assignment is made.

Wt) • Use mixed case. (Ex. Dist2. space or type-declaration character. (Ex.Choosing Variable Names  VB Variable Naming Requirements • Must not exceed 255 characters. Width)  • Use consistent abbreviations for the same word. Span. Load. Time. with a capital letter at the start of each new word. (Ex. (Ex. Dist3) • Use entire words or initial syllables. • Must begin with a letter. Dist1. • Cannot be the same as a keyword. ICNo. • Not case sensitive. • Cannot contain an embedded period. MatrixNo) . UDL. Standard Guidelines for Naming Variables • Be meaningful and descriptive. • Must be unique. PtLoad.

select from the menu.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. Tools  Options  Check Require Variable Declaration You have to do this before opening the code window. all variables must be declared before they can be used. otherwise you have to type in Demo .  To automatically include the Option Explicit statement at the beginning of every program code.

text) CPA = CSng(txtCPA.text) CreditHour= CInt(txtCredit. we have to convert the information to numeric form using conversion functions.Data Conversion • Input and output information displayed on a form through textbox & label are stored as a string in the property of the controls. Example. • If the information is made up of numeric characters and we want to store it as a numeric variable. • This information can be directly copied to a string variable by using the assignment (=) operator. so that we can perform mathematical calculation.text) Please refer to the supplementary notes on Conversion Functions . Distance = Val(txtJarak.

text Age = txtAge.text Dim Width as Single. 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 Dim Name as String Name = txtName.text) Depth = Val(txtDepth.text) Dim Message as String Name = txtName.text Message = “Hello ” & Name & _ vbnewline & “You are ” & Age & _ “years old” Assigning results of string concatenation to variable Message . Depth as Single Width = Val(txtWidth.Using Variables in Assignment Statements  Variables are often used in assignment statements along with control properties and literals.

like variables.Constants • • • Constants. 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 .

" & vbNewLine & _ "Welcome To Visual BASIC!“ lblDisplay.BorderStyle = 1 Form1.BackColor = vbWhite lblDisplay.BackColor = vbYellow End Sub .Caption = " Hello.Constants (cont’d) Symbolic constant example Private Sub cmdClickMe_Click() lblDisplay.

• Syntax.14159 To define Bahasa = Melayu: Const BAHASA As String = “Melayu” .Constants (cont’d) b) User-Defined Constant • Constant defined by the user to be used in VB. To define pi: Const PI As Single = 3. Const NAME As Type = value Example.

Classification Scheme for Data items Data Item Numeric String Constant Integer Real Variable Constant Variable Constant Variable .

Operators Three types of Operators  Arithmetic Operators  Comparison Operators  Logical Operators a) Arithmetic Operators (in order of precedence) Operator ^ Operation exponential *. 2) +.- Addition and subtraction . the dividend & divisor are rounded to integer./ \ Mod Multiplication and division Integer division Modulus 1) \ and Mod Prior to division.VB Statements (cont‘d) 4. The result of \ is rounded (truncated) to the direction of zero.

those with lower precedence. right.2mod1.6 Value 5.6 9.75 4 9. the innermost set is evaluated first. If there is more than one set.2.84 1419857.0 • Expressions with parentheses are evaluated first.6 17^5 Rules of precedence 1 34.2^1.Arithmetic Operators Expression 9.2/1.6 9. • Operations with the higher precedence are evaluated prior to • Operations with equal precedence are performed from left to .

875 = 11.875 Variable2 = (8 – 5 * 3) ^2 = (8 –15) ^ 2 = (-7) ^ 2 = 49 Value1 = 13 – 12 / 3 + 4 * 2 = 13 – 4 + 4 * 2 = 13 – 4 + 8 = 17 .Arithmetic Operators (cont’d) Variable1 = 10 + 15 * 2 / 4 ^ 2 = 10 + 15 * 2 /16 = 10 + 30 /16 = 10 + 1.

6e3) M= (P*( L – a) * x / L) – (P * ( x – a)) k = M / (b * d ^2 * fcu) z = d * ( 0.25 – k/0.5) As = M / (0.5 + (0.Arithmetic to VB Expressions Normal Arithmetic Expression Equivalent VB Statement Area = b*h Ixx = b*h^3/12 Speed = (distance * 1e3)/(time*3.5 + ( 0.9)^0.87fyz .8 * fy * z) Area = bh Ixx = bh3/12 Speed (m/s) = distance(km) x 103 time(hr) x 60 x 60 M = P(L-a)x – P(x – a) L k = M/bd2fcu z = d(0.25 – k/0.9 )1/2 ) As = M/0.

B B=B*B End Sub .Print A .Arithmetic Operators in VB Statements Code Walkthrough A Private Sub cmdCompute_Click( ) B C 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.

Placed between two values and returns a Boolean value. Values must be compatible types.Operators (cont’d) b) Comparison Operators (Relational) Operator > < Comparison Greater than Less than >= <= = <> Greater than or equal to Less than or equal to equal to Not equal to • • • • • All have the same precedence. Compare values of literals. eg. number to number. they are evaluated in order of appearance from left to right. . String to string. variables and control properties. Use conversion functions when required.

general rule 0<9<A<Z<a<z. 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 { } ~ .Comparison Operators (cont’d) • • The ANSI (ASCII) code values determine whether one character is greater than another in a string comparison. Table below shows a few of the values.

Credit=12 Rs=0 StuName=Anas TextboxtxtCourse = (empty) Expression txtCourse.text=“” Credit<10 Rs>2 Boolean Value True False False Rs>= 0 StuName=Anis StuName<>“” 123>9 “123” > “9” True False True True False (Credit*3-25)> 0 True .Comparison Operators (cont’d) Example.

. • AND returns true when both relations expressions are true. • When combining relational expressions and comparison operators.c) Logical Operators Operator Not And Or Operators (cont’d) Operation Logical not (reversing its Boolean value) Logical and Logical or • Returns a Boolean value. In general arithmetic operators are evaluated first. and logical operators are evaluated last. • And and Or combine the relational expressions. • OR returns true as long as at least one of the relations expressions is true. each relational expression is evaluated first. then relational operators.

.Logical Operators (cont’d) Example Bil Nama Bil<=10 AND Nama <>”” Bil<=10 OR Nama <>”” 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 .

/)  Output Needs: display results of the operations Design  Hierarchy Chart Calculator Program 2. product and quotient of two numbers.Example Example 4 Write a program that calculates the sum.Program Development . 1. x. Analyze the Problem  Input needs: 2 numbers  Processing needs: arithmetic operations (+. -. difference. Form Event Number input textbox & Label input request Arithmetic operator Command buttons & label Click Event show result Exit command button Click Event – halt program execution 32 .

Example 4 (cont’d)  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 Terminate the program End You can also write pseudocodes 33 .

Example 4 (cont’d)  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 .

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 (cont’d) 3.

24points …. Bold.. 12 points Click a button Times New Roman. Caption Caption Caption Font Caption font MS San Serif. 12 points Label: Label2 36 . Bold. 24points Value of Property Form: form1 Textbox: txtFirstNo Textbox: txtSecondNo Commandbutton: cmdDivide Commandbutton: cmdSubtract Commandbutton: cmdMultiply Commandbutton: cmdAdd Label: lblResult Commandbutton: cmdEnd Label: Label1 Caption Font …. Bold Italic. 9 points &End Type two numbers Times New Roman. …. Tahoma.Example 4 (cont’d)  Setting Control Properties Control Property Name Caption Text Text Caption Font Form1 (blank) (blank) / MS San Serif. Bold Italic. Bold. ….

event procedures Option Explicit Dim No1 As Single.Text) Result = No1 / No2 lblResult. i.Caption = txtFirstNo.Text) Result = No1 + No2 lblResult.Text & " EQUALS TO " & Result End Sub 37 .Text) No2 = Val(txtSecondNo.Text) No2 = Val(txtSecondNo.Text & " EQUALS TO " & Result End Sub Private Sub cmdAdd_Click() No1 = Val(txtFirstNo. Coding The coding for the command buttons is then written. No2 As Single.Caption = txtFirstNo.Text & " PLUS " & _ txtSecondNo.e.Example 4 (cont’d) 4.Text & " DIVIDED BY " & _ txtSecondNo. Result As Single Private Sub cmdDivide_Click() No1 = Val(txtFirstNo.

Text) No2 = Val(txtSecondNo.Text & " MINUS " & _ txtSecondNo.Caption = txtFirstNo.Example 4 (cont’d) Coding (cont’d) Private Sub cmdMultiply_Click() No1 = Val(txtFirstNo.No2 lblResult.Text & " EQUALS TO " & Result End Sub Private Sub cmdSubtract_Click() No1 = Val(txtFirstNo.Text) Result = No1 .Text & " EQUALS TO " & Result End Sub Private Sub cmdEnd_Click() End End Sub 38 .Text) No2 = Val(txtSecondNo.Text & " TIMES " & _ txtSecondNo.Caption = txtFirstNo.Text) Result = No1 * No2 lblResult.

When the program is run Enter numbers 8 and 4 in the textbox.Example 4 (cont’d) 5. in lblResult label You can choose any other click buttons (Demo) 39 . then click Result is shown here. Test & Debug After testing and debugging the the program is now competed.

The program should:  Provide facility for the user to enter input data. .  Provide a read-me message on different form. perimeter and area. perimeter and area triangle where the coordinates of the sides are known.  Display the side lengths.Example 4a – Triangle Problem: Write a program to calculate the length of the sides.

5  Area = 0.5[(y1x2+y2x3+y3x1)-(x1y2+x2y3+x3y1)] You are advised to carry out the programming development process .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.

02 19.Example 4a – Triangle 10.11 0.89 0.96 9.12 10.15 .

Show End Sub Private Sub CmdCalc_Click() 'Declaration of Variables Dim X1 As Single.Text): X3 = Val(txtX3.Hide frmReadMe. X3 As Single Dim Y1 As Single. S2 As Single.Text) . Y3 As Single Dim S1 As Single.Text) Y1 = Val(txtY1. Area As Single 'Assignment of Variables X1 = Val(txtX1. Y2 As Single. S3 As Single Dim Perimeter As Single. X2 As Single.Text): X2 = Val(txtX2.Text): Y2 = Val(txtY2.Text): Y3 = Val(txtY3.Example 4a – Triangle Source Codes Option Explicit Private Sub cmdReadMe_Click() frmtriangle.

5 * (Y1 * X2 + Y2 * X3 + Y3 * X1 _ .Example 4a – Triangle 'Calculations S1 = Sqr((X1 .Caption = "Length of side S1 = " & _ FormatNumber(S1.Y3) ^ 2) S3 = Sqr((X3 . 3) _ & vbNewLine & "Perimeter = " & FormatNumber (Perimeter. 3) & vbNewLine & _ "Length of side S2 = " & FormatNumber (S2.X1) ^ 2 + (Y3 .Y2 * X1 .X2) ^ 2 + (Y1 .Y3 * X2 .Y1 * X3)) 'Displaying Results lblResult. 3) End Sub .Y2) ^ 2) S2 = Sqr((X2 .Y1) ^ 2) Perimeter = S1 + S2 + S3 Area = Abs(0. 3) _ & vbNewLine & "Area = " & FormatNumber (Area. 3) & _ vbNewLine & "Length of side S3 = " & FormatNumber (S3.X3) ^ 2 + (Y2 .

. 9. 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. 6. What are three rules for naming variables? What naming standard is suggested for controls that you place on a form. 5. Keywords ______ begin the body of an event procedure and keywords ______ end the body of an event procedure. how do you continue long statements on another line? 3.Test Your Understanding 1. A location in a computer’s memory that may contain different values at various times throughout program execution is called a ______. 2. 8. What character in VB indicates the start of a comment? In VB. 4. 7.

VB syntax always requires arithmetic expressions to be enclosed in parentheses – otherwise. syntax errors occur. Declarations can appear anywhere in a body of an event procedure.Test Your Understanding 10. f) 11. Determine whether or not the name is the valid variable name: Sales. An integer datatype can store the value 50000. State whether each of the following true or false: a) b) c) d) e) Option Explicit forces explicit variable declaration. The variables PeLaJaR and pelajar are identical. Integer division has the same precedence as floatingpoint division.2004 Income 05 Food&Drink Number? Car_1 2143Test1 val _under .

Test Your Understanding 12. Are the following expressions valid? a) b) c) 14. a) b) c) d) Not (10 >= 8) (“A” = “a”) Not (“A” = “a”) (“CAT” = “CAT”) And (1 < 2) . What is the value of the following expressions: a) b) c) (1+8/2+((1*4)+(5*4))/4) ((2+2+2)/3 + (1+1+1)*5)) ((3*5*2*7)+12/2) (3+3)*1 4(3*5) 13. (5)(5) Indicate whether each expression evaluates to true or false.

X Private Sub cmdCompute_Click() X=2 Y = 3 * X^2 X=Y+3 Y picResults.Cls picResults.Test Your Understanding 15. Complete the tables below by filling in the value of each variable after each line is executed.3 Dise = 7 Bal = Bal + Ker * Bal Bal = Bal .Dise End Sub KerX Dise .Print X + 5 Y=Y+X/2 End Sub Bal Private Sub cmdCompute_Click() Bal = 30 Ker = 0.

followed by other appropriate message on the following lines. 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 Greet Clear False End False . display the title and name on the first line of the label. clear the contents of the textboxes and label.Bold Arial 10. a) Ask the user to type in the name and title in the textboxes. Enable the Greet button when the title textbox is filled. Write a program that fulfill the following requirements. Create a user interface and set the properties of controls as shown below. Enable the Clear and End buttons. b) When Greet button is clicked. c) When Clear button is clicked. and disable the command buttons.Programming Exercise 1.

b)triangular distributed load over the span. Write a program to calculate the magnitude and direction of the resultant force of three concurrent forces acting on a particle. Develop a program to calculate the MOI of I. 4. Write a VB program to calculate the area.Programming Exercise 2.8r4/9p Ix=pr4/4 3. perimeter and moment of inertia of a semi circle and circle about their centroidal x-axis as shown below. . T and C sections. c)A point and udl over the span. Ix=pr4/8 . Use picturebox for input and labels to display the output. Write a program to calculate the support reactions of a simply supported beam carrying: a)uniformly distributed loaded (udl) over the span. 5. H.

the END .