Fundamentals of Programming: Iteration

From Wikibooks, open books for an open world
Jump to: navigation, search

UNIT 1 - ⇑ Fundamentals of Programming ⇑

← Selection Iteration Built-in functions →


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
Down arrow Hexagonal Icon.svg

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


A computer game example would be increasing the speed of a car while the accelerator is pressed down and until you hit its top speed.

dim maxSpeed as integer = 120
dim curSpeed as integer = 0
dim pedalPress as boolean = True
 
While curSpeed <= maxSpeed And pedalPress = True
   console.writeline(curSpeed)
   curSpeed = curSpeed + 1
End While
console.writeline("MAXSPEED!")
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

0
1
2
3
...
120
MAXSPEED!


Exercise: While Loops
Write a program that counts from 20 to 60 inclusive like so:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

20
21
22
...
60

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:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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[edit]

While-loop-diagram.svg

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
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

0
1
...
118
119

Do While Loop[edit]

Do-while-loop-diagram.svg

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?")
age = console.readline()
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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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[edit]

CPT-Programming-FOR-Loop.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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!".

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

Click here to learn more

Loopy Loops[edit]

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!

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

\
\\
\\\
\\\\
\\\\\

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