3

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
    }
Dan.M
  • 71
  • 1
  • 3
    I dont know ballerina.. but I've just googled for "ballerina for loop statement" and got the answer.. did you do the same? Don't think so – B001ᛦ Jul 05 '18 at 09:10

3 Answers3

6

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);    
    }   
}
user272735
  • 10,473
  • 9
  • 65
  • 96
Sameera Jayasoma
  • 1,545
  • 8
  • 12
  • 1
    In Ballerina 1.0.5 this has the non-obvious limitation that the integer range expressions only increment. I.e. `foreach var i in 9...0 { io:println(i); } compiles but prints nothing. – user272735 Dec 15 '19 at 12:34
2

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
}
Tharik Kanaka
  • 2,490
  • 6
  • 31
  • 54
1

According to Ballerina 0.990.2, variable type should be declared.

    foreach int i in 0 ... 9 {
        //some logic
}