~ Programming in VB.Net


Iteration - click on a link to get started

Introducing Iteration

An incredibly important part of computing is the idea of iteration, that is repeating the same thing again and again. You probably use iteration every day. Take writing lines in a detention for example; you write some lines, check to see if you have met the line limit, and if you haven't you write some more lines, check if you have met the line limit and so on, until you do meet the line limit and then you can stop.

'Programmers are lazy and can get computers to write detention lines for them
'they are also lazy as they can do a declaration and assignment at the same time:
dim count as integer = 0

While count <= 100
   console.writeline(count & ". I should always do my programming homework.")
   count = count + 1
End While
  Blank.svg Code Output

0. I should always do my programming homework.
1. I should always do my programming homework.
2. I should always do my programming homework.
3. I should always do my programming homework.
...
100. I should always do my programming homework.

 

Comprehension Exercise: While Loops
  1. How many lines will be printed by this while loop?
  2. What value will be stored in the variable count immediately after the loop has finished executing?
  3. How many times will the condition at the top of the loop (count <= 100) be tested?

Think carefully before you answer each of these.

Answer :

  1. 101 lines, starting with the line numbered 0, and ending with the line numbered 100.
  2. count will contain the value 101 upon exiting the loop.
  3. The test will be performed 102 times. The first 101 times the condition count <= 100 will be true, so the body of the loop will be executed. On the 102nd occasion (when count is 101), the condition count <= 100 will be false, so execution of the loop is terminated. At this point program execution continues from the next instruction after the end of the loop (in this case there are none, so it stops).


A further example might be in a computer game, where the speed of a car is increased all the time the accelerator pedal is pressed down until you hit its maximum speed.

dim maxSpeed as integer = 120
dim speedNow as integer = 0
dim pedalDown as boolean = True

While speedNow < maxSpeed And pedalDown
   console.writeline(speedNow)
   speedNow = speedNow + 1
End While
console.writeline("MAXSPEED!")
  Blank.svg Code Output

0
1
2
3
...
119
MAXSPEED!

 

 

Loops - Q&A + Answers below

Scroll down for the answers power point




Loops - Q and A

More Loops - Create a Booking System

Loops - and White Box Testing

And more test

Loops and 2d Arrays

Loops Challenges