Statements - Suraj @ LUMS

Introduction to
Computing
Dr. Nadeem A Khan
Lecture 24
For…Next Loops
► The
general format with step of 1:
For i = m To n
Statements
Next i
For Next Loops
►
Convert to For.. Next Loop
Sub Command1_Click ( )
Dim num As Integer
Let num=1
Do While num<=10
Picture1.Print num;
Let num=num+1
Loop
End Sub
For Next Loops
►
Example with For.. Next Loop
Sub Command1_Click ( )
Dim num As Integer
For num=1 To 10
Picture1.Print num;
Next num
End Sub
For Next Loops
► The
result:
1 2 3 4 5 6 7 8 9 10
For…Next Loops
► The
general format with steps:
For i = m To n Step s
Statements
Next i
=> Each time increment: i = i + s;
m, n, s could be numeric expressions
For Next Loops
►
Example with For.. Next Loop with steps
Sub Command1_Click ( )
Dim num As Integer
For num= 1 To 10 Step 2
Picture1.Print num;
Next num
End Sub
The output?
For Next Loops
► The
result:
13579
Nested Loops: For…Next
► Rewrite
the following program using nested
For.. Next Loop
Nested Loops: For…Next
Sub Command1_Click ( )
Dim num As Integer, counter As Integer
Let counter=1
Do While counter<=4
Let num=1
Do While num<=10
Picture1.Print num;
Let num=num+1
Loop
Let counter=counter+1
Picture1.Print
Loop
End Sub
Nested Loops: For…Next
Sub Command1_Click ( )
Dim num As Integer, counter As Integer
For counter = 1 To 4
For num =1 To 10
Picture1.Print num;
Next num
Picture1.Print
Next counter
End Sub
Nested Loops
► The
result:
1
1
1
1
5
5
5
5
2
2
2
2
3
3
3
3
4
4
4
4
6
6
6
6
7
7
7
7
8
8
8
8
9
9
9
9
10
10
10
10
For Next Loops
►
Reverses the input string
Sub Command1_Click ( )
Picture1.Cls
Picture1.Print Reverse$((Text1.Text))
End Sub
For Next Loops
Function Reverse$ (info As String)
Dim m As Integer, j As Integer, temp As String
Let temp = “”
For j = Len(info) To 1 Step -1
Let temp = temp + Mid$(info, j, 1)
Next
Reverse$ = temp
End Function
Exit For
► Exit
For: Works similar as Exit Do
Note:
► Read:
Schneider Chapter 6, Warner Chapter 6
► Read comments and do practice problems
of these sections
► Attempt some questions of Exercises
Chapter 7:
Array Variables (Arrays)
Array Variables (Arrays)
►
Array:
 A list of values can be assigned
 Collection of variables of the same
type
Array Variables (Arrays)
►
Array Declaration:
Dim arrayName (1 to n) As varType
e.g:
Dim names(1 To 3) as Strings
Dim scores(1 To 10) as Single
Array Variables (Arrays)
► Value
assignment:
Dim names(1 To 3) as Strings
Let names(1)=“Aslam”
Let names(2)=“Khalid”
Let names(3)=“Akbar”
Picture1.Print names(3), names(2),names(1)
Array Variables (Arrays)
► What
is what?
Dim scores(1 To 3) as Single
scores( ):
scores(1):
scores(2):
scores(3):
1, 2, 3:
name of the array
first element
second element
third element
subscripts
Array Variables (Arrays)
► What
are the ranges or dimensions?
Dim scores(1 To 3) as Single
Dim names(1 To 10) as String
End