170 likes | 324 Views
Loop de Loop Going around and around and around. VB12. Sometimes you want to do the same thing over and over. If not too drunk then Get a pint If not too drunk then Get a pint If not too drunk then Get a pint If not too drunk then Get a pint.
E N D
Sometimes you want to do the same thing over and over If not too drunk then Get a pint If not too drunk then Get a pint If not too drunk then Get a pint If not too drunk then Get a pint VB12
Computer programs use loops to do things over and over Do until (drunk) Get a pint Loop VB12
Do … Until … Loop Semantics • The Do Until Loop loops around and around and keeps going until some condition is TRUE Do Until blnTankFull Add Petrol Loop VB12
Do … While … Loop Semantics • The Do While Loop loops around and around and keeps going as long as some condition is TRUE Do While blnHungry Eat Loop VB12
VB uses 3 kinds of loops • Do Until Loop • Do While Loop • For Loop VB12
Do While Loop Do While(Boolean expression) One or more VB statements Loop Boolean expression is evaluated before each iteration and the code is executed if the expression is true VB12
Do Until Loop Do Until(Boolean expression) One or more VB statements Loop Boolean expression is evaluated before each iteration and the code is executed if the expression is false VB12
Often we need a loop to count something each iteration To make 10 cups of coffee Cups = 0 Do until (cups = 10) Make a cup of coffee cups = cups + 1 Loop VB12
For Loops can count VB12
For Loops can count for us To make 10 cups of coffee For cup = 1 to 10 Make a cup of coffee Next cup VB12
For Loop ForintCounter=intStarttointEnd One or more VB statements NextintCounter For loop starts with intCounter set to intStart. After each iteration the value of intCounter is incremented. The iteration when intCounter = intEnd is the last one. VB12
Compound Interest Calculator curPrincipal = 2000 intTime = 5 sngRate = 3.5 For years = 1 to intTime curTotal = curPrincipal * (1 + sngRate / 100) curPrincipal = curTotal Next Years VB12
Loops conditions cant be checked at the bottom • The While and Until loops we looked at check the condition at the top • They can also check at the bottom VB12
Do …Loop Until Do Get a pint Loop Until (Drunk) VB12
Do …Loop While Do Eat Loop While (Hungry) VB12
N! = N*(n-1)*(n-2) … 2 * 1 5! = 1 * 2 * 3 * 4 * 5 lngFactorial = 1 For x = 1 to n lngFactorial = lngFactorial * n Next x Factorial VB12