# title=Fundamentals of Programming: Iteration

 ← Selection Iteration Arithmetic operations →

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
```

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 How many lines will be printed by this while loop? What value will be stored in the variable count immediately after the loop has finished executing? 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: 101 lines, starting with the line numbered 0, and ending with the line numbered 100. count will contain the value 101 upon exiting the loop. 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!")
```

 Exercise: While Loops Write a program that counts from 20 to 60 inclusive like so: Answer: ```dim count as integer = 20 While count <= 60 console.writeline(count) count = count + 1 End While ``` Write a program that takes an input and outputs the times table for that number: insert a number: 7 1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49 8 * 7 = 56 9 * 7 = 63 10 * 7 = 70 Answer: ```dim count as integer = 1 dim times as integer console.write("insert a number: ") times = console.readline() While count <= 10 console.writeline(count & " * " & times & " = " & count * times) count = count + 1 End While ``` Write a program that adds all the numbers from 10 to 20 inclusive together and finally outputs the result Answer: ```dim count as integer = 10 dim total as integer = 0 While count <= 20 total = total + count count = count + 1 End While console.writeline("the total is: " & total) ```

## While Do

The while loop: For example:

```While not top speed Do
increase speed
End
```
```dim speed as integer = 0
While speed < 120
console.writeline(speed)
speed = speed + 1
End While
```

## Do While Loop

Another type of while loop is a Do-While loop. This is slightly different from the While loop in that you perform the task before you check that you have to perform the task again. This means you perform the task whatever the circumstances of the check:

```Do
increase speed
While not top speed
End
```

Visual Basic handles this with some slight syntax differences

```console.write("how old are you?")
Do
console.writeline(age & " year olds should attend school!")
age = age + 1
Loop Until age > 17
console.writeline(age & " is too old to attend school!")
```

This is great for young students:

how old are you? 15
15 year olds should attend school!
16 year olds should attend school!
17 is too old to attend school!

But we run into a problem when we have a 78 year old:

78 year olds should attend school!
78 is too old to attend school!

 Exercise: Do While and While Do For the dodgy example above re-write the Do While as a While Do loop Answer: ```console.write("how old are you?") age = console.readline() While age < 17 console.writeline(age & " year olds should attend school!") age = age + 1 End While console.writeline(age & " is too old to attend school!") ```

Be careful when you use each loop!

## For Loop

The most complicated tool you may meet is the for loop. This is a glorified While loop and don't be put off by how complicated it looks. It also tends to be one of the easiest ways to iterate in Visual Basic

```For (speed = 0, not top speed, increase speed)
drive
```

It is far easier to use in vb

```For speed = 0 to 120
drive()
Loop
```

For loops also allow you to count downwards. For example if you creating a timer that counts down to a target. To do this we use the `step - 1` code, making the following code:

```For x = 10 To 1 Step -1
Console.Write(x & ",")
Next
console.writeline("Test over!")
```

display:

10,9,8,7,6,5,4,3,2,1,Test over!

 Exercise: For loops Write a for loop to display the words "I will eat my greens" 40 times: Answer: ```for x = 1 to 40 console.writeline("I will eat my greens") next ``` Write code that will input a lower and higher number, then write the numbers on the screen, starting at the lower and writing each number until you reach the higher. Use a for loop, it should display the following: insert lower number: 10 insert higher number: 13 10 11 12 13 Answer: ```dim lower, higher as integer console.write("insert lower number: ") lower = console.readline() console.write("insert higher number: ") higher = console.readline() For x = lower to higher console.writeline(x) Next ``` Write a for loop that will output the frequencies: 100,200,300,400, ... , 20000. HINT, you might want to start at 1 and multiply. Remember `console.beep(200, 200)` Answer: ```For x = 1 to 200 console.beep(x* 100, 100) Next ``` Get the computer to keep asking a user whether they are "Ready to launch?". If they say anything other than "Yes", then keep asking the question. If they say yes, then count down from 5 and end with the words "BLAST OFF!". Ready to launch? No Ready to launch? Not yet Ready to launch? Yes 5 4 3 2 1 BLAST OFF! Extension: If you want to really show that you know how to use case statements, get it to say: FIVE, FOUR, THREE, TWO, ONE instead of showing the numbers Answer: ```Dim answer As String Do Console.Write("Ready to launch? ") answer = Console.ReadLine() Loop While answer <> "Yes" For x = 5 To 1 Step -1 Console.WriteLine(x) Next Console.Write("BLAST OFF!") ```

You have met the three main sorts of iteration that you can use, some being more suited for solving certain problems than others:

• While Do
• Do While
• For

## Loopy Loops (Nested Loop)

Some times it might be a good idea to combine several loops together. Take a look at this example

```For x = 1 to 10
console.writeline(x & " : ")
for y = 0 to 10
console.writeline(x & " * " & y & " = " & x * y)
Next
Next
```

This code uses a loop inside a loop to print out the times tables. All that time you spent learning them at school can be rewritten in six lines of code!

1 :
1 * 0 = 0
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
2 :
2 * 0 = 0
...

 Exercise: Loopy loops Write a for loop inside a loop to display a Christmas Tree, like so: Answer: ```For x = 1 to 5 For y = 1 to x Console.Write("\") Next Console.WriteLine() Next ``` Adjust the code above so that the user inputs how high the tree is Answer: ```dim h as integer console.writeline("please insert a height") h = console.readline() For x = 1 to h For y = 1 to x Console.Write("\") Next Console.WriteLine() Next ```