Sie sind auf Seite 1von 3

Iteration - Condition

Controlled
Iteration is the process of repeating a process over and over. Often in
programming you need to repeat a block of code several times.

WHILE Loops
A while loop is known as a condition controlled loop, you should use it
when you do not know how many times the code needs to repeat as
you can say repeat while a condition is True.

Dim userentry As String = "y"

While userentry <> "n"

userentry = InputBox("Play again? y/n")

End While

MessageBox.Show("Game over")

This is what happens when the button is clicked:


How the while loop works

 there is a condition after the word while, it works like


an if condition. while the variable userentry is not equal
to n the code inside the loop (that is indented) will repeat
 when n is entered by the user, the loop will end and it will
continue with the code after the loop. In this case it will display a
message box saying “Game Over”.

Example Program 1 - Guess the


Number
This program asks the user to guess the number, it will keep asking
them to guess the number until they guess it correctly. Once they
have guessed it correctly it will tell them how many attempts it took.
Code when btnGuess is clicked

Dim answer As Integer = 15


Dim attempts As Integer = 0

Dim userentry As String = ""

'a loop that repeats while the users guess is not the same as the answer

While answer.ToString <> userentry

userentry = InputBox("Enter a number between 1 and 20")

'each time through the loop 1 is added to the number of attempts

attempts = attempts + 1

End While

'after the loop it will say how many attempts it took

MessageBox.Show("Well done you correctly guessed the number, it took you " &
attempts.ToString & " attempts")

This is what happens when the button is clicked:

Das könnte Ihnen auch gefallen