<<

Given a list of in a file, find the sum of the numbers in the list Pseudo Code Read next sum = next Do While Not End of File Read next sum = sum + next End If Loop Print sum Private Sub Command1_Click() Dim sum, newnum As Open "test.txt" For Input As #1 Input #1, newnum sum = newnum Do While Not EOF(1) Input #1, newnum sum = sum + newnum Loop Close #1 Print sum End Sub Given a list of numbers in a file, find the maximum of the list Pseudo Code Read next max = next Do While Not End of File Read next If max < next Then max = next End If Loop Private Sub Command1_Click() Dim max, newnum As Integer Open "test.txt" For Input As #1 Input #1, newnum max = newnum Do While Not EOF(1) Input #1, newnum If max < newnum Then max = newnum End If Loop Close #1 End Sub Do .. Loop

Suitable if we do not know how many times we need to execute the loop

We only know the condition(s) for exiting the loop

Also called Indeterminate Loops For .. Next Loop

Suitable when we know how many times we need to execute a loop Also called Determinate Loops

Example: Display the first 20 numbers in the Fibonacci sequence Private Sub Command1_Click() Dim a1, a2, Sum, i As Integer a1 = 1 a2 = 1 Print a1 Print a2 For i = 3 To 20 Sum = a1 + a2 a1 = a2 a2 = Sum Print a2 Next i End Sub General For .. Next Loop

Step size need not be 1 Can also step down Example For i = 10 To 2 Step –2 Print 2^I Next i What happens if you undershoot?

Continues until the counter is less than the ending value (when down)

Continues until the counter is more than the ending value (when counting up) Private Sub Command1_Click()

Dim i As Integer For i = 10 To 2 Step -2 Print 2 ^ i Next i

End Sub • Sets the counter variable to the starting value • Checks if the counter value is less (greater) than or equal to the ending value • Does nothing if greater (less) than ending value • If starting value is less (greater) than or equal to ending value, processes all statements up to Next • Adds step value to counter value and starts process all over again • Process continues until counter value is larger (smaller) than ending value For .. Next can even have fractional step! For example: Private Sub Command1_Click() Dim i As Single For i = 1 To 5 Step 0.5 Print 2 ^ i Next i End Sub Should declare counter variable as single for fractional steps For .. Next Loop

Always use integer values for the counter - efficiency in calculation - accuracy in calculation Other programming languages restrict counter variables to be integer While .. Wend Loop

While condition statement(s) Wend

Not used much in Visual Basic Was introduced to preserve compatibility with the interpreted version of Basic that preceded Visual Basic