Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamentals of Programming in Visual Basic

Similar presentations


Presentation on theme: "Fundamentals of Programming in Visual Basic"— Presentation transcript:

1 Fundamentals of Programming in Visual Basic
Chapter 3 Fundamentals of Programming in Visual Basic Chapter 3 - Visual Basic Schneider

2 Outline and Objectives
Visual Basic Objects Visual Basic Events Numbers Strings Input/Output Built-In Functions Chapter 3 - Visual Basic Schneider

3 The Initial Visual Basic Screen
Menu bar Project Explorer window Toolbar Toolbox Properties window Description pane Form Project Container window Form Layout window Chapter 3 - Visual Basic Schneider

4 Steps to Create a Visual Basic Program
1. Create the interface by placing controls on the form 2. Set properties for the controls and the form 3. Write code for event procedures associated with the controls and the form Chapter 3 - Visual Basic Schneider

5 Four Useful Visual Basic Controls
Text Boxes Labels Command Buttons Picture Boxes The icons in the Tool Box represent objects that can be placed on the form. The four objects discussed today are: text boxes….. Text Box: you use a text box primarily to get information, referred to as input , from the user Label is placed next to text box to tell the user what type of information to enter into the to he text box Command button : The user clicks a command button to initiate an action Picture Boxes: You use a picture box to display text or graphics Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider

6 Placing a Text Box on a Form
Double-click on the text box icon in the toolbox to add a text box to your form Activate the properties window (Press F4) Set values of properties for text box Go over resizing and dragging the text box The first line of the properties window (called the object box) reads “Text1 TextBox” . Text1 is the current name of the textbox. The two Tab permit you to view the list of properties either alphabetically or grouped by categories.. We discuss four properties : The Text property determines the words in the text box. Press Shift+Ctrl+F to move to the first property beginning with F . Move to the property ForeColor. The foregroung color is the color of the text.. Click on Palette tab to display a selection of colors. Highlight the Font property and change it to Italic Chapter 3 - Visual Basic Schneider

7 Placing a label on a Form
Chapter 3 - Visual Basic Schneider

8 Some Useful Properties of Objects
1. Command Buttons 2. Text Boxes 3. Labels 4. Picture Boxes Name - all Caption - 1,3 Text (for Text Boxes) - 2 BorderStyle - 2,3,4 Visible - all BackColor – all For command buttons, change style to graphical Alignment- 2,3,4 Font - all Border Style: Setting the BorderStyle to 0-None removes the border from an object Visible: Setting the property to false hides an object when the program run. The object can be set to reappear with code BackColor: Specifies the background color for text box, label, picture box or form.. Also specific background color for a command button having Style set to “1-Graphical” BackStyle: The background of a label is opaque by default. Setting the background style of a label to transparent causes whatever is behind the label remain visible.; the background color of the label essentially becomes “see through” Font: Two unusual fonts are Symbols and Wingdings> For instance with the windingsfonts , changing the text to % & ‘ and J yields a bell, a book, a candle and a smiling face Chapter 3 - Visual Basic Schneider

9 Chapter 3 - Visual Basic Schneider
Naming Objects: Use the Property window to change the Name property of an object Good programming practice dictates that each object name begins with a three letter prefix that identifies the type of object. Chapter 3 - Visual Basic Schneider

10 Chapter 3 - Visual Basic Schneider
Naming Objects: Chapter 3 - Visual Basic Schneider

11 Naming Objects An Object Name Must Start with a letter
Can include numbers and underscore (_) Cannot include punctuation or spaces Can be a maximum of 40 characters Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider

12 Chapter 3 - Visual Basic Schneider
Visual Basic Events Code is a set of statements that instruct the computer to carry out a task. Code can be associated with events When an event occurs, the code associated with that event (called an Event Procedure) is executed. When a VB program is run, a form and its controls appear on the screen. Normally, nothing happens until the user takes an action, such as clicking a control or pressing the Tab key. Such an action is called event. Chapter 3 - Visual Basic Schneider

13 Creating An Event Procedure
Double-click on an object to open a Code window. (The empty default event procedure will appear. Click on the Procedure box if you want to display a different event procedure.) Write the code for that event procedure. Object Property Setting frmWalkthrough Caption Demonstration txtPhrase Text (blank) cmdBold Caption Make Phrase Bold Object Box Procedure Box: Contains a list of all possible event procedures associated with the text box Choose txtPhrase_LostFocus() txtPhrase.Font.Size = 12 End Sub Choose GotFocus and type: txtPhrase.Font.Size = 8 txtPhrase.Font.Bold = False Go to command Button and choose cmdBold_Click and type txtPhrase.Font.Bold = True Chapter 3 - Visual Basic Schneider

14 Example of An Event Procedure
Private Sub objectName_event ( ) statements End Sub Private Sub Text2_GotFocus( ) Text2.Font.Size = 12 Text2.Font.Bold = False Text2.forecolor=vbRed The word Sub signals the beginning of the event procedure, and also identifies the Object and the event occurring to that object The word private indicates that the event procedure cannot be invoked by an event from another procedure. The word Sub means subprogram Example: the event procedure private Sub cmdButton_Click () txtBox.Text = “” End Sub The event clicking cmdButton is different from the event clicking picBox_Click Chapter 3 - Visual Basic Schneider

15 Chapter 3 - Visual Basic Schneider
More Examples Private Sub cmdButton_Click( ) txtBox.ForeColor = vbRed txtBox.Font.Size = 24 txtBox.Text = “Hello” End Sub Each color can be identified by a sequence of digits and letter beginning with &H. &HFF& = Red &HFF00& = Green &HFF000& = Blue Chapter 3 - Visual Basic Schneider

16 Exercises: What is wrong??!
11. Private Sub cmdButton_Click( ) frmHi = “Hello” End Sub 12. Private Sub cmdButton_Click( ) txtOne.ForeColor= “red” Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider

17 13. Private Sub cmdButton_Click( ) txtBox.Caption = “Hello” End Sub
Exercises 13. Private Sub cmdButton_Click( ) txtBox.Caption = “Hello” End Sub 16. Private Sub cmdButton_Click( ) txtOne.MultiLine= True Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider

18 Most Properties can be set or altered at run time with code.
Tips Most Properties can be set or altered at run time with code. cmdButton.visible = False The MultiLine property of a text box can only be set from the properties window, also the Name property…. “” surrounds Caption, Name, Font.Name or strings. Not True for vars or numeric constants Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider

19 At design time colors are selected from a palette
Color Constants At design time colors are selected from a palette At run time the eight most common colors can be assigned with the color constants: vbBlack vbMagenta vbRed vbCyan vbGreen vbYellow vbBlue vbWhite Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider

20 Components of Visual Basic Statements
Constants Variables Keywords (reserved words) Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 20

21 Can NOT change during the execution of a program. Types of Constants:
numeric constants string constants Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 21

22 Valid Numeric Constants:
Integer Real number Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 22

23 Invalid Numeric Constants:
14, % $190.04 & Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 23

24 Arithmetic Operations
Operator Operation Basic expression ^ Exponentiation A ^ B * Multiplication A * B / Division A / B Addition A + B Subtraction A - B Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 24

25 Examples of Arithmetic Operations
Evaluate the following expressions: x = 3 * / 3 x = 4 ^ (8 / 4) y = / (3 * (10 - 9)) z = ^ 2 m = 6 / 3 + 3 Chapter 3 - Visual Basic Schneider

26 Scientific Notation 10n=1000...0 103=1000 10-n=0.000...01 10-3=0.0001
b.10±r VB Notation bE±r 1.4 * 10-45 14 * 10 ^-45 1.4E -45 1.4E -44 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider

27 A sequence of characters treated as a single item
String Constants: A sequence of characters treated as a single item The characters in a string must be surrounded by double quotes (“ ”) Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 27

28 Valid String Constants
“A rose by any other name” “9W” “134.23” “She said, ‘stop , thief!’ ” Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 28

29 Invalid String Constants
‘Down by the Seashore’ “134.24 “She said, “Stop, thief!”” Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 29

30 Chapter 3 - Visual Basic Schneider
5 x Variables 2.6 y z 7.6 A storage location in main memory whose value can be changed during program execution. These storage locations can be referred to by their names. Every variable has three properties: a Name, a Value, and a Data Type. Types of variables: Numeric and String Chapter 3 - Visual Basic Schneider

31 Rules for Naming Variables
Must begin with a letter Must contain only letters, numeric digits, and underscores ( _ ) Can have up to 255 characters Cannot be a Visual Basic language keyword (for example, Sub, End, False) VB does not distinguish between uppercase and lowercase letters Example: numberOfCars, tax_Rate_1994 Let statement assigns values to variables and Print method displays the values of variable Chapter 3 - Visual Basic Schneider

32 Valid Variable Names: timeElapsed a1b2c3 Var_1 n celsius
Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 32

33 Invalid Variable Names:
maximum/average 1stChoice square yard Name? Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 33

34 Words that have predefined meaning to Visual Basic .
Keywords Words that have predefined meaning to Visual Basic . Can Not be used as variable names. Examples: End - Print Sub - Let If -Select While -Call The VB editor automatically capitalizes the first letter of reserved word Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 34

35 Chapter 3 - Visual Basic Schneider
Numeric Variables Used to store numbers Value is assigned by a statement of the form: numVar = expression The variable must be on the left and the expression on the right. Chapter 3 - Visual Basic Schneider

36 Assignment Statement:
The statement var = expr assigns the value of the expression to the variable tax = 0.02 * (income * dependents) sum = 2 + x y Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 36

37 Valid Assignment Statements
count = count + 1 num = 5 count = count + num /2 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 37

38 Invalid Assignment Statements
10 = count count + 1 = count Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 38

39 A string variable stores a string.
The rules for naming string variables are identical to those for naming numeric variables. When a string variable is first declared, its value is the empty string. The value of string variable is assigned or altered with Let statements and displayed with Print methods just like the Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 39

40 Visual Basic Print Statement
Print is a method used to display data on the screen or printer. Can be used to display values of variables or expressions Chapter 3 - Visual Basic Schneider

41 Examples of Print Statements
Private Sub cmdCompute_Click() picResults.Print 3 + 2 picResults.Print 3 - 2 picResults.Print “3 * 2” picResults.Print 3 / 2 picResults.Print 3 ^ 2 picResults.Print 2 * (3 + 4) End Sub Chapter 3 - Visual Basic Schneider

42 Examples of Print Statements
speed=3 taxRate=speed+5 total=30 picOutput.Print speed picOutput.Print taxRate picOutput.Print “Class average is”; total/3 3 8 Class average is 10 Chapter 3 - Visual Basic Schneider

43 Examples of Print Statements
y = 5 picOutput.Print (x + y) / 2, x / y Output: 10 3 Chapter 3 - Visual Basic Schneider

44 String Variable Example
Private Sub cmdShow_Click() picOutput.Cls phrase = "win or lose that counts." picOutput.Print "It's not whether you "; phrase picOutput.Print "It's whether I "; phrase End Sub Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 44

45 Two strings can be combined by using the concatenation operation.
The concatenation operator is the ampersand (&) sign. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 45

46 Concatenation, Example
Private Sub Command1_Click() Print "cs116" & "cs112" Print "cs" & 116 Print 116 & "cs" Print 116 & 117 Print "cs116" ; "cs112" Print "cs" ; 116 Print 116 ; "cs" Print 116 ; 117 End Sub Chapter 3 - Visual Basic Schneider

47 Chapter 3 - Visual Basic Schneider
Example &: is always used to make concatenation +: makes concatenation when it is used with strings, and as summation with numbers What about “hi”+5 ??? Chapter 3 - Visual Basic Schneider

48 Examples of Concatenation:
Private Sub Command1_Click() strVar1 = "Hello" strVar2 = "World" picOutput.Print strVar1 & strVar2 txtBox.Text = "32" & Chr(176) & " Fahrenheit" End Sub Chr(176) prints º Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 48

49 Chapter 3 - Visual Basic Schneider
Chr() & Asc() The characters have numbers associated with them, these values called ANSI values of characters Chr(65) = A Chr(66) = B Chr(97) = a Chr(176) = Asc(A) = 65 Asc(B) = 66 Asc(a) = 97 Asc( ) = 176 Chapter 3 - Visual Basic Schneider

50 Chapter 3 - Visual Basic Schneider

51 Chapter 3 - Visual Basic Schneider
Val, Str Val (“23”) = 23 Str (23) =“ 23” Val (“50” + “60”) = Val (“5060”) = 5060 Val (“50”) + Val(“60”) = 50+60=110 Val(“Hi”) = 0 Val(“89Hello”) = 89 Val(“89Hi10”) = 89 Str("10") + Str("50") = 10 50 Str(“Hello”)  error Chapter 3 - Visual Basic Schneider

52 Declaring Variable Types
Use the Dim statement to declare the type of a variable. Examples: Dim number As Integer Dim flower As String Dim interestRate As Single From now on we will declare all variables. Declaring variables is regarded as good programming practice. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 52

53 Single: a numeric variable that stores real numbers (0 By default)
Data Types : Single: a numeric variable that stores real numbers (0 By default) Integer: a numeric variable that stores integer numbers (from to 32767) (0 By default) String: a variable that stores a sequence of characters (“”empty string By default) Boolean: a variable that stores True or False (False By default) The default data type is a single precision numeric variable Therefore Number and Number! Are the same Double precision variable is used to store number with many digits A single precision variable is accurate to about seven decimal points where double precision is accurate to about 15 decimal points Is used when a high degree of accuracy is needed. If you try to assign a real number , the number would be cut off and an integer would be assigned to it. Declaring variables is regarded as good programming practice Example: Dim variableName As String Dim variableName As Single Type Declaration Tags Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 53

54 Using Text Boxes for Input/Output
The contents of a text box are always a string type. Numbers can be stored in text boxes as strings. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 54

55 Using Text Boxes for Input/Output
The contents of a text box should be converted to a number before being assigned to a numeric variable. Val(txtBox.Text) gives the value of a numeric string as a number Example: Dim numVar as Single numVar = Val(txtBox.Text) Function Input Output Str number string Val string number If str is a string representation of a number, then Val(str) is that number. Conversely, if num is a number, then Str(num) is a string representation of the number. Therefore statements such as numVar = Val(txtBox.Text) and txtBox.Text = Str(numVar) Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 55

56 Chapter 3 - Visual Basic Schneider
Example1 A program for adding two numbers Private Sub Command1_Click() Dim num1 As Integer Dim num2 As Integer Dim result As Integer num1 = 4 num2 = 7 result = num1 + num2 Print result End Sub Chapter 3 - Visual Basic Schneider

57 Chapter 3 - Visual Basic Schneider
Example2 A program for adding two numbers Private Sub Command1_Click() Cls Dim num1 As Integer Dim num2 As Integer Dim result As Integer num1 = Val(txtNum1.Text) num2 = Val(txtNum2.Text) result = num1 + num2 Print result End Sub Chapter 3 - Visual Basic Schneider

58 Chapter 3 - Visual Basic Schneider
Example3 A program for adding two numbers Private Sub Command1_Click() Cls Print Val(txtNum1.Text) + Val(txtNum2.Text) End Sub Chapter 3 - Visual Basic Schneider

59 Chapter 3 - Visual Basic Schneider
Example3 A program for adding two numbers Private Sub Command1_Click() Cls Print txtNum1.Text + txtNum2.Text End Sub Works like string Concatenation Chapter 3 - Visual Basic Schneider

60 Chapter 3 - Visual Basic Schneider
The contents of a text box is always a string Numbers types into the text box are stored as strings. Therefore, they should be converted to numbers before being assigned to numeric. Chapter 3 - Visual Basic Schneider

61 Example (convert miles to furlongs and vice versa)
xString=“528” xValue=Val(xString)  xValue=528 Example 2 yValue=428 yString=Str(yValue)  yString=“428” Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 61

62 Example (convert miles to furlongs and vice versa)
Private Sub txtFurlong_LostFocus() txtMile.Text = Str(Val(txtFurlong.Text / 8)) End Sub Private Sub txtMile_LostFocus() txtFurlong.Text = Str(8 * Val(txtMile.Text)) Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 62

63 Program Documentation
An apostrophe (') is used to indicate that the remainder of the line is a comment. (Comments are ignored by Visual Basic.) Remarks can appear on a separate line or following a Visual Basic statement. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 63

64 The KeyPress Event Procedure
Private Sub txtCharacter_KeyPress(KeyAscii As Integer) txtCharacter.Text = "" picOutput.Cls picOutput.Print Chr(KeyAscii); " has ANSI value"; KeyAscii End Sub Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 64

65 Reading Data from Files
1. Choose a number to be the reference number for the file 2. Execute an Open statement 3. Read the data sequentially using Input # statements 4. Close the file 1. The name of the file: follows the same rules for naming program files. Use invest.bas and invest.dat 2. The mode in which the file is to be used , can be output, input, append . Output: indicates data is written to the file from the program input: the contents of the file are being read into the program append :allows new records to be added to an existing file. A butter is a reserved part of the primary storage unit used a s temporary storage area for the data that is being written or read from a file Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 65

66 Example of Reading from a File:
Open the file Open “DATA.TXT” For Input As #1 Input #1, num1 Input #1, num2 picOutput.Print num1+num2 Close #1 Reference number Read the data and assign it to num1 Data.txt A file can have either one item per line or many items (separated by commas) can be listed on the same line the items of data will be assigned to variables one at the time in the order they appear in the file. 1. Choose a number from 1 to 255 to be the reference number for the file 2. Open the file for input 3. Read items of data in order, one at the time, from the file with Input sattement Show Examples: Path is C;\F98 CSE181\Examples\Ch3\Data.txt The response typed into an input box is treated as a single string value, no matter what is typed. Quotation marks are not needed, and if included, are considered as part of the string. Numeric data typed into n input box should be converted to a number with Val before it is assigned to a numeric variable or used in calculation. 3 4 Close the file Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 66

67 Example of Reading from a File:
Data.txt 3 4 Open “DATA.TXT” For Input As #1 Input #1, num1, num2 picOutput.Print num1+num2  7 Close #1 math.txt 2 4 5 8 5 6 Example #1: create a file named Student.dat Prepare the file to receive data If a file already exists, it is destroyed and a new file is created. Associated with the file Student.date with buffer #1. As long as the file is open. Buffer #1 is used temporarily before the data is written to the file on disk Other statement in the program use this number to identify the file.. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 67

68 Reading Data from Files
Files can be also used for output rather than input. More about files will be discussed in chapter 8 and 9. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 68

69 Presents a window (dialog box) requesting input Syntax:
Input Dialog Box An input dialog box can be used to obtain a single item of input from the user Presents a window (dialog box) requesting input Syntax: stringVar = InputBox(prompt, title) Note:The type of inputBox is string type After users types in a response into the rectangle at the bottom of the screen and press Enter, the response is assigned to the string variable. Normally, text box is used to obtain input, sometimes we want just one piece of input and would rather not have a text box and label stay on the screen for ever. Example Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 69

70 Chapter 3 - Visual Basic Schneider
Private Sub cmdAdd_Click() Dim z As String z = InputBox("enter the number", "Hello") picBox.Print z End Sub After user types in a response into the rectangle at the bottom of the screen and press Enter, the response is assigned to the string variable. Chapter 3 - Visual Basic Schneider

71 Chapter 3 - Visual Basic Schneider
Example Private Sub cmdDisplay_Click() Dim num1 As Integer num1 = InputBox("Enter a Number to get its square", "My Number") Print num1 * num1 End Sub Chapter 3 - Visual Basic Schneider

72 Using Message Dialog Box for Output
The message dialog box is used to present a pop-up window containing information for the user Syntax: MsgBox prompt, , title Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 72

73 Example of a Message Dialog Box
MsgBox "CS116", , "Visual Basic" Stays on the screen until the user presses OK Chapter 3 - Visual Basic Schneider hhhhhhh 73

74 Example of a Message Dialog Box
MsgBox "CS116" Chapter 3 - Visual Basic Schneider

75 Chapter 3 - Visual Basic Schneider
Example Chapter 3 - Visual Basic Schneider

76 Formatting the Output:
Create easily readable output In the Print method, the spacing of the output is controlled by the following devices: semicolon comma Tab function Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 76

77 The next value output is placed in the next column position. Example:
Semicolons The next value output is placed in the next column position. Example: picOutput.Print “Patrick”; ”Jon” Output: PatrickJon Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 77

78 picOutput.Print “Patrick”; “ Jon” Output Screen: Patrick Jon
Example of Semicolon picOutput.Print “Patrick”; “ Jon” Output Screen: Patrick Jon Space here Space here Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 78

79 Example of Semicolon picOutput.Print 100; -200; 300 Output Screen:
Two spaces One space Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 79

80 Each print zone is 14 positions wide.
Commas A comma in a Print method causes the next value output to be placed in the next available print zone. Each print zone is 14 positions wide. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 80

81 picOutput.Print “SEE”, ”YOU”, ”SOON” Output Screen: SEE YOU SOON
Using Commas Example: picOutput.Print “SEE”, ”YOU”, ”SOON” Output Screen: SEE YOU SOON See in column 1 Y in column 15 and S in column 29 Column 29 Column 15 Column 1 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 81

82 Using Commas Example: Output Screen:
picOutput.Print “abc123def456ghi”, ”whatever” Output Screen: abc123def456ghi whatever See in column 1 Y in column 15 and S in column 29 Column 29 Column 15 Column 1 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 82

83 A print zone can be skipped by typing consecutive commas Example:
Using Commas A print zone can be skipped by typing consecutive commas Example: picOutput.Print “HOURLY”, , “PAY” Output Screen: HOURLY PAY Example 3.5.5 Column 29 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 83

84 Chapter 3 - Visual Basic Schneider
Cls: clears the form of all text PicBox.Cls: clears the PicBox of all text Chapter 3 - Visual Basic Schneider

85 Chapter 3 - Visual Basic Schneider
Examples The contents of a text box is always a string Numbers types into the text box are stored as strings. Therefore, they should be converted to numbers before being assigned to numeric. Chapter 3 - Visual Basic Schneider

86 Chapter 3 - Visual Basic Schneider
Private Sub cmdAdd_Click() picoutput.Print " " picoutput.Print 10; 20; picoutput.Print -10, 30, picoutput.Print picoutput.Print 15; ; 6 picoutput.Print "Hello"; "hi"; picoutput.Print "12345", "12" End Sub ;  in the next position column position ,  in the next available print zone picOutput.Print  moves the cursor to the beginning of the next line Chapter 3 - Visual Basic Schneider

87 Chapter 3 - Visual Basic Schneider
Private Sub Command1_Click() picoutput.Print 10; 20; picoutput.Print -10; 30; picoutput.Print picoutput.Print 15; ; 6 picoutput.Print "12345", "12" End Sub The number of empty lines = 3 Chapter 3 - Visual Basic Schneider

88 Specifies the column where output will start
Tab Function Specifies the column where output will start Use only semicolons with the Tab function Can only be used to advance the print position (cannot move backwards) Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 88

89 Example of Tab Function
picOutput.Print Tab(3); “Hi there!” ; Tab(25) ;“Bye!” Output Screen: Hi there! Bye! Example 3.5.6 Organizes data into columns of a table Column 25 Column 3 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 89

90 Example of Tab Function
picOutput.Print Tab(3); “Hi there!” ; Tab(5) ;“Bye!” Because column 5 is already occupied by the previous string, the output will be at the next line Output Screen: Hi there! Bye! Example 3.5.6 Organizes data into columns of a table Column 3 Column 5 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 90

91 Take one or more input values and return an output value
Built-In Functions Take one or more input values and return an output value A means provided by Visual Basic for carrying out small, common tasks Types of Built-In functions Numeric functions (manipulate numbers) String functions (manipulate strings) Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 91

92 Numeric Functions Chapter 3 - Visual Basic Schneider
Example for Int function and Sqr function Example : rounds a positive number to the nearest integer.. To round a number t two decimal places r = Int (100*n + 0.5) / 100 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 92

93 Example of Numeric Functions
Private Sub cmdEvaluate_Click() Dim n As Single, root As Single n = 6.76 root = Sqr(n) picResults.Print root; Int(n); Round(n,1) End Sub Output: Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 93

94 Chapter 3 - Visual Basic Schneider

95 Something about Round with number 5
123.8 12.4 4 4 5 23.6 Note that to round a number that is followed by number 5 and nothing after number 5, if it is odd make the round, if it is even number don’t round Chapter 3 - Visual Basic Schneider

96 Commonly-Used String Functions
Function: Left(“Penguin”, 4) Purpose: Returns the number of characters specified, starting at the beginning of the string Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 96

97 Commonly-Used String Functions
Function: Right(“Gotham City”, 4) Purpose: Returns the number of characters specified from the end of the string Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 97

98 Commonly-Used String Functions
Function: Mid(“Commissioner”, 4, 3) Purpose: Returns the substring starting at the position indicated by the first number and continuing for the length specified by the second number Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 98

99 Commonly-Used String Functions
Function: UCase(“Yes”) Purpose: Converts any lowercase letters in a string to uppercase Go over Example 6 page 121 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 99

100 String-Related Numeric Functions
Function: InStr(“John Smith”, “m”) Purpose: Searches for the first occurrence of one string in another and gives the position at which the string is found If not found  returns 0 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 100

101 String-Related Numeric Function
Function: Len(“John Smith”) Purpose: Returns the number of characters in the string. Is 10 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 101

102 Chapter 3 - Visual Basic Schneider

103 Chapter 3 - Visual Basic Schneider

104 Chapter 3 - Visual Basic Schneider

105 Format Functions The format functions provide detailed control of how numbers, dates, and strings are displayed. Examples FormatNumber ( , 1) 12,345.7 FormatCurrency ( , 2) $12,345.68 FormatPercent (.185, 2) % FormatNumber (1 + Sqr(2), 3) Numbers can be made to line up uniformly and be displayed with dollar signs, commas and a specified number of decimal places. Dates can be converted to a long or medium form. Strings can be right justified. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 105

106 Format Function Format (expr, “@……..@”)
Purpose: The value of this function is the value of expr right justified in a field of n spaces, where n is the number symbols. If num is number , numeric expression , or a string representation of a number, and fmt is a s string of symbols, then Format (num,fmt) is asserting of character with the number right justified in a field of n spaces. If num is any string,produced by a Format function , then the value of Format (num,fmt) contains the string right-justified in a field of n spaces. Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 106

107 Format Examples Format(12345, “@@@@@”) 12345 Format(123, “@@@@@”) 123
Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 107

108 Examples Chapter 3 - Visual Basic Schneider
hhhhhhh 108

109 Examples Chapter 3 - Visual Basic Schneider
hhhhhhh 109

110 Examples Chapter 3 - Visual Basic Schneider
hhhhhhh 110

111 FormatDateTime Example
FormatDateTime (“ ”, vbLongDate) Output: Monday, September 15, 2004 String Value: Sunday, September20, 1998 09-Sep-98 Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 111

112 Rnd Function Returns a random number from 0 to 1. (excluding 1).
Example: picBox.Print Rnd Output: Displays a random number from 0 to 1 (0 included and 1 excluded). picBox.Print Rnd +5 Output: Displays a random number from 5 to 6 (5 included and 6 excluded). Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 112

113 Rnd Function Example: picBox.Print Int(Rnd) Output: Displays 0.
Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 113

114 Rnd Function Random number between x and y Int((y-x+1)*Rnd) + x
Example: picBox.Print Int(5*Rnd) Output: Displays a random Integer from 0 to 4 (0 and 4 included). OR Output: Displays a random Integer from 0 to 5 (0 included and 5 excluded) picBox.Print Int(5*Rnd) +2 Output: Displays a random Integer from 2 to 6 (2 and 6 included). Random number between x and y Int((y-x+1)*Rnd) + x Chapter 3 - Visual Basic Schneider Chapter 3 - Visual Basic Schneider hhhhhhh 114

115 Chapter 3 - Visual Basic Schneider
Exercise: Revision What will be dsiplayed in the picOutput when the user double click (click 2 times) on the command button cmdExample Chapter 3 - Visual Basic Schneider

116 Chapter 3 - Visual Basic Schneider
Exercises Position the location of the form at run time  Form layout windows To open a file called “data.txt” located in C:\VB folder you must write  Open “C:\VB\data.txt” for input as #1 Which of the following statement assign the content of the input box to a numeric variable X X = Val(InputBox(“Enter the number”)) Chapter 3 - Visual Basic Schneider

117 Chapter 3 - Visual Basic Schneider
4) What is the output of the following code? Dim s as integer, n as integer Open “data.txt” for Input as #1 Input #1,n s=s+n close #1 print “s=”;s output: s = 60 data.txt 10 20 30 Chapter 3 - Visual Basic Schneider

118 Chapter 3 - Visual Basic Schneider
5) what is output of the following code Dim n as integer Open “data.txt” for Input as #1 Input #1,n Close #1 Print “n = ”; n Output: n = 20 data.txt 10 20 30 Chapter 3 - Visual Basic Schneider

119 Chapter 3 - Visual Basic Schneider
6) what is output of the following code Dim n as integer Open “data.txt” for Input as #1 Input #1,n Close #1 Print “n = ”; n Output: n = 10 data.txt 10 20 30 Chapter 3 - Visual Basic Schneider

120 Syntax Errors (Compile Errors)
Grammatical errors, such as misspelling, are called syntax error. Syntax error is encountered during compilation (by Complier) picBox.Primt 3 9W = 5 picBox.Print 2- If x > 10 x = x+1 End If Chapter 3 - Visual Basic Schneider

121 Chapter 3 - Visual Basic Schneider
Run-time errors Errors that occur while a program is running are called run-time errors Division by zero File not found Chapter 3 - Visual Basic Schneider

122 Chapter 3 - Visual Basic Schneider

123 Chapter 3 - Visual Basic Schneider
Logical errors Occurs when a program dose not perform the way it was intended A program with a logic error is a valid program in the language, though it does not behave as intended. Average = num1 + num2 / 2 Chapter 3 - Visual Basic Schneider

124 Chapter 3 - Visual Basic Schneider
Debugging The process of finding and correcting errors Chapter 3 - Visual Basic Schneider

125 Chapter 3 - Visual Basic - Schneider
Reference Chapter 3 - Visual Basic - Schneider Chapter 3 - Visual Basic Schneider

126 Chapter 3 - Visual Basic Schneider
End of chapter 3 Chapter 3 - Visual Basic Schneider


Download ppt "Fundamentals of Programming in Visual Basic"

Similar presentations


Ads by Google