Download presentation
Presentation is loading. Please wait.
1
Data Types 1
3
Single or Double ? Visual Basic provides data type Single for storing single-precision floating-point numbers. Data type Double requires more memory to store a floating-point value, but is more accurate than type Single. Type Single is useful in applications that need to conserve memory and do not require the accuracy provided by type Double.
4
Dim statement declares variable Dim varname As type [ = initexpr ]
Declaring a Variable Dim statement declares variable Dim varname As type [ = initexpr ] varname is variable name As type contains data type of variable Optional initexpr contains the initial value of a variable
5
Initialize a variable when declaring it
Declaring a Variable Initialize a variable when declaring it New to VB .NET Declare an Integer variable and store the value 30 in the variable Dim mintYearTerm As Integer = 30
6
Declaring a Variable Possible to declare multiple variables on the same line Dim mintYearTerm, mintMonthTerm As Integer
7
Declaring a Variable Dim I as Integer , S As String I = 10 S = “11”
console.WriteLine( I + S ) 21 console.WriteLine( I & S ) 1011
8
Declaring a Variable Dim dExpiration As Date dExpiration = #1/1/2003#
Dim dnewExpiration As Date dnewExpiration = dExpiration . AddYears(3)
9
Declaring Constants Declare constants with the Const statement.
Constants are similar to variables – constants are values that are stored to memory locations; however, a constant cannot have its value change during program execution – constant values are generally fixed over time. Examples: Const SALES_TAX_RATE_SINGLE As Single = F Const BIG_STATE_NAME_STRING As String = "Alaska" Const TITLE_STRING As String = "Data Entry Error" Const MAX_SIZE_INTEGER As Integer = 4000
10
Declaring Constants Follow these rules for assigning numeric values to constants: You can use numbers, a decimal point, and a plus (+) or minus (-) sign. Do not include special characters such as a comma, dollar sign, or other special characters. Append one of these characters to the end of the numeric constant or variable to denote a data type declaration. If you do not use these, a whole number is assumed to be Integer and a fractional value is assumed to be Double. Decimal D 40.45D Double R R Integer I 47852I Long L L Short S 2588S Single F F
11
Strings Such as sentences, words, letters of the alphabet, names, telephone numbers& addresses. A string constant is a sequence of characters that is treated as a single item.
12
Strings quote1 = “ The ball game isn’t over “
quote2 = “ until it is over “ quote = quote1 & “ , “ & quote2 console.writeLine ( quote ) The ball game isn’t over , until it is over
13
String Manipulation Chr (65) A Asc (“Apple”) 65 Asc(“Ahmad”) 65
“32” & chr(176) & “Fahrenheit” 32°Fahrenheit
14
String Manipulation - Example
Dim firstName, secondName, fullName As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click firstName = TextBox1.Text secondName = TextBox2.Text fullName = firstName & " " & secondName TextBox3.Text = fullName End Sub
15
Method Equals String1.Equals(“….“) True or False variable
String.Equals(Str1,Str2)True or False namespace
16
CompareTo Str1.compareTo (str2) 0 if equal
-1 if str1 < str2 …. ASCII codes if str1 > str2
17
String Functions Left (str , n ) Left(“Welcome”,3) Wel
Right(str,n )Right(“Welcome”,4) come Mid (“Welcome”,5,2) om Ucase (“Welcome”) WELCOME Trim (“ “)
18
String Functions Len (“Welcome”) = 7 Len (“Just a moment”) = 13
19
String Functions InStr (“Welcome”,”come”) 4
InStr (“Just a moment”,” “) 5 InStr (“Welcome”,” end”) 0
20
Some String Functions Len = .Length Mid = .SubString
Replace = Replace InStr = IndexOf UCase = ToUpper LCase = ToLower Split = Split Join = .Join
21
Substring function Dim s As String = "Welcome to the world"
s = s.Substring(8) ‘ “to the world” Dim r As String = "Welcome to the world" r = r.SubString(8, 6) ‘ “to the”
22
IndexOf function Dim r As Integer
TextBox1.Text = "Welcome to the grand parade" TextBox2.text = "grand“ r = TextBox1.Text.IndexOf(TextBox2.Text) ‘ if r > 0 the word is find and r is the position of the where it starts; else the word is not found.
23
Replace Function This code would produce a message replacing the word 'fool' with 'brave bloke’: Dim i As String = "Only a fool goes outside in the cold without a coat on" i = i.Replace("fool", "brave bloke") To define the point where the Replace function starts searching the string, include the number of characters you wish to start from in the command. Not only does this example only replace the second 'e' with an 'E', it cuts off the string from the point you specify. The outcome of the line below would be 'TEst' MsgBox(Replace("Test Test", "e", "E", 6))
24
StrReverse Function If you wish to flip around the front and back end of a string, then the StrReverse(string) is for you. It is used in the following way. This would pop up a message saying ‘looc si 112pac’ MsgBox(StrReverse(“cap211 is cool"))
25
Boolean Data Type It stores True (1) / False (0)
Any non-zero value will be considered as TRUE. These variables are combined with the logical operators.. AND, OR & NOT.
26
Examining Variable Types
IsNumeric() IsDate() System.Date.IsLeapYear (2001) False
27
Byte Data Type Holds integer in the range 0 255
Or signed Byte 128 Dim A,B As Byte A =233 B=50 Console.writeLine ( A + B ) you can do CInt(A) + CInt(B)
28
Converting Input Data Types
Text property always stores string values, even if the string looks like a number. Parse method – converts a string value to an equivalent numeric value for storage to a numeric variable. Parse means to examine a string character by character and convert the value to another format such as decimal, integer, or string. Dim QuantityInteger As Integer = Integer.Parse(TextBox2.Text)
29
Converting Output Data Types
In order to display numeric variable values as output the values must be converted from numeric data types to string in order to store the data to the Text property of a TextBox control. Use the ToString method. TextBox2.Text = QuantityInteger.ToString()
30
Conversion Between Data Types
1. Methods belong to the System.Convert class ToInt16 converts value to a Short ToInt32 converts value to an Integer ToInt64 converts value to a Long ToDouble converts value to a Double ToSingle converts value to a Single ToString converts value to a String
31
Conversion Between Data Types
Dim msngInput As Single = 3.44 Dim mstrInput As String = "3.95" Dim mintOutput As Integer Dim msngOutput As Single Convert a Single to an Integer mintOutput = System.Convert.ToInt32(msngInput) Convert a String to an Integer mintOutput = System.Convert.ToInt32(mstrInput) Convert a String to a Single msngOutput = System.Convert.ToSingle(mstrInput)
32
Conversion Between Data Types
2. CType and named functions: CType method Dim A As string = “34.56” Dim B As Double B = CType ( A , Double) / 1.14 Older versions of VB used named functions to convert values. Examples are the CDec (convert to Decimal) and CInt (convert to Integer): PriceDecimal = CDec(TextBox1.Text) QuantityInteger = CInt(TextBox2.Text) CDate, CDec, CStr, CLng, CChar, CBool, CByte
33
Implicit Conversion Implicit Conversion – this is conversion by VB from a narrower to wider data type (less memory to more memory) – this is done automatically as there is no danger of losing any precision. In this example, an integer (4 bytes) is converted to a double (8 bytes): BiggerNumberDouble = SmallerNumberInteger
34
Conversion – Summary Rules
Use the Parse method to convert a string to a number or to parse the value in a textbox control. Use the Convert method to convert a type of number to a different type of number
35
Chapter 4- Control Structures: Part 1
36
Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 If/Then Selection Structure 4.6 If/Then/Else Selection Structure 4.7 While Repetition Structure 4.8 Do While/Loop Repetition Structure 4.9 Do Until/Loop Repetition Structure 4.10 Assignment Operators 4.11 Formulating Algorithms: Case Study 1 (Counter- Controlled Repetition) 4.12 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition)
37
4. 13. Formulating Algorithms with Top-Down, Stepwise. Refinement:
4.13 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) 4.14 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 4 (Nested Repetition Structures) 4.15 Introduction to Windows Application Programming
38
Control Structures Normally, statements in a program are executed one after another in the order in which they are written. This is called sequential execution. A transfer of control occurs when an executed statement does not directly follow the previously executed statement in the written program.
39
Control Structures Bohm and Jacopini’s work demonstrated that all programs could be written in terms of only three control structures: the sequence structure, the selection structure, the repetition structure.
40
Control Structures Selection Structures If/Then If/Then/Else
Single-selection structure If/Then/Else Double-selection structure Select Case Multiple-selection structure
41
Control Structures Repetition Structures While Do While/Loop
Do/Loop While Do Until/Loop Do/Loop Until For/Next For Each/Next
42
Control Structures Visual Basic has 11 control structures: Sequence,
Three types of selection, Seven types of repetition. Each program is formed by combining as many of each type of control structure as is necessary.
43
If/Then Selection Structure
It is a single-entry/single-exit structure Example If studentGrade >= 60 Then Console.WriteLine(“Passed”) End If
44
If/Then Selection Structure
The preceding If/Then selection structure also could be written on a single line as If studentGrade >= 60 Then Console.WriteLine("Passed") In the multiple-line format, all statements in the body of the If/Then are executed if the condition is true. In the single-line format, only the statement after the Then keyword is executed if the condition is true. Writing the closing End If keywords after a single-line If/Then structure is a syntax error.
45
If/Then Selection Structure
Grade >= 60 true Console.WriteLine(“Passed”) false Fig. 4.3 Flowcharting a single-selection If/Then structure.
46
If/Then/Else Selection Structure
The If/Then/Else selection structure allows the programmer to specify that a different action (or sequence of actions) be performed when the condition is true than when the condition is false.
47
If/Then/Else Selection Structure
Grade >= 60 true Console.WriteLine(“Passed”) false Console.WriteLine(“Failed”) Fig. 4.4 Flowcharting a double-selection If/Then/Else structure.
48
If/Then/Else Selection Structure
Example If studentGrade >= 60 Then Console.WriteLine(“Passed”) Else Console.WriteLine(“Failed”) End If
49
If/Then/Else Selection Structure
The VB Editor tries to help you write If statements. When in the code view window, if you type the keyword If and press Enter, the VB editor automatically adds the keywords Then and End If. You can add the Else branch as necessary. The VB editor will try to correct errors. If you type EndIf with no space, the editor will correct this and add the required space. If you type Else with a coding statement on the line, the editor will add a colon between Else and the coding statement – the colon is a statement separator.
50
If/Then/Else Selection Structure
Illegal Syntax If HoursDecimal <= 40D Then RegularPayCheckBox.Checked = True Else RegularPayCheckBox.Checked = False End If VB Editor Correction with Colon Else : RegularPayCheckBox.Checked = False Preferred Syntax Else RegularPayCheckBox.Checked = False If you type Else with a coding statement on the line, the editor will add a colon between Else and the coding statement
51
Nested If/Then/Else Nested If/Then/Else structures test for multiple conditions by placing If/Then/Else structures inside other If/Then/Else structures. Most Visual Basic programmers prefer to write the nested If/Then/Else structure using the ElseIf keyword.
52
Nested If/Then/Else For example, the following code will print “A” for exam grades greater than or equal to 90, “B” for grades in the range 80–89, “C” for grades in the range 70–79, “D” for grades in the range 60–69 and “F” for all other grades.
53
While Repetition Structure
Allows the programmer to specify that an action should be repeated, depending on the value of a condition Example (pseudocode) While there are more items on my shopping list Purchase next item Cross it off my list
54
Write a program that finds the first power of two larger than 1000?
Failure to provide the body of the structure with an action that causes the condition to become false creates an infinite loop
55
While Repetition Structure
product <= 1000 true product = product * 2 false Fig. 4.6 Flowchart of the While repetition structure.
56
Do While/Loop Repetition Structure
This structure behaves like the While repetition structure
57
DoWhile.vb Program Output
Write a program to find the first power of two larger than 1000? DoWhile.vb Program Output Failure to provide the body of the structure with an action that causes the condition to become false creates an infinite loop
58
Do While/Loop Repetition Structure
product <= 1000 true product = product * 2 false Fig. 4.8 Flowchart of a Do While/Loop repetition structure.
59
Do Until/Loop Repetition Structure
Unlike the While and Do While/Loop repetition structures, the Do Until/Loop repetition structure tests a condition for falsity for repetition to continue. Statements in the body of a Do Until/Loop are executed repeatedly as long as the loop-continuation test evaluates to false.
60
DoUntil.vb Program Output
once again consider a program designed to find the first power of two larger than 1000. DoUntil.vb Program Output The loop ends when the condition becomes true
61
Do Until/Loop Repetition Structure
false product > 1000 product = product * 2 true Fig Flowcharting the Do Until/Loop repetition structure.
62
Assignment Operators Fig Assignment operators.
63
Assignment.vb Program Output
Calculates a power of two using the exponentiation assignment operator. Assignment.vb Program Output
64
Assignment Operators Although the symbols =, +=, -=, *=, /=, \=, ^= and &= are operators, we do not include them in operator-precedence tables. When an assignment statement is evaluated, the expression to the right of the operator is always evaluated first, then assigned to the variable on the left. Unlike Visual Basic’s other operators, the assignment operators can only occur once in a statement.
65
Property ReadOnly = true
Space Counter Example Property ReadOnly = true
66
Space Counter Example Public Class Form1
Private Sub btnCount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCount.Click Dim i, counter As Integer, A As String counter = 0 For i = 1 To Len(txtString.Text) A = Mid(txtString.Text, i, 1) If A = " " Then counter = counter + 1 Else txtStringNoSpace.Text = txtStringNoSpace.Text & A End If Next i txtSpacesNo.Text = counter End Sub Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click txtString.Clear() txtSpacesNo.Text = "" txtStringNoSpace.Text = "" End Class
67
A MUST… You must practice lots of string manipulation examples check the following websites:
68
Case Study 1 (Counter-Controlled Repetition)
Uses counter: Variable that specifies the number of times that a set of statements will execute Example: A class of ten students took a quiz. The grades (integers in the range from 0 to 100) for this quiz are available to you. Determine the class average on the quiz.
70
Program Output Enter integer grade: 89 Enter integer grade: 70
Class average is 74.5
71
Case Study 2 (Sentinel-Controlled Repetition)
Develop a class-averaging program that averages an arbitrary number of grades each time the program is run. In the first class-average example, the number of grades (10) was known in advance. In this example, no indication is given of how many grades are to be input. The program must process an arbitrary number of grades. How can the program determine when to stop the input of grades? How will it know when to calculate and print the class average?
72
Case Study 2 (Sentinel-Controlled Repetition)
One way to solve this problem is to use a special value called a sentinel value (also called a signal value, a dummy value or a flag value) to indicate “end of data entry.” The user inputs all grades and then types the sentinel value to indicate that the last grade has been entered. It is crucial to employ a sentinel value that cannot be confused with an acceptable input value. Grades on a quiz are normally nonnegative integers, thus –1 is an acceptable sentinel value for this problem.
73
In sentinel-controlled repetition, a value is read before the program reaches the While structure
Test division by zero print the value of average in the command window as a fixed-point number.
74
Program Output Enter Integer Grade, -1 to Quit: 97
Class average is 85.67
75
Case Study 3 (Nested-Control Structure)
A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, 10 of the students who completed this course took the licensing examination. The college wants to know how well its students did on the exam. You have been asked to write a program to summarize the results. You have been given a list of the 10 students. Next to each name is written a “P” if the student passed the exam and an “F” if the student failed the exam. Your program should analyze the results of the exam as follows: 1. Input each exam result (i.e., a “P” or an “F”). Display the message “Enter result” each time the program requests another exam result. 2. Count the number of passes and failures. 3. Display a summary of the exam results, indicating the number of students who passed and the number of students who failed the exam. 4. If more than 8 students passed the exam, print the message “Raise tuition.”
76
The If/Then/Else structure is a nested control
The If/Then/Else structure is a nested control. It is enclosed inside the While. Identifier vbCrLf is the combination of the carriage return and linefeed characters
77
Program Output
78
Case Study 4 (Nested-Repetition Structure)
Write a program that draws in the command window a filled square consisting solely of * characters. The side of the square (i.e., the number of * characters to be printed side by side) should be input by the user and should not exceed 20.
79
Three levels of nesting
80
Program Output
81
Introduction to Windows Application Programming
In console applications, execution starts from Main. In Windows applications, if you want a method like main you must create a method that executes when the form is loaded into memory during program execution. Like Main, this method is invoked when the program is run. Double-clicking the form in design view adds a method named FrmASimpleProgram_Load to the class, which is responsible for that
82
Introduction to Windows Application Programming
Fig Method FrmASimpleProgram_Load containing program code.
83
Conclusion Normally, statements in a program are executed one after another in the order in which they are written. This is called sequential execution. • Various Visual Basic statements enable the programmer to specify that the next statement to be executed might not be the next one in sequence. This is called a transfer of control. Bohm and Jacopini’s work demonstrated that all programs could be written in terms of only three control structures—the sequence structure, the selection structure and the repetition structure.
84
Conclusion Failure to provide in the body of a While or Do While/Loop structure an action that eventually causes the condition to become false is a logic error. Normally, such a repetition structure never terminates, resulting in an error called an “infinite loop.” Failure to provide the body of a Do Until/Loop structure with an action that eventually causes the condition in the Do Until/Loop to become true creates an infinite loop. Data types Double and Single store floating-point numbers. Data type Double requires more memory to store a floating-point value, but is more accurate and generally more efficient than type Single
85
Conclusion In Counter-controlled the number of repetitions is known before the loop begins executing. In sentinel-controlled repetition, the number of repetitions is not known before the loop begins its execution.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.