Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Visual Basic

Similar presentations


Presentation on theme: "Introduction to Visual Basic"— Presentation transcript:

1 Introduction to Visual Basic
Introduction to Visual Basic .Net Programming, Control Structures and Operators Outline 3.2 Simple Program: Printing a Line of Text 3.3 Another Simple Program: Adding Integers 3.7 Using a Dialog to Display a Message 4.4   Control Structures 4.5   If/Then Selection Structure 4.6   If/Then/Else Selection Structure 5.5   Select Case Multiple-Selection Structure 4.7   While Repetition Structure 4.8   Do While/Loop Repetition Structure 4.9   Do Until/Loop Repetition Structure 5.3   For/Next Repetition Structure 5.6   Do/Loop While Repetition Structure 5.7   Do/Loop Until Repetition Structure 5.8 Using the Exit Keyword in a Repetition Structure 3.5 Arithmetic Operators 3.6 Equality and Relational Operators 4.10   Assignment Operators 5.9   Logical Operators 4.15   Introduction to Windows Application Programming

2 3.2 Simple Program: Printing a Line of Text
Simple console application that displays a line of text When the program is run output appears in a command window It illustrates important Visual Basic features Comments Modules Sub procedures

3 A few Good Programming Practices
1 ' Fig. 3.1: Welcome1.vb 2 ' Simple Visual Basic program. 3 4 Module modFirstWelcome 5 Sub Main() Console.WriteLine("Welcome to Visual Basic!") End Sub 9 10 End Module Visual Basic console applications consist of pieces called modules The Main procedure is the entry point of the program. It is present in all console applications The Console.WriteLine statement displays text output to the console Single-quote character (') indicates that the remainder of the line is a comment Welcome to Visual Basic! A few Good Programming Practices Comments - Every program should begin with one or more comments Modules - Begin each module with mod to make modules easier to identify Procedures (subroutines) - Indent the entire body of each procedure definition one “level” of indentation

4 3.2 Simple Program: Printing a Line of Text
Now a short step-by-step explanation of how to create and run this program using the features of Visual Studio .NET IDE…

5 3.2 Simple Program: Printing a Line of Text
Create the console application Select File > New > Project… In the left pane, select Visual Basic Projects In the right pane, select Console Application Name the project Welcome1 Specify the desired location Change the name of the program file Click Module1.vb in the Solution Explorer window In the Properties window, change the File Name property to Welcome1.vb

6 3.2 Simple Program: Printing a Line of Text
Left pane Right pane Project name File location Fig. 3.2 Creating a Console Application with the New Project dialog.

7 3.2 Simple Program: Printing a Line of Text
Editor window (containing program code) Fig. 3.3 IDE with an open console application.

8 3.2 Simple Program: Printing a Line of Text
Solution Explorer Click Module1.vb to display its properties Properties window File Name property Fig. 3.4 Renaming the program file in the Properties window.

9 3.2 Simple Program: Printing a Line of Text
Change the name of the module Module names must be modified in the editor window Replace the identifier Module1 with modFirstWelcome Writing code Type the code contained in line 7 of Fig. 3.1 between Sub Main() and End Sub Note that after typing the class name and the dot operator the IntelliSense is displayed. It lists a class’s members. Note that when typing the text between the parenthesis (parameter), the Parameter Info and Parameter List windows are displayed

10 3.2 Simple Program: Printing a Line of Text
Run the program To compile, select Build > Build Solution This creates a new file, named Welcome1.exe To run, select Debug > Start Without Debugging

11 3.2 Simple Program: Printing a Line of Text
Partially-typed member Member list Description of highlighted member Fig. 3.5 IntelliSense feature of the Visual Studio .NET IDE.

12 3.2 Simple Program: Printing a Line of Text
Up arrow Down arrow Parameter List window Parameter Info window Fig. 3.6 Parameter Info and Parameter List windows.

13 3.2 Simple Program: Printing a Line of Text
Command window prompts the user to press a key after the program terminates Fig. 3.7 Executing the program shown in Fig. 3.1.

14 3.2 Simple Program: Printing a Line of Text
Omitted parenthesis character (syntax error) Blue underline indicates a syntax error Task List window Error description(s) Fig. 3.8 IDE indicating a syntax error.

15 1 ' Fig. 3.9: Welcome2.vb 2 ' Writing line of text with multiple statements. 3 4 Module modSecondWelcome 5 Sub Main() Console.Write("Welcome to ") Console.WriteLine("Visual Basic!") End Sub ' Main 11 12 End Module ' modSecondWelcome Method Write does not position the output cursor at the beginning of the next line Method WriteLine positions the output cursor at the beginning of the next line Welcome to Visual Basic!

16 3.3 Another Simple Program: Adding Integers
User input two integers Whole numbers Program computes the sum Display result

17 These variables store strings of characters Addition.vb
1 ' Fig. 3.10: Addition.vb 2 ' Addition program. 3 4 Module modAddition 5 Sub Main() 7 ' variables for storing user input Dim firstNumber, secondNumber As String 10 ' variables used in addition calculation Dim number1, number2, sumOfNumbers As Integer 13 ' read first number from user Console.Write("Please enter the first integer: ") firstNumber = Console.ReadLine() 17 ' read second number from user Console.Write("Please enter the second integer: ") secondNumber = Console.ReadLine() 21 ' convert input values to Integers number1 = firstNumber number2 = secondNumber 25 sumOfNumbers = number1 + number2 ' add numbers 27 ' display results Console.WriteLine("The sum is {0}", sumOfNumbers) 30 End Sub ' Main 32 End Module ' modAddition These variables store strings of characters Addition.vb Variable declarations begin with keyword Dim First value entered by user is assigned to variable firstNumber These variables store integers values Method ReadLine causes program to pause and wait for user input Implicit conversion from String to Integer Sums integers and assigns result to variable sumOfNumbers Format indicates that the argument after the string will be evaluated and incorporated into the string

18 Fig. 3.11 Dialog displaying a run-time error.
Please enter the first integer: 45 Please enter the second integer: 72 The sum is 117 If the user types a non-integer value, such as “hello,” a run-time error occurs Fig Dialog displaying a run-time error.

19 3.7 Using a Dialog to Display a Message
Dialogs Windows that typically display messages to the user Visual Basic provides class MessageBox for creating dialogs

20 SquareRoot.vb Program Output
1 ' Fig. 3.20: SquareRoot.vb 2 ' Displaying square root of 2 in dialog. 3 4 Imports System.Windows.Forms ' Namespace containing MessageBox 5 6 Module modSquareRoot 7 8 Sub Main() 9 ' Calculate square root of 2 Dim root As Double = Math.Sqrt(2) 12 ' Display results in dialog MessageBox.Show("The square root of 2 is " & root, _ "The Square Root of 2") 16 End Sub ' Main 17 18 End Module ' modThirdWelcome SquareRoot.vb Program Output Sqrt method of the Math class is called to compute the square root of 2 Method Show of class MessageBox The Double data type stores floating-point numbers Line-continuation character Empty command window

21 3.7 Using a Dialog to Display a Message
Assembly File that contain many classes provided by Visual Basic These files have a .dll (or dynamic link library) extension. Example Class MessageBox is located in assembly System.Windows.Forms.dll MSDN Documentation Information about the assembly that we need can be found in the MSDN documentation Select Help > Index… to display the Index dialog

22 3.7 Using a Dialog to Display a Message
Search string Filter Link to MessageBox documentation Fig Obtaining documentation for a class by using the Index dialog.

23 3.7 Using a Dialog to Display a Message
Requirements section heading MessageBox class documentation Assembly containing class MessageBox Fig Documentation for the MessageBox class.

24 3.7 Using a Dialog to Display a Message
Reference It is necessary to add a reference to the assembly if you wish to use its classes Example To use class MessageBox it is necessary to add a reference to System.Windows.Forms Imports Forgetting to add an Imports statement for a referenced assembly is a syntax error

25 3.7 Using a Dialog to Display a Message
Solution Explorer before reference is added References folder (expanded) Solution Explorer after reference is added System.Windows.Forms reference Fig Adding a reference to an assembly in the Visual Studio .NET IDE.

26 3.7 Using a Dialog to Display a Message
Button (displaying an icon) Label Menu (e.g., Help) Text box Menu bar Fig Internet Explorer window with GUI components.

27 4.4 Control Structures Transfer of control Bohm and Jacopini
GoTo statement It causes programs to become quite unstructured and hard to follow Bohm and Jacopini All programs could be written in terms of three control structures Sequence structure Selection structure Repetition structure

28 4.4 Control Structures Selection Structures If/Then If/Then/Else
Single-selection structure If/Then/Else Double-selection structure Select Case Multiple-selection structure

29 Repetition Structures
4.4 Control Structures Repetition Structures While Do While/Loop Do/Loop While Do Until/Loop Do/Loop Until For/Next For Each/Next

30 Visual Basic keywords

31 Visual Basic keywords

32 4.5 If/Then Selection Structure
A selection structure chooses among alternative courses of action. It is a single-entry/single-exit structure Example If studentGrade >= 60 Then Console.WriteLine("Passed") End If

33 4.6 If/Then/Else Selection Structure
Example If studentGrade >= 60 Then Console.WriteLine("Passed") Else Console.WriteLine("Failed") End If

34 Nested If/Then/Else Selection Structure
Test for multiple conditions by placing one structure inside the other. ElseIf keyword Example If studentGrade >= 60 Then Console.WriteLine("Good") ElseIf studentGrade >= 40 Console.WriteLine("Medium") Else Console.WriteLine("Bad") End If

35 5.5 Select Case Multiple-Selection Structure
Tests expression separately for each value expression may assume Select Case keywords begin structure Followed by controlling expression Compared sequentially with each case Code in case executes if match is found Program control proceeds to first statement after structure Case keyword Specifies each value to test for Followed by code to execute if test is true Case Else Optional Executes if no match is found Must be last case in sequence

36 Select Case begins multiple-selection structure
1 ' Fig. 5.10: SelectTest.vb 2 ' Using the Select Case structure. 3 4 Module modEnterGrades 5 Sub Main() Dim grade As Integer = 0 ' one grade Dim aCount As Integer = 0 ' number of As Dim bCount As Integer = 0 ' number of Bs Dim cCount As Integer = 0 ' number of Cs Dim dCount As Integer = 0 ' number of Ds Dim fCount As Integer = 0 ' number of Fs 13 Console.Write("Enter a grade, -1 to quit: ") grade = Console.ReadLine() 16 ' input and process grades While grade <> -1 19 Select Case grade ' check which grade was input 21 Case ' student scored 100 Console.WriteLine("Perfect Score!" & vbCrLf & _ "Letter grade: A" & vbCrLf) aCount += 1 26 Case 90 To ' student scored 90-99 Console.WriteLine("Letter Grade: A" & vbCrLf) aCount += 1 30 Case 80 To ' student scored 80-89 Console.WriteLine("Letter Grade: B" & vbCrLf) bCount += 1 34 SelectTest.vb Select Case begins multiple-selection structure Controlling expression First Case executes if grade is exactly 100 Next Case executes if grade is between 90 and 99, the range being specified with the To keyword Identifier vbCrLf is the combination of the carriage return and linefeed characters

37 Optional Case Else executes if no match occurs with previous Cases
Case 70 To ' student scored 70-79 Console.WriteLine("Letter Grade: C" & vbCrLf) cCount += 1 38 Case 60 To ' student scored 60-69 Console.WriteLine("Letter Grade: D" & vbCrLf) dCount += 1 42 ' student scored 0 or (10 points for attendance) Case 0, 10 To 59 Console.WriteLine("Letter Grade: F" & vbCrLf) fCount += 1 47 Case Else 49 ' alert user that invalid grade was entered Console.WriteLine("Invalid Input. " & _ "Please enter a valid grade." & vbCrLf) End Select 54 Console.Write("Enter a grade, -1 to quit: ") grade = Console.ReadLine() End While 58 ' display count of each letter grade Console.WriteLine(vbCrLf & _ "Totals for each letter grade are: " & vbCrLf & _ "A: " & aCount & vbCrLf & "B: " & bCount _ & vbCrLf & "C: " & cCount & vbCrLf & "D: " & _ dCount & vbCrLf & "F: " & fCount) 65 End Sub ' Main 67 68 End Module ' modEnterGrades SelectTest.vb Optional Case Else executes if no match occurs with previous Cases End Select marks end of structure

38 Program Output Enter a grade: 84 Letter Grade: B Enter a grade: 100
Enter a grade: 100 Perfect Score! Letter grade : A+ Enter a grade: 7 Invalid Input. Please enter a valid grade. Enter a grade: 95 Letter Grade: A Enter a grade: 78 Letter Grade: C Totals for each letter grade are: A: 2 B: 1 C: 1 D: 0 F: 0 Program Output

39 4.7 While Repetition Structure
Executes an action while the condition is true Example ' writes numbers from 1 to 10 Dim number As Integer = 1 While number <= 10 Console.Write("{0} ", number) number = number + 1 End While

40 4.8 Do While/Loop Repetition Structure
Behaves like the While repetition structure Example ' writes numbers from 1 to 10 Dim number As Integer = 1 Do While number <= 10 Console.Write("{0} ", number) number = number + 1 Loop

41 4.9 Do Until/Loop Repetition Structure
Executes an action until a condition is false Example ' writes numbers from 1 to 10 Dim number As Integer = 1 Do Until number > 10 Console.Write("{0} ", number) number = number + 1 Loop

42 5.6 Do/Loop While Repetition Structure
Similar to While and Do/While Loop-continuation condition tested after body executes Loop body always executed at least once Begins with keyword Do Ends with keywords Loop While followed by condition Example ' writes numbers from 1 to 10 Dim number As Integer = 1 Do Console.Write("{0} ", number) number = number + 1 Loop While (number <= 10)

43 5.7 Do/Loop Until Repetition Structure
Similar to Do Until/Loop structure Loop-continuation condition tested after body executes Loop body always executed at least once Example ' writes numbers from 1 to 10 Dim number As Integer = 1 Do Console.Write("{0} ", number) number = number + 1 Loop Until number > 10

44 5.3 For/Next Repetition Structure
For/Next counter-controlled repetition Structure header initializes control variable, specifies final value and increment For keyword begins structure Followed by control variable initialization To keyword specifies final value Step keyword specifies increment Optional Increment defaults to 1 if omitted May be positive or negative Next keyword marks end of structure Executes until control variable greater (or less) than final value

45 5.3 For/Next Repetition Structure
Example ' writes numbers from 1 to 10 Dim number As Integer For counter = 1 To 10 Step 1 Console.Write("{0} ", number) Next

46 5.4 Examples Using the For/Next Structure
Vary the control variable from 1 to 100 in increments of 1 For i = 1 To 100 For i = 1 To 100 Step 1 Vary the control variable from 100 to 1 in increments of –1 For i = 100 To 1 Step –1 Vary the control variable from 7 to 77 in increments of 7 For i = 7 To 77 Step 7 Vary the control variable from 20 to 2 in increments of –2 For i = 20 To 2 Step -2

47 Control variable counts by 2, from 2 to 100 Sum.vb Program Output
1 ' Fig. 5.5: Sum.vb 2 ' Using For/Next structure to demonstrate summation. 3 4 Imports System.Windows.Forms 5 6 Module modSum 7 Sub Main() 9 Dim sum = 0, number As Integer 11 ' add even numbers from 2 to 100 For number = 2 To 100 Step 2 sum += number Next 16 MessageBox.Show("The sum is " & sum, _ "Sum even integers from 2 to 100", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 21 22 End Module ' modSum Control variable counts by 2, from 2 to 100 Sum.vb Program Output Value of number is added in each iteration to determine sum of even numbers Text displayed in dialog Display a MessageBox Text displayed in title bar Indicate button to be OK button Indicate icon to be Information icon

48 5.4 Examples Using the For/Next Structure
Fig. 5.6 Icons for message dialogs.

49 5.4 Examples Using the For/Next Structure
Fig. 5.7 Button constants for message dialogs.

50 Type Decimal used for precise monetary calculations
1 ' Fig. 5.8: Interest.vb 2 ' Calculating compound interest. 3 4 Imports System.Windows.Forms 5 6 Module modInterest 7 Sub Main() 9 Dim amount, principal As Decimal ' dollar amounts Dim rate As Double ' interest rate Dim year As Integer ' year counter Dim output As String ' amount after each year 14 principal = rate = 0.05 17 output = "Year" & vbTab & "Amount on deposit" & vbCrLf 19 ' calculate amount after each year For year = 1 To 10 amount = principal * (1 + rate) ^ year output &= year & vbTab & _ String.Format("{0:C}", amount) & vbCrLf Next 26 ' display output MessageBox.Show(output, "Compound Interest", _ MessageBoxButtons.Ok, MessageBoxIcon.Information) 30 End Sub ' Main 32 33 End Module ' modInterest Type Decimal used for precise monetary calculations Interest.vb Perform calculation to determine amount in account Append year followed by the formatted calculation result and newline character to end of String output Specify C (for “currency”) as formatting code

51 Program Output

52 5.4 Examples Using the For/Next Structure
Fig. 5.9 String formatting codes.

53 5.8 Using the Exit Keyword in a Repetition Structure
Exit Statements Alter the flow of control Cause immediate exit from a repetition structure Exit Do Executed in Do structures Exit For Executed in For structures Exit While Executed in While structures

54 Loop specified to execute 10 times
1 ' Fig. 5.16: ExitTest.vb 2 ' Using the Exit keyword in repetition structures. 3 4 Imports System.Windows.Forms 5 6 Module modExitTest 7 Sub Main() Dim output As String Dim counter As Integer 11 For counter = 1 To 10 13 ' skip remaining code in loop only if counter = 3 If counter = 3 Then Exit For End If 18 Next 20 output = "counter = " & counter & _ " after exiting For/Next structure" & vbCrLf 23 Do Until counter > 10 25 ' skip remaining code in loop only if counter = 5 If counter = 5 Then Exit Do End If 30 counter += 1 Loop 33 ExitTest.vb Loop specified to execute 10 times Exit For statement executes when condition is met, causing loop to exit Program control proceeds to first statement after the structure counter is 3 when loop starts, specified to execute until it is greater than 10 Exit Do executes when counter is 5, causing loop to exit

55 Exit While executes when counter is 7, causing loop to exit
output &= "counter = " & counter & _ " after exiting Do Until/Loop structure" & vbCrLf 36 While counter <= 10 38 ' skip remaining code in loop only if counter = 7 If counter = 7 Then Exit While End If 43 counter += 1 End While 46 output &= "counter = " & counter & _ " after exiting While structure" 49 MessageBox.Show(output, "Exit Test", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 53 54 End Module ' modExitTest counter is 5 when loop starts, specified to execute while less than or equal to 10 Program Output Exit While executes when counter is 7, causing loop to exit

56 3.5 Arithmetic Operators

57 3.6 Equality and Relational Operators

58 4.10 Assignment Operators Binary operators Example
variable = variable operator expression variable operator= expression Example Addition assignment operator, += value = value + 3 value += 3

59 4.10 Assignment Operators Fig Assignment operators.

60 Used to form complex conditions by combining simple ones
5.9 Logical Operators Used to form complex conditions by combining simple ones Short-circuit evaluation Execute only until truth or falsity is known AndAlso operator Returns true if and only if both conditions are true OrElse operator Returns true if either or both of two conditions are true

61 5.9 Logical Operators (II)
Logical Operators without short-circuit evaluation And and Or Similar to AndAlso and OrElse respectively Always execute both of their operands Used when an operand has a side effect Condition makes a modification to a variable Should be avoided to reduce subtle errors Xor Returns true if and only if one operand is true and the other false

62 5.9 Logical Operators (III)
Logical Negation Not Used to reverse the meaning of a condition Unary operator Requires one operand Can usually be avoided by expressing a condition differently

63 5.9 Logical Operators

64 5.9 Logical Operators

65 Precedence and Associativity of Operators
higher precedence lower precedence

66 4.15 Introduction to Windows Application Programming
Consists of at least one class Inherits from class Form Form is called the superclass or base class Keyword Class Begins a class definition and is followed by the class name Keyword Inherits Indicates that the class inherits existing pieces from another class

67 4.15 Introduction to Windows Application Programming
Collapsed code Fig IDE showing program code for Fig

68 4.15 Introduction to Windows Application Programming
Windows Form Designer generated code Collapsed by default The code is created by the IDE and normally is not edited by the programmer Present in every Windows application

69 4.15 Introduction to Windows Application Programming
Expanded code Fig Windows Form Designer generated code when expanded.

70 4.15 Introduction to Windows Application Programming
Click here for code view Click here for design view Property initializations for lblWelcome Fig Code generated by the IDE for lblWelcome.

71 4.15 Introduction to Windows Application Programming
How IDE updates the generated code Modify the file name Change the name of the file to ASimpleProgram.vb Modify the label control’s Text property using the Properties window Change the property of the label to “Deitel and Associates” Examine the changes in the code view Switch to code view and examine the code Modifying a property value in code view Change the string assigned to Me.lblWelcome.Text to “Visual Basic .NET”

72 4.15 Introduction to Windows Application Programming
Text property Fig Using the Properties window to set a property value.

73 4.15 Introduction to Windows Application Programming
Text property Fig Windows Form Designer generated code reflecting new property values.

74 4.15 Introduction to Windows Application Programming
Text property Fig Changing a property in the code view editor.

75 4.15 Introduction to Windows Application Programming
Text property value Fig New Text property value reflected in design mode.

76 4.15 Introduction to Windows Application Programming
Change the label’s Text Property at runtime Add a method named FrmASimpleProgram_Load to the class Add the statement lblWelcome.Text = "Visual Basic" in the body of the method definition Examine the results of the FrmASimpleProgram_Load method Select Build > Build Solution then Debug > Start

77 4.15 Introduction to Windows Application Programming
FrmASimpleProgram_Load method Fig Adding program code to FrmASimpleProgram_Load.

78 4.15 Introduction to Windows Application Programming
Fig Method FrmASimpleProgram_Load containing program code.


Download ppt "Introduction to Visual Basic"

Similar presentations


Ads by Google