Loops and strings

Repeat work with counted and conditional loops, then extract pieces of text.

Add up a range

FOR advances the counter by one each time and includes the upper bound. Initialise the running total to zero before the first iteration.

    total = 0
    FOR i = 1 TO 5
      total += i
    NEXT
    CRT total

Expected output is 15.

Repeat while a condition holds

LOOP can stop when a condition is met. With WHILE at the top, jBC checks the condition before running the body. This example counts how many doublings take 3 past 20.

    amount = 3
    steps = 0
    LOOP WHILE amount LE 20 DO
      amount *= 2
      steps += 1
    REPEAT
    CRT 'Steps: ' : steps : ', amount: ' : amount

Expected output is Steps: 3, amount: 24.

Extract part of a string

Use text[start, length] to take a substring. Positions start at 1, so the digits in this code start at position 4.

    order_code = 'ORD4821'
    order_number = order_code[4, 4]
    CRT order_number

Expected output is 4821.

Split and count delimited text

FIELD extracts one part by position. DCOUNT counts the parts, so a single item without any delimiter counts as one.

    colours = 'red|green|blue'
    second_colour = FIELD(colours, '|', 2)
    colour_count = DCOUNT(colours, '|')
    CRT second_colour : ' of ' : colour_count

Expected output is green of 3.