ProtoLang.net

Reference: While

☰ Hide Sidebar
TOKEN WHILE
ALIAS None

The While token is used to repeatedly execute a block of long code as a specified condition remains True. The loop checks the condition before each iteration, and continues executing the code block until the condition becomes False. While loops are essential for tasks that need to repeat an unknown number of times based on changing conditions.

Syntax

The short syntax structure uses the word WHILE:

WHILE CONDITION
    STATEMENTS
END WHILE

The long syntax structure uses the word WHILE:

WHILE CONDITION
    STATEMENTS
END WHILE

How While Loops Work

A While loop follows this execution pattern:

  1. The condition is evaluated before each iteration
  2. If the condition is True, the code block executes
  3. After the code block completes, the loop returns to step 1
  4. If the condition is False, the loop ends and execution continues after END WHILE

Example: Basic While Loop Execution

NEW INT counter = 1
WHILE counter <= 3
    PRINTLN "Iteration: " .. counter
    SET counter = counter + 1
END WHILE
PRINTLN "Loop finished"
// Displays: Iteration: 1, Iteration: 2, Iteration: 3, Loop finished

Basic While Loops

Example: Simple Counter Loop

NEW INT i = 1
WHILE i <= 5
    PRINTLN i
    SET i = i + 1
END WHILE
// Displays: 1, 2, 3, 4, 5

Example: Countdown Loop

NEW INT countdown = 5
WHILE countdown > 0
    PRINTLN "T-minus " .. countdown
    SET countdown = countdown - 1
END WHILE
PRINTLN "Liftoff!"
// Displays: T-minus 5, T-minus 4, T-minus 3, T-minus 2, T-minus 1, Liftoff!

Example: Loop Until Condition

NEW INT value = 2
WHILE value < 100
    PRINTLN value
    SET value = value * 2
END WHILE
// Displays: 2, 4, 8, 16, 32, 64

Loop Conditions

The condition in a While loop can be any Expression that evaluates to a Boolean value.

Example: Using Comparison Operators

NEW INT x = 10
WHILE x >= 1
    PRINT x .. " "
    SET x = x - 1
END WHILE
// Displays: 10 9 8 7 6 5 4 3 2 1

Example: Using Boolean Variables

NEW BOOL keepGoing = TRUE
NEW INT count = 0
WHILE keepGoing
    SET count = count + 1
    PRINTLN "Count: " .. count
    IF count >= 3
        SET keepGoing = FALSE
    END IF
END WHILE
// Displays: Count: 1, Count: 2, Count: 3

Example: Using Equality Checks

NEW STR status = "running"
NEW INT i = 0
WHILE status == "running"
    SET i = i + 1
    PRINTLN "Processing: " .. i
    IF i == 3
        SET status = "complete"
    END IF
END WHILE
PRINTLN "Status: " .. status
// Displays: Processing: 1, Processing: 2, Processing: 3, Status: complete

Example: Using Inequality Checks

NEW INT current = 1
NEW INT target = 5
WHILE current != target
    PRINTLN "Not there yet: " .. current
    SET current = current + 1
END WHILE
PRINTLN "Reached target: " .. target
// Displays: Not there yet: 1, Not there yet: 2, Not there yet: 3, Not there yet: 4, Reached target: 5

Complex Conditions

While loop conditions can use Logical Operators to combine multiple checks.

Example: Using And Operator

NEW INT x = 1
NEW BOOL keepRunning = TRUE
WHILE ( x <= 10 ) && keepRunning
    PRINTLN "x = " .. x
    SET x = x + 1
    IF x == 5
        SET keepRunning = FALSE
    END IF
END WHILE
// Displays: x = 1, x = 2, x = 3, x = 4

Example: Using Or Operator

NEW INT attempts = 0
NEW BOOL success = FALSE
WHILE ( attempts < 5 ) || ( success == FALSE )
    SET attempts = attempts + 1
    PRINTLN "Attempt: " .. attempts
    IF attempts == 3
        SET success = TRUE
        BREAK
    END IF
END WHILE
// Displays: Attempt: 1, Attempt: 2, Attempt: 3

Example: Multiple Conditions

NEW INT temp = 70
NEW INT pressure = 30
WHILE ( temp < 100 ) && ( pressure < 50 )
    PRINTLN "Temp: " .. temp .. ", Pressure: " .. pressure
    SET temp = temp + 10
    SET pressure = pressure + 5
END WHILE
PRINTLN "Limits reached"
// Displays temperature and pressure readings until limits

Accumulator Patterns

While loops are commonly used to accumulate values over multiple iterations.

Example: Sum Accumulator

NEW INT i = 1
NEW INT sum = 0
WHILE i <= 10
    SET sum = sum + i
    SET i = i + 1
END WHILE
PRINTLN "Sum: " .. sum // Displays "Sum: 55"

Example: Product Accumulator

NEW INT i = 1
NEW INT product = 1
WHILE i <= 5
    SET product = product * i
    SET i = i + 1
END WHILE
PRINTLN "Factorial of 5: " .. product // Displays "Factorial of 5: 120"

Example: String Accumulator

NEW INT counter = 1
NEW STR result = ""
WHILE counter <= 5
    SET result = result .. counter .. " "
    SET counter = counter + 1
END WHILE
PRINTLN result // Displays "1 2 3 4 5 "

Example: Counting Specific Values

NEW INT i = 1
NEW INT evenCount = 0
WHILE i <= 20
    IF i % 2 == 0
        SET evenCount = evenCount + 1
    END IF
    SET i = i + 1
END WHILE
PRINTLN "Even numbers: " .. evenCount // Displays "Even numbers: 10"

Nested While Loops

While loops can be nested inside other While loops to create multi-level iterations.

Example: Multiplication Table

NEW INT i = 1
NEW INT j = 1
WHILE i <= 3
    SET j = 1
    WHILE j <= 3
        PRINT i * j .. " "
        SET j = j + 1
    END WHILE
    PRINTLN ""
    SET i = i + 1
END WHILE
// Displays:
// 1 2 3
// 2 4 6
// 3 6 9

Example: Nested Counting

NEW INT outer = 1
NEW INT inner = 1
WHILE outer <= 3
    PRINTLN "Outer: " .. outer
    SET inner = 1
    WHILE inner <= 2
        PRINTLN "  Inner: " .. inner
        SET inner = inner + 1
    END WHILE
    SET outer = outer + 1
END WHILE
// Displays outer and inner loop iterations

Example: Grid Processing

NEW INT row = 1
NEW INT col = 1
WHILE row <= 3
    SET col = 1
    WHILE col <= 3
        PRINT "(" .. row .. "," .. col .. ") "
        SET col = col + 1
    END WHILE
    PRINTLN ""
    SET row = row + 1
END WHILE
// Displays: (1,1) (1,2) (1,3)
//           (2,1) (2,2) (2,3)
//           (3,1) (3,2) (3,3)

Using Break in While Loops

The Break command immediately exits the loop, regardless of the condition.

Example: Early Exit with Break

NEW INT i = 1
WHILE i <= 10
    IF i == 5
        PRINTLN "Breaking at " .. i
        BREAK
    END IF
    PRINTLN i
    SET i = i + 1
END WHILE
PRINTLN "Loop ended"
// Displays: 1, 2, 3, 4, Breaking at 5, Loop ended

Example: Search and Stop

NEW INT i = 1
NEW BOOL found = FALSE
WHILE i <= 100
    IF i == 42
        SET found = TRUE
        PRINTLN "Found the answer: " .. i
        BREAK
    END IF
    SET i = i + 1
END WHILE
IF found == FALSE
    PRINTLN "Not found"
END IF
// Displays: Found the answer: 42

Example: Error Detection

NEW INT count = 0
NEW BOOL errorOccurred = FALSE
WHILE count < 10
    SET count = count + 1
    PRINTLN "Processing item " .. count
    IF count == 7
        PRINTLN "Error detected!"
        SET errorOccurred = TRUE
        BREAK
    END IF
END WHILE
IF errorOccurred == TRUE
    PRINTLN "Process stopped due to error"
ELSE
    PRINTLN "Process completed successfully"
END IF

Using Continue in While Loops

The Continue command skips the rest of the current iteration and moves to the next one.

Example: Skipping Values with Continue

NEW INT i = 0
WHILE i < 10
    SET i = i + 1
    IF i % 2 == 0
        CONTINUE
    END IF
    PRINTLN i
END WHILE
// Displays: 1, 3, 5, 7, 9 (skips even numbers)

Example: Processing Valid Items Only

NEW INT i = 1
WHILE i <= 10
    IF i == 5
        CONTINUE
    END IF
    PRINTLN "Processing: " .. i
    SET i = i + 1
END WHILE
// Displays all numbers except 5

Example: Filtering with Continue

NEW INT num = 1
NEW INT sum = 0
WHILE num <= 20
    IF num % 3 == 0
        SET num = num + 1
        CONTINUE
    END IF
    SET sum = sum + num
    SET num = num + 1
END WHILE
PRINTLN "Sum (excluding multiples of 3): " .. sum

Infinite Loops and Control

A While loop with a condition that never becomes False will run forever unless explicitly stopped with Break.

Example: Controlled Infinite Loop

NEW INT count = 0
WHILE TRUE
    SET count = count + 1
    PRINTLN "Iteration: " .. count
    IF count >= 5
        PRINTLN "Stopping loop"
        BREAK
    END IF
END WHILE
// Displays: Iteration: 1, Iteration: 2, Iteration: 3, Iteration: 4, Iteration: 5, Stopping loop

Example: Menu Loop

NEW BOOL running = TRUE
NEW INT choice = 0
WHILE running
    SET choice = choice + 1
    IF choice == 1
        PRINTLN "Option 1 selected"
    ELIF choice == 2
        PRINTLN "Option 2 selected"
    ELIF choice == 3
        PRINTLN "Exiting menu"
        SET running = FALSE
    END IF
END WHILE
// Displays: Option 1 selected, Option 2 selected, Exiting menu

Practical Applications

Example: Number Guessing Pattern

NEW INT guess = 1
NEW INT target = 7
NEW INT attempts = 0
WHILE guess != target
    SET attempts = attempts + 1
    PRINTLN "Guess " .. attempts .. ": " .. guess
    IF guess < target
        PRINTLN "Too low!"
    ELSE
        PRINTLN "Too high!"
    END IF
    SET guess = guess + 1
END WHILE
PRINTLN "Correct! Found " .. target .. " in " .. attempts .. " attempts"

Example: Fibonacci Sequence

NEW INT a = 0
NEW INT b = 1
NEW INT temp = 0
NEW INT count = 1
WHILE count <= 10
    PRINTLN a
    SET temp = a
    SET a = b
    SET b = temp + b
    SET count = count + 1
END WHILE
// Displays first 10 Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Example: Deposit and Withdrawal Simulation

NEW FLOAT balance = 100.0
NEW INT day = 1
WHILE day <= 5
    PRINTLN "Day " .. day .. " - Balance: $" .. balance
    IF day % 2 == 0
        SET balance = balance + 50.0
        PRINTLN "  Deposited $50.0"
    ELSE
        SET balance = balance - 20.0
        PRINTLN "  Withdrew $20.0"
    END IF
    SET day = day + 1
END WHILE
PRINTLN "Final balance: $" .. balance

Example: Temperature Monitoring

NEW INT temp = 60
NEW INT hour = 1
WHILE hour <= 12
    PRINTLN "Hour " .. hour .. ": " .. temp .. "F"
    IF temp < 72
        SET temp = temp + 3
        PRINTLN "  Heating..."
    ELIF temp > 76
        SET temp = temp - 3
        PRINTLN "  Cooling..."
    ELSE
        PRINTLN "  Optimal temperature"
    END IF
    SET hour = hour + 1
END WHILE

Example: Inventory Depletion

NEW INT stock = 100
NEW INT sold = 0
NEW INT sale = 15
WHILE stock > 0
    IF stock < sale
        SET sale = stock
    END IF
    SET stock = stock - sale
    SET sold = sold + sale
    PRINTLN "Sold " .. sale .. " units. Stock remaining: " .. stock
END WHILE
PRINTLN "Total sold: " .. sold

Example: Interest Calculation

NEW FLOAT principal = 1000.0
NEW FLOAT rate = 0.05
NEW INT years = 0
WHILE principal < 2000.0
    SET years = years + 1
    SET principal = principal + ( principal * rate )
    PRINTLN "Year " .. years .. ": $" .. principal
END WHILE
PRINTLN "Doubled in " .. years .. " years"

Example: Countdown Timer with Warnings

NEW INT seconds = 10
WHILE seconds > 0
    IF seconds <= 3
        PRINTLN "WARNING: " .. seconds .. " seconds remaining!"
    ELSE
        PRINTLN seconds .. " seconds"
    END IF
    SET seconds = seconds - 1
END WHILE
PRINTLN "Time's up!"

Example: Score Tracking System

NEW INT score = 0
NEW INT level = 1
WHILE level <= 5
    PRINTLN "Level " .. level
    SET score = score + ( level * 10 )
    PRINTLN "Score: " .. score
    IF score >= 100
        PRINTLN "Achievement unlocked!"
        BREAK
    END IF
    SET level = level + 1
END WHILE
PRINTLN "Final score: " .. score

Validating Loop Progression

It's important to ensure the loop condition will eventually become False to prevent infinite loops.

Example: Proper Loop Variable Update

NEW INT i = 1
WHILE i <= 5
    PRINTLN i
    SET i = i + 1 // CRITICAL: Without this, loop runs forever!
END WHILE
// Displays: 1, 2, 3, 4, 5

Example: Condition That Changes

NEW INT value = 1
WHILE value < 100
    PRINTLN value
    SET value = value * 2 // Value doubles, eventually exceeds 100
END WHILE
// Displays: 1, 2, 4, 8, 16, 32, 64

Example: Boolean Flag Pattern

NEW BOOL searching = TRUE
NEW INT i = 1
WHILE searching
    PRINTLN "Searching... " .. i
    SET i = i + 1
    IF i > 5
        SET searching = FALSE // Eventually becomes False
    END IF
END WHILE
PRINTLN "Search complete"

While Loops with Different Data Types

Example: Float Counter

NEW FLOAT x = 0.0
WHILE x < 1.0
    PRINTLN x
    SET x = x + 0.2
END WHILE
// Displays: 0.0, 0.2, 0.4, 0.6, 0.8

Example: String Status Check

NEW STR status = "pending"
NEW INT count = 0
WHILE status != "complete"
    SET count = count + 1
    PRINTLN "Status: " .. status .. " (check " .. count .. ")"
    IF count == 3
        SET status = "complete"
    END IF
END WHILE
PRINTLN "Process finished"

Example: Boolean State Machine

NEW BOOL isActive = TRUE
NEW INT iterations = 0
WHILE isActive
    SET iterations = iterations + 1
    PRINTLN "Active iteration: " .. iterations
    IF iterations >= 4
        SET isActive = FALSE
    END IF
END WHILE
PRINTLN "Deactivated after " .. iterations .. " iterations"

Comparing While Loop Patterns

Example: Count Up vs Count Down

// Count up
NEW INT up = 1
PRINTLN "Counting up:"
WHILE up <= 5
    PRINT up .. " "
    SET up = up + 1
END WHILE
PRINTLN ""

// Count down
NEW INT down = 5
PRINTLN "Counting down:"
WHILE down >= 1
    PRINT down .. " "
    SET down = down - 1
END WHILE
// Displays: Counting up: 1 2 3 4 5
//           Counting down: 5 4 3 2 1

Example: Increment by Different Amounts

NEW INT byOne = 0
PRINTLN "By 1:"
WHILE byOne < 5
    SET byOne = byOne + 1
    PRINT byOne .. " "
END WHILE
PRINTLN ""

NEW INT byTwo = 0
PRINTLN "By 2:"
WHILE byTwo < 10
    SET byTwo = byTwo + 2
    PRINT byTwo .. " "
END WHILE
// Displays: By 1: 1 2 3 4 5
//           By 2: 2 4 6 8 10

Zero-Iteration Loops

If the condition is False from the start, the loop body never executes.

Example: Condition False Initially

NEW INT x = 10
WHILE x < 5
    PRINTLN "This never prints"
    SET x = x + 1
END WHILE
PRINTLN "Loop skipped entirely"
// Displays: Loop skipped entirely

Example: Guarding Against Empty Loops

NEW INT count = 0
WHILE count > 0
    PRINTLN "Processing"
    SET count = count - 1
END WHILE
PRINTLN "Nothing to process"
// Displays: Nothing to process

Important Notes

  • The condition is checked before each iteration, including the first.
  • If the condition is False initially, the loop body never executes.
  • The loop variable(s) must be modified inside the loop to eventually make the condition False.
  • Use Break to exit the loop early.
  • Use Continue to skip to the next iteration.
  • The condition can use any Comparison or Logical operators.
  • While loops are ideal when the number of iterations is not known in advance.
  • Always ensure the loop has a way to terminate to avoid infinite loops.

Common Errors

Error: Infinite Loop - Condition Never Changes

NEW INT x = 1
WHILE x < 10
    PRINTLN x
    // ERROR! x is never modified, loop runs forever!
END WHILE
// Correct: Update the loop variable
NEW INT y = 1
WHILE y < 10
    PRINTLN y
    SET y = y + 1 // Loop will eventually end
END WHILE

Error: Infinite Loop - Wrong Direction

NEW INT count = 10
WHILE count > 0
    PRINTLN count
    SET count = count + 1 // ERROR! count increases, never reaches 0!
END WHILE
// Correct: Decrement when counting down
NEW INT counter = 10
WHILE counter > 0
    PRINTLN counter
    SET counter = counter - 1 // Correct direction
END WHILE

Error: Using Assignment Instead of Comparison

NEW INT x = 5
WHILE x = 10 // Syntax error! Use == for comparison
    PRINTLN x
    SET x = x + 1
END WHILE
// Correct: Use comparison operator
WHILE x == 10
    PRINTLN x
    SET x = x + 1
END WHILE

Error: Forgetting to Update Counter in Nested Loop

NEW INT i = 1
WHILE i <= 3
    NEW INT j = 1
    WHILE j <= 3
        PRINTLN i .. "," .. j
        // ERROR! j is never incremented
    END WHILE
    SET i = i + 1
END WHILE
// Correct: Update both loop variables
NEW INT a = 1
WHILE a <= 3
    NEW INT b = 1
    WHILE b <= 3
        PRINTLN a .. "," .. b
        SET b = b + 1 // Correct
    END WHILE
    SET a = a + 1
END WHILE

Error: Wrong Comparison Operator

NEW INT i = 1
WHILE i < 5
    PRINTLN i
    SET i = i + 1
END WHILE
// Displays: 1, 2, 3, 4 (stops before 5)

// If you want to include 5:
NEW INT j = 1
WHILE j <= 5
    PRINTLN j
    SET j = j + 1
END WHILE
// Displays: 1, 2, 3, 4, 5

Error: Modifying Loop Variable Incorrectly

NEW INT x = 1
WHILE x <= 5
    PRINTLN x
    SET x = 1 // ERROR! x always resets to 1, infinite loop!
END WHILE
// Correct: Increment properly
NEW INT y = 1
WHILE y <= 5
    PRINTLN y
    SET y = y + 1 // Correct
END WHILE

Error: Using Non-Boolean Condition

NEW INT x = 5
WHILE x // Type error! Condition must be Boolean
    PRINTLN x
    SET x = x - 1
END WHILE
// Correct: Use comparison to create Boolean
WHILE x > 0
    PRINTLN x
    SET x = x - 1
END WHILE

Error: Off-by-One Error

// Want to loop 5 times but only loops 4 times
NEW INT count = 1
WHILE count < 5
    PRINTLN count
    SET count = count + 1
END WHILE
// Displays: 1, 2, 3, 4

// Correct for 5 iterations:
NEW INT counter = 1
WHILE counter <= 5
    PRINTLN counter
    SET counter = counter + 1
END WHILE
// Displays: 1, 2, 3, 4, 5

Error: Variable Scope Confusion

WHILE TRUE
    NEW INT x = 0 // ERROR! x is recreated each iteration
    SET x = x + 1
    PRINTLN x // Always prints 1
    IF x >= 5
        BREAK
    END IF
END WHILE
// Correct: Declare variable outside loop
NEW INT y = 0
WHILE TRUE
    SET y = y + 1
    PRINTLN y
    IF y >= 5
        BREAK
    END IF
END WHILE

Error: Continue Without Updating Counter

NEW INT i = 0
WHILE i < 10
    IF i % 2 == 0
        CONTINUE // ERROR! i never increments when even
    END IF
    PRINTLN i
    SET i = i + 1
END WHILE
// Correct: Update counter before continue
NEW INT j = 0
WHILE j < 10
    SET j = j + 1 // Update first
    IF j % 2 == 0
        CONTINUE
    END IF
    PRINTLN j
END WHILE

Error: Mixing Integer and Float in Condition

NEW INT x = 1
NEW FLOAT limit = 10.0
WHILE x < limit // Type error! Cannot compare Integer and Float
    PRINTLN x
    SET x = x + 1
END WHILE
// Correct: Use same data type
NEW INT y = 1
NEW INT max = 10
WHILE y < max
    PRINTLN y
    SET y = y + 1
END WHILE