Tracing and Writing For Loops WS 1

advertisement
Visual Basic
Tracing For Loops Worksheet #1
Name____________________________
Trace the following code segments showing the values for each variable in the appropriate columns. Write
"infinite loop" if the loop never ends. Write "error" if you think there is a syntax error. Circle your final values.
1.
Dim intSum As Integer = 0
For J = 1 To 5
intSum = intSum + 1
Next
2.
Dim intSum As Integer = 0
For J = 2 To 10 Step 2
intSum = intSum + 1
Next
3.
Dim intSum As Integer = 0
For J = -3 To 3
intSum = intSum + 1
Next
4.
Dim intSum As Integer = 10
For J = 5 To 1 Step -1
intSum = intSum - 1
Next
5.
Dim intSum As Integer = 0
For J = 12 To 20 Step 3
intSum = intSum + 1
Next
6.
Dim intSum As Integer = 0
For J = 1 To 5
intSum = intSum + J
Next
intSum
J
Visual Basic
Writing For Loops Worksheet #1
Name____________________________
Write the following code segments & trace the loops and show the values of each variable in
columns to the right margin.
1. Write a For loop that adds the integers -6 through 5 and stores the sum in the variable intSum.
2. Write a For loop that adds the even integers between 20 and 34 and stores the sum in the variable intSum
3. Write a For loop that displays each of the values in the sequence 24, 28, 32, 36, …, 52 in a message
box.
4. Write a For loop that computes the sum of the values in the sequence 1, 3, 6, 10, 15, 21, …, 55 and
stores that sum in the variable intSum. Hint: Use a variable as a Step value and increment that variable
in the loop.
Download