You are on page 1of 2

Experiments with Loops

You will be using the LoopExperiments workbook with these exercises. As usual,
when the question asks you to say what some code will do, you should first write
down what you think it will do, then run it to see if you were right, and write down
what it actually does.
1. Look at the code for button Q1, and run the program by clicking the button.
a. What does the code inside the loop do? (Describe in your own words.)

b. Note that the value of variable limit is set to 4 before we execute


the loop. How many times does the loop execute? (You can determine
this by seeing how many times the word Hi! prints in the list box. Or,
you can step through the loop and count how many times the loop is
done.
c. Change the value of limit to 1 by changing the line in the code that
sets the value of limit. Now how many times does the code execute?
d. Change the value of limit to 0. Now how many times does the code
execute?
e. Change the line For j = 1 to limit to read For j = 2 to limit,
and set the value of limit to 4. Now how many times does the loop
execute?
f.

Try setting limit to 1 and running the program again. Now how many
times does the loop execute?

g. Explain in your own words what happens when the value of limit is
smaller than the initial value of j.

2. Look at the code for button Q2.


a. How many times is this loop executed?
b. If I change the limit to 8, what is the final value of sum?
c. Describe in your own words what this loop does.
3. Look at the code for button Q3.
a. How many times does the loop inside this code run?
b. If I wanted it to run six times, what change could I make?

c. In the line of code sum = sum + 2*j, which variable is changed?


d. In that same line, which variable is used, but not changed? (Use the
debugger running with the F8 key or locals window to check if you are
not sure.)
4. Look at the code for Q4.
a. How many times does the loop in this code run?
b. Note that I needed to add the line j = 1 before starting the loop,
and j = j + 1 inside the loop, as compared to the For loops weve
used up till now. What if I changed j = 1 to j = 3? (Try it.) How
many times does the loop run now?
c. What would happen if by mistake I put Do While j >= limit
instead of Do while j <= limit at the beginning of the loop? Why?
d. Which line(s) in the code for button Q4 changes variable j?
e. Which line(s) in this code changes variable sum?
f.

What happens if I set limit to 6 initially, and change j = j + 1 to j =


j + 2?

5. Button Q5 has no code. Write a loop that will print the numbers 5, 10, 15, 20,
25, 30, 35 vertically in the list box. There are a number of ways to do this;
you may use any way that works as long as it uses a loop. Copy and paste
your code here.

You might also like