Is there a for loop in ballerina like the for loop in java. I could only find foreach and while loop in the Ballerina Documentation.
for(int i=0; i<10; i++){
//some logic
}
Is there a for loop in ballerina like the for loop in java. I could only find foreach and while loop in the Ballerina Documentation.
for(int i=0; i<10; i++){
//some logic
}
Ballerina language has two looping constructs: while
and foreach
.
The while
statement executes the while-block until the boolean expression evaluates to false
.
The foreach
statement iterates over a sequence of items. Executes the foreach-block for each and every item in the sequence.
Your requirement is to iterate over an ordered sequence of numbers. Ballerina support integer range expressions which create arrays of integers. e.g. 0...9 produces the range 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. You can find more on integer ranges here
Here is the foreach
with integer ranges.
import ballerina/io;
function main (string... args) {
foreach var i in 0...9 {
io:println(i);
}
}
No it doesn't have a for loop. Unlike in Java same could be achieved with ballerina foreach easily with closed integer ranges as below.
foreach i in 0 ... 9 {
//some logic
}
According to Ballerina 0.990.2, variable type should be declared.
foreach int i in 0 ... 9 {
//some logic
}