Loop
Introduction
The Wave language provides loops to handle situations where the same code needs to be executed multiple times. Loops are used to continually execute code while a specific condition is met or for a set number of repetitions.
This allows for expressing repetitive tasks with concise and clear code without the need to repeatedly write the same logic. Wave supports both condition-based and count-based looping, along with keywords to control flow during the loop.
This section explains how to use while and for loops, as well as the break and continue keywords, which control loop flow.
while loop
The while loop repeatedly executes a block of code as long as the given condition evaluates to true.
The loop terminates as soon as the condition becomes false.
This method is suitable for situations where the number of repetitions is unclear and you need to repeat until a specific condition is met.
Basic Structure
The basic structure of the while loop in Wave is as follows.
while (condition) {
// code to repeat
}
The condition must evaluate to a bool, and you can write one or more statements inside the code block enclosed in braces {}.
Example: Print numbers from 0 to 4
var i :i32 = 0;
while (i < 5) {
println("i is {}.", i);
i = i + 1;
}
In this example, the loop runs as long as the variable i is less than 5.
In each iteration, the current value is printed, and the value of i is incremented by 1 so that the condition eventually becomes false.
for loop
The for loop is a type of loop suitable for use when the number of iterations is relatively clear.
By defining the initial value, condition expression, and increment/decrement in one go, the flow of the loop can be clearly expressed.
Because all the elements needed to control the loop are gathered in one place, it is easy to understand the loop structure at a glance.
Basic Structure
for (초기화; 조건식; 증감식) {
// 반복할 코드
}
Wave의 for 초기화는 여러 형태를 지원합니다.
- 암시적
var타입 초기화 var/let mut/const선언 초기화- 일반 식 초기화 (기존 변수 재사용)
예제 1: 암시적 타입 초기화
for (i :i32 = 1; i <= 5; i += 1) {
println("i = {}", i);
}