2.5.3 While Loop

Different from a for loop, a while loop continues to execute a block of code as long as a specified condition remains true. This means that the number of iterations is not predetermined; instead, it depends on the state of the condition being evaluated. The syntax is

# Syntax of while loop
while (CONDITION) {
    # Code block to be executed
}

The CONDITION could be a logical value, or a command resulting logical value. The same example of for loop above, example 4, also can be implemented through a while loop.

# Example 7
# Initialize the starting number
number = 3
# While loop to print numbers divisible by 3 up to 50
while(number <= 50){
  print(number)      # Print the current number
  number = number + 3  # Move to the next multiple of 3
}

Previous page | Lecture 2 Homepage | Next page

© 2024 Xijia Liu. All rights reserved.
Logo