Loops

HotShoe

Well-Known Member
Licensed User
Loops are a fundamental part of programming languages. Without them, we couldn't look through an array or list or database easily.

Strings for example are an array of characters, so to find a given character at a particular position, we use a loop. There are 3 basic types of loops, the For loop, the While loop and the Until loop. Most languages support all 3, but almost all implement them a little differently. Below we'll look at each type of loop and how they work.


The For loop

This is the workhorse of computer programming. It is the type of loop you will use most often for quick and dirty stuff. It defines a control variable (a counter) to determine the range that the loop will deal with and when it will stop.

B4X:
For i = 0 to txt.length -1
...execution code here
Next
This For loop checks each character in the string txt. It might be looking for spaces or it might take a range of characters and build a new string result (a substring). What it does is not as important as how it does it.

In the example above, i is the control variable, and will default to being an integer if it is not already defined in a Dim statement. That's right, you don't have to Dim i before you can use it in a For loop in B4X. The parser and compiler will do that for you.

So, i is created as an integer for you, and then it is assigned the value of 0. As long as i is less than the length of the string minus 1, the loop will repeat each time it finds the Next keyword. The reason we use the .length -1 as the loop limit is because B4X begins index numbers at 0 and not 1.

For example the string "Jem Miller" has a length of 10 characters, but the J is at position 0, so the last r is at position 9 and not 10. This is because of the way computer languages count, not all languages, but most are zero based.

If we did this:

B4X:
For i = 0 to txt.length
...execution code here
Next
The loop would raise an error when i = 10 because it is trying to read past the end of the string and no memory has been allocated for that location. Remember that strings are arrays and have to be a defined length. When you created the string "Jem Miller" B4X created a character array with the length of 10 characters, beginning at position 0 and ranging to position 9 (10 locations).

Since we don't think in base 0, it can sometimes be confusing to try to find an error such as this in your app.

Also notice that you don't ever increment or modify the control variable in a For loop, it gets incremented automatically by the loop each time the Next keyword is found.

Sometimes you want to get out of a loop while it is running if some condition is met. For that we would use the Exit keyword inside the loop:

B4X:
For I = 0 to txt.length - 1
If txt.CharAt(I) = "i" then Exit
... other code here
Next
You can also skip code inside of a For loop using the Continue keyword. When Continue is seen in the execution code, the loop aborts the code and jumps to the Next statement at the end of the loop. The loop will still continue running, but your control variable will be incremented and the loop will continue on from there.

The For-Next Step operator (Added 09-04-2015)

For loops can have a Step operator added to tell the loop how many locations to step by while counting array positions. This is very handy in some situations since you can count forwards or backwards using Step.

B4X:
For a = 1 to txt.length - 1 Step 2
... execution code here
Next
The above loop will step through each location of the array by 2 spaces in each iteration instead of the default of 1. You can also cause the loop to count backwards (from the end to the front of the array).

B4X:
For a = txt.length-1 to 0 Step - 1
... execution code here
Next
The above will count from the end of the txt string to the beginning one location at a time.

Loops can be VERY long, or elegantly short. It all depends on the needs of the routine that you are writing. You can do virtually anything inside a loop that you can do anywhere else in your program including calling methods from external libraries or other activities or modules. In a For loop it is VERY important that you do NOT modify the control variable inside of the loop. In this case the variable i. Doing so will cause unpredictable results and will almost certainly cause an eventual crash of your app.


The For-Each loop (added 09-02-15 due to brain fade)

The For-Each loop brings more power to the standard For loop. It allows iteration of array elements in a more compact and easier way than the For loop.

B4X:
Dim txt as String = "Jem Miller"
Dim ret as String

For Each i as Int in txt
ret = txt.CharAt(i)

if ret = "l" then Exit
Next
The For Each defines a control variable, in this case an Int, and a collection or array to work with in the loop. Then it iterates through the loop until a condition in the execution code is met or the length of the collection has been reached. The loop structure automatically increments the control character to the next member of the array.

You can potentially do all sorts of things with a For-Each loop including resizing elements in your activity or changing text sizes, etc. It is a powerful addition to your tool box.


The While loop

A While loop does something as long as a given condition is met.

B4X:
Dim i As Int = 0
Do While i < 10
... execution code here
i = i + 1
Loop
The above loop will continue to execute until i equals 10 then it will terminate itself. Notice that the While loop does NOT define i for you, your control statement must have all variables declared (Dim'ed) before use. You also have to increment any control variable yourself such as i = i + 1 above. Also note that once i = 10 the loop will end, so it will NOT go through the loop again once i equals 10. So the entire loop will effectively stop being useful when i equals 10.

Don't forget to initialize your control variable(s) to the values you wish BEFORE the loop begins. This is because the While loop evaluates the control statement before each iteration of the loop. You can use the Exit keyword to bail out of all loops.


The Until loop

The Until loop does something until a given condition is met. This differs very slightly from the While loop in that the control statement differs a bit.

B4X:
Dim I as int = 0

Do Until I > 9
… execution code here
I = I + 1
Loop
Instead of defining what needs to happen to keep the loop running like a While loop, you must define what needs to happen to stop the loop.

In the example above, the loop will terminate when I is greater than 9. Now this is the same basic behavior that we saw in the While loop above, but the control statement is different.

Instead of doing something WHILE a set of conditions are true, this type of loop does something UNTIL a set of conditions is true. In other languages the until loop will always run at least once, but that is not the case in B4X. It is just another tool in the box.


Complexity

While and Until loops can take more complex control statements to guide their behavior.

B4X:
Dim I As Int
Dim st As String = “This is a test”
Dim ret as string

I = 0

Do While (I < st.Length) AND (ret <> ”a”)
ret = st.CharAt(I)

I = I + 1
Loop
This is still a very simple loop, but the control statement(s) are more complex.


Summary

All of the loop types can do a particular job, but some are better than others in terms of ease of use and code accuracy.

The While and Until loops can take complex condition statements to define their execution, while the For loop is a simpler structure of control.

All can use the Exit keyword to exit the current loop, and all can be embedded inside of other loops, just be sure to keep your control variables straight between the different loops.

This lesson on loops is not meant to prefer one method over the other, but to try to show the capabilities and differences of each.

--- Jem
 
Last edited:

Enrique Gonzalez R

Well-Known Member
Licensed User
The For Each loop

Sometimes you want to iterate on non basic variables or skip indexes and work directly with the variable within the loop in those cases you use a For Each Loop

B4X:
For Each view As Node In MainForm.RootPane.GetAllViewsRecursive
  
.... loops through every node in the mainform (B4J)

Next
this is the same as writing:

B4X:
For i = 0 To MainForm.RootPane.NumberOfNodes - 1

.... loops through every node in the mainform (B4J)

Next
Both are Okey to use.
 

sorex

Expert
Licensed User
Shoe,

you could add additional info about the stepper aswell which comes in handy sooner or later.

B4X:
for x=0 to 10 step 2

for x=10 to 0 step -2
 
Top